I don't know why vichuploaderBundle not upload files - symfony

In my Symfony 3.4 project (vich/uploader-bundle: "^1.4"), I need to upload 3 kinds of files and for two of them it's work, but for the third even if i use the same process it doesn't work...? When the form is submitted, i get this exception:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'document_name' cannot be null
when i dumped, i can see that my Setter "vichuploader document name" not work and can't persisted.
This is the context:
*Everythings is ok on my local version...Files are uploaded but on my production version it's doesn't work.
*I have one Entity (NoteFrais) with OneToOne relation with another Entity (Justificatif).
*The Justificatif entity has the #vich\uploadable annotation
I followed the documentation, read many tuto, ask question on stackverflow, cleared cache and updated doctrine schema many times, tried many things...
******config.yml********
parameters:
locale: fr
app.path.logos: /uploads/logos
app.path.imports: /uploads/imports
app.path.documents: /uploads/documents
vich_uploader:
db_driver: orm
mappings:
logo:
uri_prefix: '%app.path.logos%'
upload_destination: '%kernel.root_dir%/../web%app.path.logos%' //========IT'S WORK FINE FOR THIS ONE==========//
namer: vich_uploader.namer_uniqid
inject_on_load: false
delete_on_update: true
delete_on_remove: true
import:
uri_prefix: '%app.path.imports%'
upload_destination: '%kernel.root_dir%/../web%app.path.imports%' //=========IT'S WORK FINE THIS ONE=========//
namer: vich_uploader.namer_uniqid
# inject_on_load: true important!!
inject_on_load: false
delete_on_update: true
delete_on_remove: true
document:
uri_prefix: '%app.path.documents%'
upload_destination: '%kernel.root_dir%/../web%app.path.documents%'
namer: vich_uploader.namer_uniqid
# inject_on_load: true important!!
inject_on_load: false
delete_on_update: true
delete_on_remove: true
******JustificatifType*******
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('justificatifFile', FileType::class, array( //========= I TRIED WITH FILETYPE OR VICHFILETYPE =======//
//'data_class' => null, //======== NOTE:USALLY I USE TO FILETYPE AND IT'S WORK FINE ==============//
'label' => false,
'required' => true,
'attr' => array(
'class' => 'NoteFraisBootstrapFileInput',
'type' => 'file',
'placeholder' => 'Selectionner un justificatif (jpeg, png, jpg, pdf)',
'data-preview-file-type' => 'text',
'data-allowed-file-extensions' => '["jpeg", "png", "jpg", "pdf"]',
)
));
}
******NoteFraisType**********
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//=======OTHERS FIELDS===========//
->add('justificatif', JustificatifType::class, array(
'required' => false));
}
*****Justificatif.php (Entity)*****
<?php
namespace MKG\MystiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Justificatif
*
* #ORM\Table(name="justificatif")
* #ORM\Entity(repositoryClass="MKG\MystiBundle\Repository\JustificatifRepository")
* #vich\Uploadable
*/
class Justificatif
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="document", fileNameProperty="documentName")
*
* #var File
*/
private $justificatifFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $documentName;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
/**
* Constructor
*/
public function __construct()
{
$this->updatedAt = new \DateTime();
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|UploadedFile $justificatif
*/
public function setJustificatifFile(File $justificatif = null)
{
$this->justificatifFile = $justificatif;
if ($justificatif) {
$this->updatedAt = new \DateTime('now');
}
}
/**
* #return File|null
*/
public function getJustificatifFile()
{
return $this->justificatifFile;
}
/**
*
* #param $documentName
*
* #return $this
*/
public function setDocumentName($documentName)
{
$this->documentName = $documentName;
return $this;
}
/**
* #return string|null
*/
public function getDocumentName()
{
return $this->documentName;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return Justificatif
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
}
*******NoteFrais (Entity)*********
<?php
namespace MKG\MystiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* NoteFrais
*
* #ORM\Table(name="note_frais")
* #ORM\Entity(repositoryClass="MKG\MystiBundle\Repository\NoteFraisRepository")
*/
class NoteFrais
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="MKG\MystiBundle\Entity\Mission", cascade={"persist"})
* #ORM\JoinColumn(name="mission_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
*/
private $mission;
/**
* #ORM\ManyToOne(targetEntity="MKG\MystiBundle\Entity\CodeComptable", cascade={"persist"})
* #ORM\JoinColumn(name="compte_comptable_id", referencedColumnName="id", onDelete="SET NULL", nullable=true)
*/
private $compteComptable;
/**
* #var string
*
* #ORM\Column(name="montant_defraiement_max", type="string", length=255, nullable=false)
*/
private $montantDefraiementMax;
/**
* #var string
*
* #ORM\Column(name="refacturation_client", type="string", length=255, nullable=true)
*/
private $refacturationClient;
/**
* #var string
*
* #ORM\Column(name="total_defraiement", type="string", length=255, nullable=true)
*/
private $totalDefraiement;
/**
* #var string
*
* #ORM\Column(name="total_refacturation", type="string", length=255, nullable=true)
*/
private $totalRefacturation;
/**
* #var string
*
* #ORM\Column(name="compte_avances_et_acomptes", type="string", length=255, nullable=true)
*/
private $compteAvancesEtAcomptes;
/**
* #var string
*
* #ORM\Column(name="admin_current_user", type="string", length=255, nullable=true)
*/
private $currentUser;
/**
* #var string
*
* #ORM\Column(name="code_affaire", type="string", length=255, nullable=true)
*/
private $codeAffaire;
/**
* #var string
*
* #ORM\Column(name="etat", type="string", length=255, nullable=true)
*/
private $etat;
/**
* #ORM\OneToOne(targetEntity="Justificatif", cascade={"persist"})
* #ORM\JoinColumn(name="justificatif_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
*/
private $justificatif;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreation", type="datetime")
*/
private $dateCreation;
public function __construct() {
$this->dateCreation = new \DateTime;
$this->etat = "0";
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set montantDefraiementMax
*
* #param string $montantDefraiementMax
*
* #return NoteFrais
*/
public function setMontantDefraiementMax($montantDefraiementMax)
{
$this->montantDefraiementMax = $montantDefraiementMax;
return $this;
}
/**
* Get montantDefraiementMax
*
* #return string
*/
public function getMontantDefraiementMax()
{
return $this->montantDefraiementMax;
}
/**
* Set refacturationClient
*
* #param string $refacturationClient
*
* #return NoteFrais
*/
public function setRefacturationClient($refacturationClient)
{
$this->refacturationClient = $refacturationClient;
return $this;
}
/**
* Get refacturationClient
*
* #return string
*/
public function getRefacturationClient()
{
return $this->refacturationClient;
}
/**
* Set compteAvancesEtAcomptes
*
* #param string $compteAvancesEtAcomptes
*
* #return NoteFrais
*/
public function setCompteAvancesEtAcomptes($compteAvancesEtAcomptes)
{
$this->compteAvancesEtAcomptes = $compteAvancesEtAcomptes;
return $this;
}
/**
* Get compteAvancesEtAcomptes
*
* #return string
*/
public function getCompteAvancesEtAcomptes()
{
return $this->compteAvancesEtAcomptes;
}
/**
* Set currentUser
*
* #param string $currentUser
*
* #return NoteFrais
*/
public function setCurrentUser($currentUser)
{
$this->currentUser = $currentUser;
return $this;
}
/**
* Get currentUser
*
* #return string
*/
public function getCurrentUser()
{
return $this->currentUser;
}
/**
* Set codeAffaire
*
* #param string $codeAffaire
*
* #return NoteFrais
*/
public function setCodeAffaire($codeAffaire)
{
$this->codeAffaire = $codeAffaire;
return $this;
}
/**
* Get codeAffaire
*
* #return string
*/
public function getCodeAffaire()
{
return $this->codeAffaire;
}
/**
* Set etat
*
* #param string $etat
*
* #return NoteFrais
*/
public function setEtat($etat)
{
$this->etat = $etat;
return $this;
}
/**
* Get etat
*
* #return string
*/
public function getEtat()
{
return $this->etat;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
*
* #return NoteFrais
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set mission
*
* #param \MKG\MystiBundle\Entity\Mission $mission
*
* #return NoteFrais
*/
public function setMission(\MKG\MystiBundle\Entity\Mission $mission = null)
{
$this->mission = $mission;
return $this;
}
/**
* Get mission
*
* #return \MKG\MystiBundle\Entity\Mission
*/
public function getMission()
{
return $this->mission;
}
/**
* Set compteComptable
*
* #param \MKG\MystiBundle\Entity\CodeComptable $compteComptable
*
* #return NoteFrais
*/
public function setCompteComptable(\MKG\MystiBundle\Entity\CodeComptable $compteComptable = null)
{
$this->compteComptable = $compteComptable;
return $this;
}
/**
* Get compteComptable
*
* #return \MKG\MystiBundle\Entity\CodeComptable
*/
public function getCompteComptable()
{
return $this->compteComptable;
}
/**
* Set justificatif
*
* #param \MKG\MystiBundle\Entity\Justificatif $justificatif
*
* #return NoteFrais
*/
public function setJustificatif(\MKG\MystiBundle\Entity\Justificatif $justificatif = null)
{
$this->justificatif = $justificatif;
return $this;
}
/**
* #return File
*/
public function getJustificatif()
{
return $this->justificatif;
}
/**
* Set totalDefraiement
*
* #param string $totalDefraiement
*
* #return NoteFrais
*/
public function setTotalDefraiement($totalDefraiement)
{
$this->totalDefraiement = $totalDefraiement;
return $this;
}
/**
* Get totalDefraiement
*
* #return string
*/
public function getTotalDefraiement()
{
return $this->totalDefraiement;
}
/**
* Set totalRefacturation
*
* #param string $totalRefacturation
*
* #return NoteFrais
*/
public function setTotalRefacturation($totalRefacturation)
{
$this->totalRefacturation = $totalRefacturation;
return $this;
}
/**
* Get totalRefacturation
*
* #return string
*/
public function getTotalRefacturation()
{
return $this->totalRefacturation;
}
}
********* newAction in NoteFraisController *********
/**
* Creates a new noteFrais entity.
*
*/
public function newAction(Request $request)
{
// === RECUPERE LA MISSION
$em = $this->getDoctrine()->getManager();
$mission = $em->getRepository('MKGMystiBundle:Mission')->findOneBy(array('id' => $request->get('idMission')));
$lignesNoteFrais = $em->getRepository('MKGMystiBundle:NoteFrais')->findBy(array('mission' => $mission->getId()));
$noteFrais = new Notefrais();
$form = $this->createForm('MKG\MystiBundle\Form\NoteFraisType', $noteFrais);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//$noteFrais->setMission($mission);
$em = $this->getDoctrine()->getManager();
$em->persist($noteFrais);
//dump($noteFrais);die();
$em->flush();
$this->addFlash('notice', 'Une ligne a été ajouté à la note de frais!');
return $this->redirect($request->getUri());
}
return $this->render('#MKGMysti/Notefrais/new.html.twig', array(
'lignesNoteFrais' => $lignesNoteFrais,
'mission' => $mission,
'noteFrais' => $noteFrais,
'form' => $form->createView(),
));
}
Thank you very much your time!!!!

Related

Foreign Key (don't want to edit it) error

I have a little problem i don't know why i can't edit my foreign key ($idProfile) but i can edit an other value from the database :
I can change the value enable for exemple but not the idProfile when i try to change it i have this error : "An instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface must be injected in FOS\RestBundle\View\ViewHandler to render templates." don't know if that can help thx for help guys :p
my Profile controller :
/**
* Creates a new profile entity.
*
* #Route("/new/{id}", name="profile_new")
*/
public function newProfileAction(Request $request, User $user)
{
$loggedAs = $this->getUser();
$username = $loggedAs->getUsername();
$profile = new Profile();
$form = $this->createForm(ProfileType::class, $profile);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$profile->setLastConnexion(new \DateTime('now'));
$profile->setCreatedAccount(new \DateTime('now'));
$em = $this->getDoctrine()->getManager();
$em->persist($profile);
$em->flush();
$user->setEnabled('1');
$user->setIdLocation($profile->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_list');
}
return $this->render('admin/user/new_profile.html.twig', array(
'profile' => $profile,
'form' => $form->createView(),
'username' => $username,
));
}
My userEntity :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table(name="user", uniqueConstraints=
{#ORM\UniqueConstraint(name="user_id_uindex", columns={"id"}),
#ORM\UniqueConstraint(name="user_username_uindex", columns=
{"username"})}, indexes={#ORM\Index(name="user_profile_id_fk",
columns={"id_profile"}), #ORM\Index(name="user_localisation_id_fk",
columns={"id_location"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #UniqueEntity("username", groups={"Default", "Patch"})
*/
class User implements UserInterface
{
const ROLE_USER = 'ROLE_USER';
const ROLE_ADMIN = 'ROLE_ADMIN';
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #Serializer\Groups({"Default", "Deserialize", "user_detail"})
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=32)
* #Serializer\Groups({"Default", "Deserialize", "user_detail"})
*/
protected $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
* #Serializer\Groups({"Deserialize", "user_detail"})
* #Assert\Regex(
* pattern="/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{7,}/",
* message="Password must be seven characters long and contain at least one digit code, upper case, and lower case letter!",
* groups={"Default", "Patch"}
* )
*/
protected $password;
/**
* #var boolean
*
* #ORM\Column(name="enabled", type="boolean", nullable=false)
*/
protected $enabled = '1';
/**
* #var \AppBundle\Entity\Localisation
*
* #ORM\ManyToOne(targetEntity="Localisation")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_location", referencedColumnName="id")
* })
*/
protected $idLocation;
/**
* #var \AppBundle\Entity\Profile
*
* #ORM\ManyToOne(targetEntity="Profile")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_profile", referencedColumnName="id")
* })
*/
protected $idProfile;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="User", inversedBy="idUserOne")
* #ORM\JoinTable(name="friend",
* joinColumns={
* #ORM\JoinColumn(name="id_user_one", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_user_two", referencedColumnName="id")
* }
* )
*/
protected $idUserTwo;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", inversedBy="idUserInvited")
* #ORM\JoinTable(name="list_invited",
* joinColumns={
* #ORM\JoinColumn(name="id_user_invited", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_place_invited", referencedColumnName="id")
* }
* )
*/
protected $idPlaceInvited;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", mappedBy="idUserPresent")
*/
protected $idPlacePresent;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", inversedBy="idUserPlace")
* #ORM\JoinTable(name="user_place",
* joinColumns={
* #ORM\JoinColumn(name="id_user_place", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_place_place", referencedColumnName="id")
* }
* )
*/
protected $idPlacePlace;
/**
* #var array
* #ORM\Column(type="simple_array", length=200)
* #Serializer\Exclude()
*/
protected $roles;
/**
* Constructor
*/
public function __construct()
{
$this->idUserTwo = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlaceInvited = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlacePresent = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlacePlace = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id)
{
$this->id = $id;
}
/**
* #return string|null
*/
public function getUsername()
{
return $this->username;
}
/**
* #param string $username
*/
public function setUsername(string $username)
{
$this->username = $username;
}
/**
* #return string|null
*/
public function getPassword()
{
return $this->password;
}
/**
* #param string $password
*/
public function setPassword(string $password)
{
$this->password = $password;
}
/**
* #return bool
*/
public function isEnabled()
{
return $this->enabled;
}
/**
* #param bool $enabled
*/
public function setEnabled(bool $enabled)
{
$this->enabled = $enabled;
}
/**
* #return mixed
*/
public function getIdLocation()
{
return $this->idLocation;
}
/**
* #param mixed $idLocation
*/
public function setIdLocation($idLocation)
{
$this->idLocation = $idLocation;
}
/**
* #return mixed
*/
public function getIdProfile()
{
return $this->idProfile;
}
/**
* #param mixed $idProfile
*/
public function setIdProfile($idProfile)
{
$this->idProfile = $idProfile;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdUserTwo()
{
return $this->idUserTwo;
}
/**
* #param \Doctrine\Common\Collections\Collection $idUserTwo
*/
public function setIdUserTwo(\Doctrine\Common\Collections\Collection $idUserTwo)
{
$this->idUserTwo = $idUserTwo;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlaceInvited()
{
return $this->idPlaceInvited;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlaceInvited
*/
public function setIdPlaceInvited(\Doctrine\Common\Collections\Collection $idPlaceInvited)
{
$this->idPlaceInvited = $idPlaceInvited;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlacePresent()
{
return $this->idPlacePresent;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlacePresent
*/
public function setIdPlacePresent(\Doctrine\Common\Collections\Collection $idPlacePresent)
{
$this->idPlacePresent = $idPlacePresent;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlacePlace()
{
return $this->idPlacePlace;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlacePlace
*/
public function setIdPlacePlace(\Doctrine\Common\Collections\Collection $idPlacePlace)
{
$this->idPlacePlace = $idPlacePlace;
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* #return (Role|string)[] The user roles
*/
public function getRoles()
{
return $this->roles;
}
/**
* #param array $roles
*/
public function setRoles(array $roles)
{
$this->roles = $roles;
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* #return string|null The salt
*/
public function getSalt()
{
// TODO: Implement getSalt() method.
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
some screen of data base : [https://ibb.co/iCSnWy
p
[https://ibb.co/cZZedd
p
In this case you'll have to do it this way:
$loggedAs = $this->getUser(); // get the user
$profile = new Profile();
// set up profile variables
// [...]
$profile->setUser($loggedAs); // case 1
// or, depending on your implementation
$loggedAs->addProfile($profile); // case 2
// persist, flush etc
With doctrine the foreign key handling is behind the scenes,
you don't have to worry about them if your mappings are correct
So instead of fkeys, you just attach entities.
Depending on your implementation (the relation can be uni- or bi-directional) you only have to chose one of the 2 cases.
I hope it helps, more here and here.

Symfony foreign keys (How can i edit them ?)

I have a little problem i don't know why i can't edit my foreign key ($idProfile) but i can edit an other value from the database :
I can change the value enable for exemple but not the idProfile when i try to change it i have this error : "An instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface must be injected in FOS\RestBundle\View\ViewHandler to render templates." don't know if that can help thx for help guys :p
In general : I just want to know how can i edit my $id_profile to link it with my profile entity
my Profile controller :
/**
* Creates a new profile entity.
*
* #Route("/new/{id}", name="profile_new")
*/
public function newProfileAction(Request $request, User $user)
{
$loggedAs = $this->getUser();
$username = $loggedAs->getUsername();
$profile = new Profile();
$form = $this->createForm(ProfileType::class, $profile);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$profile->setLastConnexion(new \DateTime('now'));
$profile->setCreatedAccount(new \DateTime('now'));
$em = $this->getDoctrine()->getManager();
$em->persist($profile);
$em->flush();
$user->setEnabled('1');
$user->setIdLocation($profile->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_list');
}
return $this->render('admin/user/new_profile.html.twig', array(
'profile' => $profile,
'form' => $form->createView(),
'username' => $username,
));
}
My userEntity :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table(name="user", uniqueConstraints=
{#ORM\UniqueConstraint(name="user_id_uindex", columns={"id"}),
#ORM\UniqueConstraint(name="user_username_uindex", columns=
{"username"})}, indexes={#ORM\Index(name="user_profile_id_fk",
columns={"id_profile"}), #ORM\Index(name="user_localisation_id_fk",
columns={"id_location"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #UniqueEntity("username", groups={"Default", "Patch"})
*/
class User implements UserInterface
{
const ROLE_USER = 'ROLE_USER';
const ROLE_ADMIN = 'ROLE_ADMIN';
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #Serializer\Groups({"Default", "Deserialize", "user_detail"})
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=32)
* #Serializer\Groups({"Default", "Deserialize", "user_detail"})
*/
protected $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
* #Serializer\Groups({"Deserialize", "user_detail"})
* #Assert\Regex(
* pattern="/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{7,}/",
* message="Password must be seven characters long and contain at least one digit code, upper case, and lower case letter!",
* groups={"Default", "Patch"}
* )
*/
protected $password;
/**
* #var boolean
*
* #ORM\Column(name="enabled", type="boolean", nullable=false)
*/
protected $enabled = '1';
/**
* #var \AppBundle\Entity\Localisation
*
* #ORM\ManyToOne(targetEntity="Localisation")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_location", referencedColumnName="id")
* })
*/
protected $idLocation;
/**
* #var \AppBundle\Entity\Profile
*
* #ORM\ManyToOne(targetEntity="Profile")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_profile", referencedColumnName="id")
* })
*/
protected $idProfile;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="User", inversedBy="idUserOne")
* #ORM\JoinTable(name="friend",
* joinColumns={
* #ORM\JoinColumn(name="id_user_one", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_user_two", referencedColumnName="id")
* }
* )
*/
protected $idUserTwo;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", inversedBy="idUserInvited")
* #ORM\JoinTable(name="list_invited",
* joinColumns={
* #ORM\JoinColumn(name="id_user_invited", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_place_invited", referencedColumnName="id")
* }
* )
*/
protected $idPlaceInvited;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", mappedBy="idUserPresent")
*/
protected $idPlacePresent;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", inversedBy="idUserPlace")
* #ORM\JoinTable(name="user_place",
* joinColumns={
* #ORM\JoinColumn(name="id_user_place", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_place_place", referencedColumnName="id")
* }
* )
*/
protected $idPlacePlace;
/**
* #var array
* #ORM\Column(type="simple_array", length=200)
* #Serializer\Exclude()
*/
protected $roles;
/**
* Constructor
*/
public function __construct()
{
$this->idUserTwo = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlaceInvited = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlacePresent = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlacePlace = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id)
{
$this->id = $id;
}
/**
* #return string|null
*/
public function getUsername()
{
return $this->username;
}
/**
* #param string $username
*/
public function setUsername(string $username)
{
$this->username = $username;
}
/**
* #return string|null
*/
public function getPassword()
{
return $this->password;
}
/**
* #param string $password
*/
public function setPassword(string $password)
{
$this->password = $password;
}
/**
* #return bool
*/
public function isEnabled()
{
return $this->enabled;
}
/**
* #param bool $enabled
*/
public function setEnabled(bool $enabled)
{
$this->enabled = $enabled;
}
/**
* #return mixed
*/
public function getIdLocation()
{
return $this->idLocation;
}
/**
* #param mixed $idLocation
*/
public function setIdLocation($idLocation)
{
$this->idLocation = $idLocation;
}
/**
* #return mixed
*/
public function getIdProfile()
{
return $this->idProfile;
}
/**
* #param mixed $idProfile
*/
public function setIdProfile($idProfile)
{
$this->idProfile = $idProfile;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdUserTwo()
{
return $this->idUserTwo;
}
/**
* #param \Doctrine\Common\Collections\Collection $idUserTwo
*/
public function setIdUserTwo(\Doctrine\Common\Collections\Collection $idUserTwo)
{
$this->idUserTwo = $idUserTwo;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlaceInvited()
{
return $this->idPlaceInvited;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlaceInvited
*/
public function setIdPlaceInvited(\Doctrine\Common\Collections\Collection $idPlaceInvited)
{
$this->idPlaceInvited = $idPlaceInvited;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlacePresent()
{
return $this->idPlacePresent;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlacePresent
*/
public function setIdPlacePresent(\Doctrine\Common\Collections\Collection $idPlacePresent)
{
$this->idPlacePresent = $idPlacePresent;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlacePlace()
{
return $this->idPlacePlace;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlacePlace
*/
public function setIdPlacePlace(\Doctrine\Common\Collections\Collection $idPlacePlace)
{
$this->idPlacePlace = $idPlacePlace;
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* #return (Role|string)[] The user roles
*/
public function getRoles()
{
return $this->roles;
}
/**
* #param array $roles
*/
public function setRoles(array $roles)
{
$this->roles = $roles;
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* #return string|null The salt
*/
public function getSalt()
{
// TODO: Implement getSalt() method.
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
some screen of data base : [https://ibb.co/iCSnWy
p
[https://ibb.co/cZZedd
p
you defined profile as type of \AppBundle\Entity\Profile this is the right way to work with doctrine. No to understand what is the difference in your entities and your database...
In the entities you need to set the entity not the id. Doctrine will then passt the id in the database, and when you get the entity from doctrine it will parse the id to an entity.
This means:
$user->setIdLocation($profile); //<-- set the entity
$profil = $user->getIdLocation(); // get the profile not the id

How to get the mapping entity in PrePersist LifecycleEvent within a form in Symfony2 for a OneToOne relationship

I have two entities in my code: Session and SessionPicture.
There is a OneToOne relationship between Session and SessionPicture. Session is the mapping entity and SessionPicture the inverse one.
I have a SessionType form, which embeds a SessionPictureType form. I would like the user to be able to upload an image for each session when he fille the SessionType form.
The SessionPicture class contains a file attribute (UploadedFile class) and I have used LifecycleEvents to upload the image file and save it in the right directory.
This is what my code looks for the session class:
/**
* Session
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Session
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\SessionPicture", cascade={"persist", "remove"}, inversedBy="session")
* #ORM\JoinColumn(name="session_picture_id", referencedColumnName="id", nullable=true)
*/
private $sessionPicture;
/**
* Set name
*
* #param string $name
*
* #return Session
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set sessionPicture
*
* #param \MyBundle\Entity\SessionPicture $sessionPicture
*
* #return Session
*/
public function setSessionPicture(MyBundle\Entity\SessionPicture $sessionPicture = null)
{
$this->sessionPicture = $sessionPicture;
return $this;
}
/**
* Get sessionPicture
*
* #return \MyBundle\Session\SessionPicture
*/
public function getSessionPicture()
{
return $this->sessionPicture;
}
And this one for my SessionPicture class:
/**
* SessionPicture
*
* #ORM\Table(name="at_session_picture")
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionPictureRepository")
* #ORM\HasLifecycleCallbacks()
*/
class SessionPicture
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="extension", type="string", length=255)
*/
private $extension;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #var string
*
* #ORM\Column(name="path", type="string", length=255, nullable=true)
*/
private $path;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\Session", mappedBy="sessionPicture")
*/
private $session;
public $file;
private $fileNameForRemove;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set extension
*
* #param string $extension
*
* #return SessionPicture
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* #return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* Set alt
*
* #param string $alt
*
* #return SessionPicture
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* Set path
*
* #param string $path
*
* #return SessionPicture
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set session
*
* #param \MyBundle\Entity\Session $session
*
* #return SessionPicture
*/
public function setSession(\NyBundle\Entity\Session $session = null)
{
$this->session = $session;
return $this;
}
/**
* Get session
*
* #return \MyBundle\Entity\Session
*/
public function getSession()
{
return $this->session;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$name = $this->getSession()->getName();
$this->extension = (string)$extension;
$this->alt = (string)strval($name);
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
$this->path = $this->alt.'.'.$this->extension;
if ($this->file === null)
return ;
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
I would like to draw your attention on the preUpload() function in my SessionPicture.php
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$name = $this->getSession()->getName();
$this->extension = (string)$extension;
$this->alt = (string)strval($name);
}
I use this function to give my SessionPicture the same name as the mapping session name and save it in my server with the same name after form validation. Below is an excerpt of my SessionType.php. As you can notice, I embedded a SessionPictureType inside my SessionType.
class SessionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'required' => true
))
->add('sessionPicture', new SessionPictureType(), array(
'required' => false
))
->add('Submit', 'submit');
When I validate this form, I get the error
Error: Call to a member function getName() on a non-object
It seems that in my preUpload() function in my SessionPicture.php, trying to call $this->getSession() returns nothing instead of returning the mapping session. The same applies if I use $this->getSession() in the upload function.
Can anyone help with that? How can I get the mapping entity before or during form validation and use it in my inversing entity to update its attributes?
Many thanks in advance.

Error on update query symfony2

I generated the CRUD for the entity Evenement(event) , which is working. But now I want to update a field in another entity called notification everytime an Evenement is added. Each Evenement has a categorie
Evenement.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Mql14\mqlmeBundle\Entity\Evenement
*
* #ORM\Table(name="evenement")
* #ORM\Entity
*/
class Evenement
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $nom
*
* #ORM\Column(name="nom", type="string", length=45, nullable=true)
*/
private $nom;
/**
* #var datetime $date
*
* #ORM\Column(name="date", type="datetime", nullable=true)
*/
private $date;
/**
* #var string $description
*
* #ORM\Column(name="description", type="string", length=400, nullable=true)
*/
private $description;
/**
* #var integer $ticket
*
* #ORM\Column(name="Ticket", type="integer", nullable=true)
*/
private $ticket;
/**
* #var User
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="evenement")
*/
private $user;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie", inversedBy="evenement")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="categorie_id", referencedColumnName="id")
* })
*/
private $categorie;
/**
* #var Lieu
*
* #ORM\ManyToOne(targetEntity="Lieu")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="lieu_id", referencedColumnName="id")
* })
*/
private $lieu;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set date
*
* #param datetime $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* Get date
*
* #return datetime
*/
public function getDate()
{
return $this->date;
}
/**
* Set description
*
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set ticket
*
* #param integer $ticket
*/
public function setTicket($ticket)
{
$this->ticket = $ticket;
}
/**
* Get ticket
*
* #return integer
*/
public function getTicket()
{
return $this->ticket;
}
/**
* Add user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function addUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user[] = $user;
}
/**
* Get user
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Set categorie
*
* #param Mql14\mqlmeBundle\Entity\Categorie $categorie
*/
public function setCategorie(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$this->categorie = $categorie;
}
/**
* Get categorie
*
* #return Mql14\mqlmeBundle\Entity\Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
/**
* Set lieu
*
* #param Mql14\mqlmeBundle\Entity\Lieu $lieu
*/
public function setLieu(\Mql14\mqlmeBundle\Entity\Lieu $lieu)
{
$this->lieu = $lieu;
}
/**
* Get lieu
*
* #return Mql14\mqlmeBundle\Entity\Lieu
*/
public function getLieu()
{
return $this->lieu;
}
public function getCategorieId(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$idc= $categorie->getId();
return $idc;
}
}
Categorie.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mql14\mqlmeBundle\Entity\Categorie
*
* #ORM\Table(name="categorie")
* #ORM\Entity
*/
class Categorie
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $nomcat
*
* #ORM\Column(name="nomCat", type="string", length=45, nullable=true)
*/
private $nomcat;
/**
* #var string $photo
*
* #ORM\Column(name="photo", type="string", length=45, nullable=true)
*/
private $photo;
/**
* #var $evenement
*
* #ORM\OneToMany(targetEntity="Evenement", mappedBy="categorie")
*/
private $evenement;
/**
* #var User
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="categorie")
*/
private $user;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nomcat
*
* #param string $nomcat
*/
public function setNomcat($nomcat)
{
$this->nomcat = $nomcat;
}
/**
* Get nomcat
*
* #return string
*/
public function getNomcat()
{
return $this->nomcat;
}
/**
* Set photo
*
* #param string $photo
*/
public function setPhoto($photo)
{
$this->photo = $photo;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Add user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function addUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user[] = $user;
}
/**
* Get user
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Add evenement
*
* #param Mql14\mqlmeBundle\Entity\Categorie $evenement
*/
public function addEvenement(\Mql14\mqlmeBundle\Entity\Evenement $evenement)
{
$this->evenement[] = $evenement;
}
/**
* Get evenement
*
* #return Doctrine\Common\Collections\Collection
*/
public function getEvenement()
{
return $this->evenement;
}
}
Notification.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mql14\mqlmeBundle\Entity\Notification
*
* #ORM\Table(name="notification")
* #ORM\Entity
*/
class Notification
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $etat
*
* #ORM\Column(name="etat", type="integer", nullable=true)
*/
private $etat;
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="User_id", referencedColumnName="id")
*
* })
*/
private $user;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="Categorie_id", referencedColumnName="id")
*
* })
*/
private $categorie;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set etat
*
* #param string $etat
*/
public function setEtat($etat)
{
$this->etat = $etat;
}
/**
* Get etat
*
* #return string
*/
public function getEtat()
{
return $this->etat;
}
/**
* Set user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function setUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user = $user;
}
/**
* Get user
*
* #return Mql14\mqlmeBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set categorie
*
* #param Mql14\mqlmeBundle\Entity\Categorie $categorie
*/
public function setCategorie(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$this->categorie = $categorie;
}
/**
* Get categorie
*
* #return Mql14\mqlmeBundle\Entity\Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
}
In the createAction that was generated after the execution of the CRUD for the Evenement entity I added the update query :
public function createAction(Request $request)
{
$entity = new Evenement();
$request = $this->getRequest();
$form = $this->createForm(new EvenementType(), $entity);
$form->bindRequest($request);
$entity->upload();
$cat=$entity->getCategorie();
if ($cat) {
$catn = $cat->getNomCat();
$query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie LIKE :catn ' );
$query->setParameter('categorie', $catn);
$query->execute();
}
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('mql14mqlme_adminshow', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
And the error I'm getting is this:
[Semantical Error] line 0, col 61 near 'categorie LIKE': Error:
Invalid PathExpression. Must be a StateFieldPathExpression.
You set the wrong parameter in the update query.
On this line:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery(
'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1
WHERE n.categorie LIKE :catn' );
$query->setParameter('categorie', $catn);
$query->execute();
It should be:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery(
'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1
WHERE n.categorie LIKE :catn' );
$query->setParameter('catn', $catn);
$query->execute();
n.categorie is an entity (of type Mql14\mqlmeBundle\Entity\Categorie) and you can't compare entities using LIKE.
Try replacing LIKE with =.
Change
UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie LIKE :catn
To
UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie = :catn

Form nulling a value when user doesn't supply it

Reading this page I've setup a form to handle PATCH requests.
I've a Player entity:
<?php
namespace Acme\PlayerBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\PlayerBundle\Entity\Player
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\PlayerBundle\Entity\PlayerRepository")
*/
class Player
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotBlank()
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="players")
* #ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* #ORM\ManyToOne(targetEntity="Acme\TeamBundle\Entity\Team", inversedBy="players")
* #ORM\JoinColumn(nullable=false)
* #Assert\NotBlank()
*/
private $team;
/**
* #var integer $shirtNumber
*
* #ORM\Column(name="shirtNumber", type="smallint")
* #Assert\NotBlank()
*/
private $shirtNumber;
/**
* #var integer $vsid
*
* #ORM\Column(name="vsid", type="integer", nullable=true)
*/
private $vsid;
/**
* #var string $firstname
*
* #ORM\Column(name="firstname", type="string", length=255, nullable=true)
*/
private $firstname;
/**
* #var string $lastname
*
* #ORM\Column(name="lastname", type="string", length=255, nullable=true)
*/
private $lastname;
/**
* #var boolean $deleted
*
* #ORM\Column(name="deleted", type="boolean")
*/
private $deleted = false;
/**
* #var integer $role
*
* #ORM\Column(type="integer", nullable=true)
*/
private $role;
/**
* Create the user salt
*/
public function __construct()
{
//TODO: just for test
$this->uniqueId = substr(uniqid(), 0, 14);
}
/* MANAGED BY DOCTRINE, DON'T EDIT */
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Player
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set shirtNumber
*
* #param integer $shirtNumber
* #return Player
*/
public function setShirtNumber($shirtNumber)
{
$this->shirtNumber = $shirtNumber;
return $this;
}
/**
* Get shirtNumber
*
* #return integer
*/
public function getShirtNumber()
{
return $this->shirtNumber;
}
/**
* Set vsid
*
* #param integer $vsid
* #return Player
*/
public function setVsid($vsid)
{
$this->vsid = $vsid;
return $this;
}
/**
* Get vsid
*
* #return integer
*/
public function getVsid()
{
return $this->vsid;
}
/**
* Set firstname
*
* #param string $firstname
* #return Player
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return Player
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Player
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Set role
*
* #param integer $role
* #return Player
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Get role
*
* #return integer
*/
public function getRole()
{
return $this->role;
}
/**
* Set owner
*
* #param Acme\UserBundle\Entity\User $owner
* #return Player
*/
public function setOwner(\Acme\UserBundle\Entity\User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return Acme\UserBundle\Entity\User
*/
public function getOwner()
{
return $this->owner;
}
/**
* Set team
*
* #param Acme\TeamBundle\Entity\Team $team
* #return Player
*/
public function setTeam(\Acme\TeamBundle\Entity\Team $team)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* #return Acme\TeamBundle\Entity\Team
*/
public function getTeam()
{
return $this->team;
}
}
and a Team entity:
<?php
namespace Acme\TeamBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\TeamBundle\Entity\Team
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\TeamBundle\Entity\TeamRepository")
*/
class Team
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $uniqueId
*
* #ORM\Column(name="uniqueId", type="string", length=15)
*/
private $uniqueId;
/**
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="teams")
* #ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=50)
* #Assert\NotBlank()
*/
private $name;
/**
* #var string $homeColor
*
* #ORM\Column(name="homeColor", type="string", length=7, nullable=true)
*/
private $homeColor;
/**
* #var string $awayColor
*
* #ORM\Column(name="awayColor", type="string", length=7, nullable=true)
*/
private $awayColor;
/**
* #var string $homeShirt
*
* #ORM\Column(name="homeShirt", type="string", length=50, nullable=true)
*/
private $homeShirt;
/**
* #var string $awayShirt
*
* #ORM\Column(name="awayShirt", type="string", length=50, nullable=true)
*/
private $awayShirt;
/**
* #var string $teamLogo
*
* #ORM\Column(name="teamLogo", type="string", length=50, nullable=true)
*/
private $teamLogo;
/**
* #var boolean $deleted
*
* #ORM\Column(name="deleted", type="boolean")
*/
private $deleted = false;
/**
* #ORM\OneToMany(targetEntity="Acme\PlayerBundle\Entity\Player", mappedBy="team", cascade={"persist", "remove"})
*/
private $players;
/**
* #ORM\OneToMany(targetEntity="Acme\MatchBundle\Entity\Match", mappedBy="homeTeam")
*/
private $homeMatches;
/**
* #ORM\OneToMany(targetEntity="Acme\MatchBundle\Entity\Match", mappedBy="awayTeam")
*/
private $awayMatches;
/**
* Create the user salt
*/
public function __construct()
{
$this->players = new ArrayCollection();
$this->homeMatches = new ArrayCollection();
$this->awayMatches = new ArrayCollection();
//TODO: just for test
$this->uniqueId = substr(uniqid(), 0, 14);
}
public function getMatches()
{
return array_merge($this->awayMatches->toArray(), $this->homeMatches->toArray());
}
/* MANAGED BY DOCTRINE, DON'T EDIT */
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set uniqueId
*
* #param string $uniqueId
* #return Team
*/
public function setUniqueId($uniqueId)
{
$this->uniqueId = $uniqueId;
return $this;
}
/**
* Get uniqueId
*
* #return string
*/
public function getUniqueId()
{
return $this->uniqueId;
}
/**
* Set name
*
* #param string $name
* #return Team
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set homeColor
*
* #param string $homeColor
* #return Team
*/
public function setHomeColor($homeColor)
{
$this->homeColor = $homeColor;
return $this;
}
/**
* Get homeColor
*
* #return string
*/
public function getHomeColor()
{
return $this->homeColor;
}
/**
* Set awayColor
*
* #param string $awayColor
* #return Team
*/
public function setAwayColor($awayColor)
{
$this->awayColor = $awayColor;
return $this;
}
/**
* Get awayColor
*
* #return string
*/
public function getAwayColor()
{
return $this->awayColor;
}
/**
* Set homeShirt
*
* #param string $homeShirt
* #return Team
*/
public function setHomeShirt($homeShirt)
{
$this->homeShirt = $homeShirt;
return $this;
}
/**
* Get homeShirt
*
* #return string
*/
public function getHomeShirt()
{
return $this->homeShirt;
}
/**
* Set awayShirt
*
* #param string $awayShirt
* #return Team
*/
public function setAwayShirt($awayShirt)
{
$this->awayShirt = $awayShirt;
return $this;
}
/**
* Get awayShirt
*
* #return string
*/
public function getAwayShirt()
{
return $this->awayShirt;
}
/**
* Set teamLogo
*
* #param string $teamLogo
* #return Team
*/
public function setTeamLogo($teamLogo)
{
$this->teamLogo = $teamLogo;
return $this;
}
/**
* Get teamLogo
*
* #return string
*/
public function getTeamLogo()
{
return $this->teamLogo;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Team
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Add players
*
* #param Acme\PlayerBundle\Entity\Player $players
* #return Team
*/
public function addPlayer(\Acme\PlayerBundle\Entity\Player $players)
{
$this->players[] = $players;
return $this;
}
/**
* Remove players
*
* #param Acme\PlayerBundle\Entity\Player $players
*/
public function removePlayer(\Acme\PlayerBundle\Entity\Player $players)
{
$this->players->removeElement($players);
}
/**
* Get players
*
* #return Doctrine\Common\Collections\Collection
*/
public function getPlayers()
{
return $this->players;
}
/**
* Add homeMatches
*
* #param Acme\MatchBundle\Entity\Match $homeMatches
* #return Team
*/
public function addHomeMatche(\Acme\MatchBundle\Entity\Match $homeMatches)
{
$this->homeMatches[] = $homeMatches;
return $this;
}
/**
* Remove homeMatches
*
* #param Acme\MatchBundle\Entity\Match $homeMatches
*/
public function removeHomeMatche(\Acme\MatchBundle\Entity\Match $homeMatches)
{
$this->homeMatches->removeElement($homeMatches);
}
/**
* Get homeMatches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getHomeMatches()
{
return $this->homeMatches;
}
/**
* Add awayMatches
*
* #param Acme\MatchBundle\Entity\Match $awayMatches
* #return Team
*/
public function addAwayMatche(\Acme\MatchBundle\Entity\Match $awayMatches)
{
$this->awayMatches[] = $awayMatches;
return $this;
}
/**
* Remove awayMatches
*
* #param Acme\MatchBundle\Entity\Match $awayMatches
*/
public function removeAwayMatche(\Acme\MatchBundle\Entity\Match $awayMatches)
{
$this->awayMatches->removeElement($awayMatches);
}
/**
* Get awayMatches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getAwayMatches()
{
return $this->awayMatches;
}
/**
* Set owner
*
* #param Acme\UserBundle\Entity\User $owner
* #return Team
*/
public function setOwner(\Acme\UserBundle\Entity\User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return Acme\UserBundle\Entity\User
*/
public function getOwner()
{
return $this->owner;
}
}
Now I've created a player form class with the app/console and I've edited the team field to be an instance of the Team entity, this way:
<?php
namespace Acme\PlayerBundle\Form;
use Acme\TeamBundle\Entity\TeamRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PlayerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('shirtNumber')
->add('firstname')
->add('lastname')
->add('role')
->add('team', 'entity', array(
'class' => 'AcmeTeamBundle:Team',
'query_builder' => function(TeamRepository $er) {
$query = $er->createQueryBuilder('t');
return $query;
}
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\PlayerBundle\Entity\Player',
'csrf_protection' => false
));
}
public function getName()
{
return 'player';
}
}
And this is the relevant part of my controller:
/**
* Create a new player
*
* #Route(".{_format}", name="api_player_create")
* #Method("POST")
* #ApiDoc(
* description="Create a new player",
* statusCodes={
* 201="Player created and informations are returned",
* 400="Missing informations",
* 403="The user isn't authorized"
* },
* input="Acme\PlayerBundle\Form\PlayerType",
* return="Acme\PlayerBundle\Entity\Player"
* )
*
* #return Renders the player just created
*/
public function createPlayerAction()
{
return $this->processForm(new Player());
}
/**
* Edit a player
*
* #param integer $id The id of the player to be created
*
* #Route("/{id}.{_format}", name="api_player_patch", requirements={ "id": "\d+" })
* #Method("PATCH")
* #ApiDoc(
* description="Edit a player",
* statusCodes={
* 200="Player is updated",
* 400="Missing informations",
* 403="The user isn't authorized"
* },
* input="Acme\PlayerBundle\Form\PlayerType",
* return="Acme\PlayerBundle\Entity\Player"
* )
*
* #return Renders the player just edited
*/
public function editPlayerAction(Player $player)
{
if ($player->getOwner() != $this->getUser()) {
throw new ApiException\PermissionDeniedException;
}
return $this->processForm($player);
}
/**
* Function to handle a form to create/edit a player
*
* #param Player $player The player to be created or edited
*
* #return Api Response
*/
private function processForm(Player $player)
{
/**
* Check if the player is new (to be created) or we're editing a player
*/
$statusCode = is_null($player->getId()) ? 201 : 200;
$form = $this->createForm(new PlayerType(), $player);
$form->bind($this->getRequest());
if ($form->isValid()) {
if($player->getTeam()->getOwner() != $this->getUser()) {
throw new ApiException\PermissionDeniedException;
}
$player->setOwner($this->getUser());
$this->entityManager->persist($player);
$this->entityManager->flush();
return $this->apiResponse->getResponse($player, $statusCode);
}
return $this->apiResponse->getResponse($form, 400, 'Missing arguments');
}
The player creation works fine, the player edit doesn't, when the user makes the api request, passing the ID in the url and the name of the player I get:
Catchable Fatal Error: Argument 1 passed to Acme\PlayerBundle\Entity\Player::setTeam() must be an instance of Acme\TeamBundle\Entity\Team, null given, called in /Volumes/Dati/Users/alessandro/Sites/acme-api/vendor/symfony/symfony/src/Symfony/Component/Form/Util/PropertyPath.php on line 538 and defined in /Volumes/Dati/Users/alessandro/Sites/acme-api/src/Acme/PlayerBundle/Entity/Player.php line 278
Seems that form is trying to set the Team to null, why?
I've tried both sending and not the team as the form parameters but it doesn't work.
Any clue?
Figured it out that null unsent fields in the form is the default behaviour in symfony.
There is an open request for partial form binding in symfony. For now a guy created a form event subscriber that adds the missing fields with the actual values:
https://gist.github.com/3720535
This is his code:
<?php
namespace Foo;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
/**
* Changes Form->bind() behavior so that it treats not set values as if they
* were sent unchanged.
*
* Use when you don't want fields to be set to NULL when they are not displayed
* on the page (or to implement PUT/PATCH requests).
*/
class PatchSubscriber implements EventSubscriberInterface
{
public function onPreBind(FormEvent $event)
{
$form = $event->getForm();
$clientData = $event->getData();
$clientData = array_replace($this->unbind($form), $clientData ?: array());
$event->setData($clientData);
}
/**
* Returns the form's data like $form->bind() expects it
*/
protected function unbind($form)
{
if ($form->hasChildren()) {
$ary = array();
foreach ($form->getChildren() as $name => $child) {
$ary[$name] = $this->unbind($child);
}
return $ary;
} else {
return $form->getClientData();
}
}
static public function getSubscribedEvents()
{
return array(
FormEvents::PRE_BIND => 'onPreBind',
);
}
}
to add to the form you have to edit the buildForm method in the form class:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$subscriber = new PatchSubscriber();
$builder->addEventSubscriber($subscriber);
$builder->add('name');
....
}
In this case you're ok to use the PATCH REST requests to edit an entity just by the sent fields

Resources