Symfony Increment value in Database - database

I'm working on a website where people can download wallpapers.
I have a table 'Images' with a 'Download' column.
I would like to increment the value on this field for each time people click on the 'download button'
I'm usingg Symphony 6 with EasyAdmin-bundle & Twig
Can someone help me to make a query to increment this value ?
Thank you
enter image description here
<?php
namespace App\Entity;
use App\Repository\ImagesRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ImagesRepository::class)]
class Images
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255)]
private ?string $image = null;
#[ORM\Column(nullable: true)]
private ?int $downloads = null;
#[ORM\ManyToOne(inversedBy: 'images')]
private ?Wallpapers $wallpaper = null;
#[ORM\ManyToOne(inversedBy: 'device')]
private ?Devices $devices = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
public function getDownloads(): ?int
{
return $this->downloads;
}
public function setDownloads(?int $downloads): self
{
$this->downloads = $downloads;
return $this;
}
public function getWallpaper(): ?Wallpapers
{
return $this->wallpaper;
}
public function setWallpaper(?Wallpapers $wallpaper): self
{
$this->wallpaper = $wallpaper;
return $this;
}
public function getDevices(): ?Devices
{
return $this->devices;
}
public function setDevices(?Devices $devices): self
{
$this->devices = $devices;
return $this;
}
public function __toString(): string
{
return $this->image;
}
}
<div class="row">
{% for item in wallpapers.getImages() %}
<div class="col">
<img src="/uploads/wps/{{ item.image }}" class="card"/>
<button>Download</button>
</div>
{% endfor %}
</div>
I tried many example but as it's my first experience with Symphony is a bit complicated to understand all the concept of Query Builder

You must create a new controller with route like this:
#[Route('/downloads/{entity}', name:'downloads')
public function downloads(
Entity $entity,
EntityManagerInterface $em
){
$entity->setDownload($entity->getDownload() + 1);
$em->persist($entity);
$em->flush();
return $this->file($entity->getImage(), 'name_file.ext');
}
in your twig file you can redirect to this func with entity id param.
Function is an example you must use your entity class and get file content to download something.

Related

Codeigniter load array results in different functions

I have more function where I need to read $data['getContacts'] more times, the code working correctly, but there is a clean and different method for call it?
thanks!
class AppController extends CI_Controller {
public $id;
function __construct() {
parent::__construct();
$this->id = !empty($this->input->post('id')) ? (int)$this->input->post('id', TRUE) : '';
}
public function restoreCredit()
{
$data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?
if($data['getContacts']->status != false) :
$this->appmodel->restoreCredit($this->id);
endif;
}
public function createRandToken()
{
$data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?
if(!empty($data['getContacts']) && $data['getContacts']->token == false):
$this->appmodel->setRandUserToken($this->id);
endif;
}
}
Your could define a function getContacts. It will fetch $contacts first time from the DB, after that it will always returned the fetched Contacts.
<?php
class AppController extends CI_Controller
{
public $id;
public $contacts;
function __construct()
{
parent::__construct();
$this->id = !empty($this->input->post('id')) ? (int) $this->input->post('id', TRUE) : '';
}
public function getContacts() {
if( !empty ( $this->contacts) ) { //If its populated return from here.
return $this->contacts;
}
$this->contacts = $this->appmodel->getContacts($this->id);
return $this->contacts;
}
public function restoreCredit()
{
$data['getContacts'] = $this->getContacts();
if ($data['getContacts']->status != false) :
$this->appmodel->restoreCredit($this->id);
endif;
}
public function createRandToken()
{
$data['getContacts'] = $this->getContacts();
if (!empty($data['getContacts']) && $data['getContacts']->token == false) :
$this->appmodel->setRandUserToken($this->id);
endif;
}
}

Disabling foreign key constraint in Laravel

Attempting to disable foreign key constraint. This is what the create users table looks like as of right now. Attempted to use the method disableForeignKeyConstraints, but no luck when migrating. I also tried using the enableForeignKeyConstraints method after the create schema, but that also didn't help. Any help on this would be greatly appreciated.
Blog Post Controller:
public function index(){
$blog_posts = BlogPost::all();
return view('whatsnew.index', compact("blog_posts"));
}
public function show($blog_post){
$blog_post = BlogPost::find($blog_post);
return view('whatsnew.show', compact("blog_post"));
}
public function create(){
return view('whatsnew.create');
}
public function store(BlogPostRequest $request){
$formData = $request->all();
BlogPost::create($formData);
return redirect('whatsnew');
}
public function edit($blog_post){
$blog_post = BlogPost::findOrFail($blog_post);
return view('whatsnew.edit', compact("blog_post"));
}
public function update(BlogPostRequest $request, $blog_post){
$formData = $request->all();
$blog_post = BlogPost::findOrFail($blog_post);
$blog_post->update($formData);
return redirect('whatsnew');
}
public function __construct(){
$this->middleware('auth', ['only' =>['create', 'edit', 'destroy']]);
}
public function destroy(BlogPost $blog_post){
$blog_post->delete();
return redirect('whatsnew');
}

Does Sonata admin work with self generated entity ids?

Does Sonata admin work self generated entity ids? I have the following entity which uses the Uuid library to generate its own id but when I try to create a new Group using Sonata admin it gets confused and thinks I am editing an existing entity and not creating a new one.
<?php declare(strict_types=1);
namespace App\Entity;
use App\Value\StartEndTime;
use App\Exception\GroupInactiveException;
use Ramsey\Uuid\Uuid;
use Assert\Assertion;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
class Group
{
/** #var string */
private $id;
/** #var string */
private $title;
/** #var string */
private $description;
/** #var User */
private $admin;
/** #var Collection */
private $members;
/** #var Collection */
private $invites;
/** #var StartEndTime */
private $startEndTime;
/** #var StartEndTime */
private $eventStartEndTime;
public function __construct()
{
$this->id = Uuid::uuid4()->toString();
$this->members = new ArrayCollection();
$this->invites = new ArrayCollection();
}
public function getId(): string
{
return $this->id;
}
public function getTitle()
{
return $this->title;
}
public function setTitle(string $title)
{
Assertion::notEmpty($title, 'Title is not specified');
$this->title = $title;
return $this;
}
public function getDescription()
{
return $this->description;
}
public function setDescription(string $description)
{
Assertion::notEmpty($description, 'Description is not specified');
$this->description = $description;
return $this;
}
public function getStartEndTime()
{
return $this->startEndTime;
}
public function setStartEndTime(StartEndTime $startEndTime)
{
$this->startEndTime = $startEndTime;
return $this;
}
public function getEventStartEndTime()
{
return $this->eventStartEndTime;
}
public function setEventStartEndTime(StartEndTime $startEndTime)
{
$this->eventStartEndTime = $startEndTime;
return $this;
}
}

Laravel Cart and controller

I am having issue with the route and controller.
The error code consist of sql column not found which is looking for column id from items table. Which im quite curious due to the differences with my migration.
CartController.php
namespace App\Http\Controllers;
use App\Cart;
use App\CartItem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CartController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function addItem ($itemNo){
$cart = Cart::where('user_id',Auth::user()->id)->first();
if(!$cart){
$cart = new Cart();
$cart->user_id=Auth::user()->id;
$cart->save();
}
$cartItem = new Cartitem();
$cartItem->itemNo=$itemNo;
$cartItem->cart_id= $cart->id;
$cartItem->save();
return redirect('/cart');
}
public function showCart(){
$cart = Cart::where('user_id',Auth::user()->id)->first();
if(!$cart){
$cart = new Cart();
$cart->user_id=Auth::user()->id;
$cart->save();
}
$items = $cart->cartItems;
$total=0;
foreach($items as $item){
$total+=$item->product->price;
}
return view('cart.view',['items'=>$items,'total'=>$total]);
}
public function removeItem($id){
CartItem::destroy($id);
return redirect('/cart');
}
}
ItemController.php
<?php
namespace App\Http\Controllers;
use App\Item;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
class ItemController extends Controller
{
public function index(){
$items = item::all();
return view('admin.items',['items' => $items]);
}
public function destroy($itemNo){
item::destroy($itemNo);
return redirect('/admin/items');
}
public function newItem(){
return view('admin.new');
}
public function add() {
$file = Request::file('file');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new \App\File();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
$Item = new Item();
$Item->file_id=$entry->id;
$Item->itemName =Request::input('name');
$Item->itemDescription =Request::input('description');
$Item->price =Request::input('price');
$Item->imageurl =Request::input('imageurl');
$Item->save();
return redirect('admin/items');
}
}

Saving data from DDBB into AS class

i am trying to make a "game" in Flex similar to Shake&Fidget. I'm saving all the user data in a mysql database and I retrieve the data using ZendFramework (PHP).
I thought of saving all the user and character info I'm going to need into am AS class so I can use that data in every view.
The data recived from the database is correct. I was able to load it in my app labbels but everytime i changed views it had to ask it again, so i thought of making this classes in order to just ask once for the information.
I'll post here the files so it's all more clear.
ViewNavigatorAplication.mxml
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
firstView="views.RotrHomeView"
persistNavigatorState="true">
<fx:Script>
<![CDATA[
import flash.net.registerClassAlias;
import valueObjects.Character;
registerClassAlias("Character", valueObjects.Character);
]]>
</fx:Script>
The first View goes to the login screen, it works OK. So i'll go to the view that loads and "tries" to show the character data.
char_panel.mxml
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:usersservice1="services.usersservice1.*"
title="Character Sheet"
viewActivate="char_panel_viewActivateHandler()">
<fx:Script>
<![CDATA[
import mx.binding.utils.*;
import mx.events.FlexEvent;
import mx.rpc.events.ResultEvent;
import valueObjects.Character;
//[Bindable]protected var character:Character = new Character();
public function updateStats():void{
var str:int = parseInt(getGlobalStatsResult.lastResult.globalSTR) + parseInt(getCharacterStatsResult.lastResult.str);
var dex:int = parseInt(getGlobalStatsResult.lastResult.globalDEX) + parseInt(getCharacterStatsResult.lastResult.dex);
var intel:int = parseInt(getGlobalStatsResult.lastResult.globalINT) + parseInt(getCharacterStatsResult.lastResult.intel);
var cha:int = parseInt(getGlobalStatsResult.lastResult.globalCHA) + parseInt(getCharacterStatsResult.lastResult.cha);
var sta:int = parseInt(getGlobalStatsResult.lastResult.global_VIT) + parseInt(getCharacterStatsResult.lastResult.vit);
data.modStats(str,intel,cha,sta,dex)
data.showStats(lb_show_str,lb_show_dex,lb_show_int,lb_show_cha,lb_show_vit);
//character.showStats(lb_show_str,lb_show_dex,lb_show_int,lb_show_cha,lb_show_vit);
}
public function char_panel_viewActivateHandler():void{
if(!data){
data = new Character();
}
getCharacterStatsResult.token = usersService1.getCharacterStats("user01");
getGearListResult.addEventListener(ResultEvent.RESULT,onResult);
getGearListResult.token = usersService1.getGearList();
}
public function onStatsResult(event:ResultEvent):void{
if(getGlobalStatsResult.lastResult.globalSTR != null){
updateStats();
}
}
public function onResult(event:ResultEvent):void{
if(getGearListResult.lastResult[0].itemName != null){
getGlobalStatsResult.addEventListener(ResultEvent.RESULT, onStatsResult);
getGlobalStatsResult.token = usersService1.getGlobalStats("user01");
currentState = "Character";
}
}
]]>
</fx:Script>
<s:states>
<s:State name="Loading"/>
<s:State name="Character"/>
</s:states>
<fx:Declarations>
<s:CallResponder id="getCharacterStatsResult"/>
<s:CallResponder id="getGearListResult"/>
<s:CallResponder id="getGlobalStatsResult"/>
<usersservice1:UsersService1 id="usersService1"/>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Label id="lb_show_str" includeIn="Character" x="119" y="46" text=""/>
<s:BusyIndicator includeIn="Loading" left="172" right="171" top="148" bottom="424"
horizontalCenter="0" verticalCenter="-138"/>
<s:Label id="lb_show_int" includeIn="Character" x="119" y="90"/>
<s:Label id="lb_show_cha" includeIn="Character" x="119" y="139"/>
<s:Label id="lb_show_vit" includeIn="Character" x="119" y="191"/>
<s:Label id="lb_show_dex" includeIn="Character" x="119" y="243"/>
As for the AS classes:
Character.as
package valueObjects{
import mx.data.ChangedItems;
import mx.messaging.channels.StreamingAMFChannel;
import spark.components.Label;
import spark.skins.spark.StackedFormHeadingSkin;
[Bindable]
public class Character
{
private var _name:String;
private var _stats:FinalStats;
private var _gear:GearList;
public function Character()
{
this._stats = new FinalStats();
this._gear = new GearList();
}
public function modStats(str:int,intel:int,cha:int,sta:int,dex:int):void{
this._stats.modStr(str);
this._stats.modInt(intel);
this._stats.modCha(cha);
this._stats.modVit(sta);
this._stats.modDex(dex);
}
public function getStats():Array{
var aStats:Array;
aStats["str"]=this._stats.getStr();
aStats["int"]=this._stats.getInt();
aStats["cha"]=this._stats.getCha();
aStats["sta"]=this._stats.getVit();
aStats["dex"]=this._stats.getDex();
return aStats;
}
public function setName(charName:String):void{
this._name = charName;
}
public function getName():String{
return this._name;
}
public function showStats(lbSTR:Label, lbDEX:Label, lbINT:Label, lbCHA:Label, lbVIT:Label):void{
lbSTR.text = "" + this._stats.getStr();
lbDEX.text = "" + this._stats.getDex();
lbINT.text = "" + this._stats.getInt();
lbCHA.text = "" + this._stats.getCha();
lbVIT.text = "" + this._stats.getVit();
}
}}
FinalStats.as
package valueObjects{
public class FinalStats
{
private var str:int = 0;
private var intel:int = 0;
private var cha:int = 0;
private var sta:int = 0;
private var dex:int = 0;
public function FinalStats()
{
}
public function getStr():int{
return this.str;
}
public function modStr(x:int):void{
this.str+=x;
}
public function getDex():int{
return this.dex;
}
public function modDex(x:int):void{
this.dex+=x;
}
public function getInt():int{
return this.intel;
}
public function modInt(x:int):void{
this.intel+=x;
}
public function getCha():int{
return this.cha;
}
public function modCha(x:int):void{
this.cha+=x;
}
public function getVit():int{
return this.sta;
}
public function modVit(x:int):void{
this.sta+=x;
}
}
}
And the last one GearList.as
package valueObjects{
import mx.data.ChangedItems;
import mx.messaging.channels.StreamingAMFChannel;
import spark.components.Label;
import spark.skins.spark.StackedFormHeadingSkin;
public class GearList
{
private var _headID:String;
private var _shoulderID:String;
private var _chestID:String;
private var _bracersID:String;
private var _glovesID:String;
private var _pantsID:String;
private var _bootsID:String;
private var _main_handID:String;
private var _off_handID:String;
public function GearList()
{
}
public function showStats(lbHead:Label, lbShoulder:Label, lbChest:Label, lbBracer:Label, lbGlove:Label, lbPants:Label, lbBoots:Label, lbMainHand:Label, lbOffHand:Label):void{
lbHead.text = ""+this._headID;
lbShoulder.text = ""+this._shoulderID;
lbChest.text = ""+this._chestID;
lbBracer.text = ""+this._bracersID;
lbGlove.text = ""+this._glovesID;
lbPants.text = ""+this._pantsID;
lbBoots.text = ""+this._bootsID;
lbMainHand.text = ""+this._main_handID;
lbOffHand.text = ""+this._off_handID;
}
public function getOff_handID():String
{
return _off_handID;
}
public function setOff_handID(value:String):void
{
_off_handID = value;
}
public function getMain_handID():String
{
return _main_handID;
}
public function setMain_handID(value:String):void
{
_main_handID = value;
}
public function getBootsID():String
{
return _bootsID;
}
public function setBootsID(value:String):void
{
_bootsID = value;
}
public function getPantsID():String
{
return _pantsID;
}
public function setPantsID(value:String):void
{
_pantsID = value;
}
public function getGlovesID():String
{
return _glovesID;
}
public function setGlovesID(value:String):void
{
_glovesID = value;
}
public function getBracersID():String
{
return _bracersID;
}
public function setBracersID(value:String):void
{
_bracersID = value;
}
public function getChestID():String
{
return _chestID;
}
public function setChestID(value:String):void
{
_chestID = value;
}
public function getShoulderID():String
{
return _shoulderID;
}
public function setShoulderID(value:String):void
{
_shoulderID = value;
}
public function getHeadID():String
{
return _headID;
}
public function setHeadID(value:String):void
{
_headID = value;
}
}}
If you are still here you have all my respect :D
When i try it out, i get the following error. I've tried in char_panel.mxml using Character::modStats(...) instead of data.modStats i'll put the error log under this one.
Error log when using data.modStats(...)
TypeError: Error #1006: modStats is not a function.
at views::char_panel/updateStats()[C:\Users\Zebrah\Rotr\Rotr\src\views\char_panel.mxml:23]
at views::char_panel/onStatsResult()[C:\Users\Zebrah\Rotr\Rotr\src\views\char_panel.mxml:39]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.rpc::CallResponder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\CallResponder.as:122]
at mx.rpc::AsyncToken/http://www.adobe.com/2006/flex/mx/internal::applyResult()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AsyncToken.as:239]
at mx.rpc.events::ResultEvent/http://www.adobe.com/2006/flex/mx/internal::callTokenResponders()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\events\ResultEvent.as:207]
at mx.rpc::AbstractOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AbstractOperation.as:244]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:318]
at mx.rpc::Responder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\Responder.as:56]
at mx.rpc::AsyncRequest/acknowledge()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:84]
at NetConnectionMessageResponder/resultHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:552]
at mx.messaging::MessageResponder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\messaging\MessageResponder.as:235]
Error Log using Character::modStats(...)
Error: Error #1034: Type Coercion failed: cannot convert valueObjects::Character$ to Namespace.
at views::char_panel/updateStats()[C:\Users\Zebrah\Rotr\Rotr\src\views\char_panel.mxml:23]
at views::char_panel/onStatsResult()[C:\Users\Zebrah\Rotr\Rotr\src\views\char_panel.mxml:39]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.rpc::CallResponder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\CallResponder.as:122]
at mx.rpc::AsyncToken/http://www.adobe.com/2006/flex/mx/internal::applyResult()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AsyncToken.as:239]
at mx.rpc.events::ResultEvent/http://www.adobe.com/2006/flex/mx/internal::callTokenResponders()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\events\ResultEvent.as:207]
at mx.rpc::AbstractOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AbstractOperation.as:244]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:318]
at mx.rpc::Responder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\Responder.as:56]
at mx.rpc::AsyncRequest/acknowledge()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:84]
at NetConnectionMessageResponder/resultHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:552]
at mx.messaging::MessageResponder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\messaging\MessageResponder.as:235]
Thanks in advance to anyone that get so far in this help cry :D i'd apreciate any sugestions that you can make.
ok so the reason it doesn't work with data is that event though you said
data = new Character();
data is still actually an object (that now looks like a character). to make it work
var myChar:Character = Character(data); // cast it to a Character and it now knows the method
myChar.modStats()
the reason the other call didn't work is the way you called it:
Character::modStats(...)
This say look for a method called modStats in the namespace Character. Instead call this
character.modStats()
and it will work.
You Sir are my personal Hero :D, i've just tried it and it shows the data.
I changed the constructor for the character in Character.AS like this:
public function Character(obj:Object)
{
this._stats = new FinalStats();
this._gear = new GearList();
}
I'm not entirely sure if this is correct, but as you mentioned in your answer:
var myChar:Character = Character(data);
I supose i'll have to use that data object to initialice myChar...am i right? Well, later when i have the time i'll try to add new views and buttons to go through views and see if the data is there :D

Resources