How to get an email from a imbricated form into swiftmailer? - forms

I want to insert an email from an imbricated form into swiftmailer.
The email is the "sendTo" section of the swifmailer.
As I tried it doesn't work. The form is sent but no email is recieved.
How can I have it? Do you have an idea?
So the controller, the action to send the form and then the email is :
/**
* Creates a new Reservations entity.
*
*/
public function createAction(Request $request)
{
$entity = new Reservations();
$emailPool = new Pool();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
// Get the sender's email adress
$sender = $entity->getEmail();
// Get the recipients' emails adresses (pool address)
$emailPool = $this->$pool->getEmailPool(); // mal codé >> trouver la bonne méthode
// Send email
$message = \Swift_Message::newInstance()
->setSubject('Demande de véhicule')
->setFrom($sender)
->setTo($emailPool) // email à entrer Vehicule.Esplanade#eurelien.fr
// Indicate "High" priority
->setPriority(2)
->setBody(
$this->renderView(
// View in app/Resources/views/emails/demandereservation.html.twig
'emails/demandereservation.html.twig', array(
'reservations' => $entity)),
'text/html'
);
$this->get('mailer')->send($message);
$this->get('session')->getFlashBag()->Add('notice', 'Votre réservation a bien été envoyée');
return $this->redirect($this->generateUrl('reservations_show', array('id' => $entity->getId())));
}
return $this->render('CDCarsBundle:Reservations:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
The form (with the imbricated form (pool)) is :
<?php
namespace CD\CarsBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use CD\CarsBundle\Entity\Reservations;
use CD\CarsBundle\Entity\Vehicules;
use Application\Sonata\UserBundle\Entity\User;
class ReservationsType extends AbstractType
{
// Form for the entity "Reservations" which is used to build the car's booking form
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nomAgent', null, array(
'label' => 'Nom de l\'agent',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('prenomAgent', null, array(
'label' => 'Prénom de l\'agent',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('dga', null, array(
'label' => 'D.G.A',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('direction', null, array(
'label' => 'Direction',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('email', null, array(
'label' => 'Email',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('telephone', null, array(
'label' => 'Téléphone',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
// ajouter le pool
->add('pool', new PoolType())
->add('heureDebut', null, array(
'label' => 'Date et heure de début',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
->add('heureFin', null, array(
'label' => 'Date et heure de fin',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
// ajouter type véhicule
->add('besoin', 'choice', array(
'label' => 'Type',
'choices' => array(
'V.L' => 'V.L',
'V.L.E' => 'V.L.E',
'V.U' => 'V.U',
'velo' => 'Vélo')
)
)
// ajouter nombre personnes
->add('nombrePersonne', 'choice', array(
'label' => 'Nombre de personne',
'choices' => array(
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5 +')
)
)
// ajouter demande de remisage -> si coché dévoiler champs pour le remisage (dématérialisation) => à faire dans la vue
->add('remisage', null, array('required' => false))
->add('adresseRemisage', null, array('label' => 'Adresse'))
->add('dateDebutRemisage', null, array(
'label' => 'Du',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
->add('dateFinRemisage', null, array(
'label' => 'au',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
->add('emailDirecteur', null, array(
'label' => 'Email du directeur',
'attr' => array(
'placeholder' => 'email#email.fr',
))
)
->add('destination', null, array('label' => 'Destination'))
->add('motifRdv', null, array('required' => false))
->add('motifFormation', null, array('required' => false))
->add('motifReunion', null, array('required' => false))
->add('motifCollecte', null, array('required' => false))
->add('motifInstallation', null, array('required' => false))
->add('motifProgrammation', null, array('required' => false))
->add('motifDepannage', null, array('required' => false))
->add('motifVad', null, array('required' => false))
->add('motifAutre', null, array('label' => 'Autre motif'))
->add('conducteur', null, array('required' => false))
// ajouter mandataire -> si coché dévoiler champs pour le mandataire (email...) => à faire dans la vue
->add('mandataire', null, array('required' => false))
->add('nomMandataire', null, array('label' => 'Votre nom'))
->add('prenomMandataire', null, array('label' => 'Votre prénom'))
->add('emailMandataire', null, array('label' => 'Votre émail'))
->add('honneur', null, array('required' => true))
;
}
The Pool form is :
<?php
namespace CD\CarsBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use CD\CarsBundle\Entity\Pool;
use CD\CarsBundle\Entity\Vehicules;
class PoolType extends AbstractType
{
// Form for the entity "pool"
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
/*->add('nom', null, array(
'label' => 'Nom',
))*/
->add('emailPool', null, array(
'label' => 'Email du pool duquel vous dépendez',
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CD\CarsBundle\Entity\Pool'
));
}
/**
* #return string
*/
public function getName()
{
return 'cd_carsbundle_pool';
}
}
The pool entity is :
<?php
namespace CD\CarsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pool
*/
class Pool
{
// Code for the entity "Pool"
public function __toString()
{
return (string) $this->getEmailPool();
}
//YML GENERATED CODE
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $nom;
/**
* #var string
*/
private $emailPool;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $vehicules;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $user;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $reservations;
/**
* Constructor
*/
public function __construct()
{
$this->vehicules = new \Doctrine\Common\Collections\ArrayCollection();
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
$this->reservations = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
* #return Pool
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set emailPool
*
* #param string $emailPool
* #return Pool
*/
public function setEmailPool($emailPool)
{
$this->emailPool = $emailPool;
return $this;
}
/**
* Get emailPool
*
* #return string
*/
public function getEmailPool()
{
return $this->emailPool;
}
/**
* Add vehicules
*
* #param \CD\CarsBundle\Entity\Vehicules $vehicules
* #return Pool
*/
public function addVehicule(\CD\CarsBundle\Entity\Vehicules $vehicules)
{
$this->vehicules[] = $vehicules;
return $this;
}
/**
* Remove vehicules
*
* #param \CD\CarsBundle\Entity\Vehicules $vehicules
*/
public function removeVehicule(\CD\CarsBundle\Entity\Vehicules $vehicules)
{
$this->vehicules->removeElement($vehicules);
}
/**
* Get vehicules
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVehicules()
{
return $this->vehicules;
}
/**
* Add user
*
* #param \Application\Sonata\UserBundle\Entity\User $user
* #return Pool
*/
public function addUser(\Application\Sonata\UserBundle\Entity\User $user)
{
$this->user[] = $user;
return $this;
}
/**
* Remove user
*
* #param \Application\Sonata\UserBundle\Entity\User $user
*/
public function removeUser(\Application\Sonata\UserBundle\Entity\User $user)
{
$this->user->removeElement($user);
}
/**
* Get user
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Add reservations
*
* #param \CD\CarsBundle\Entity\Reservations $reservations
* #return Pool
*/
public function addReservation(\CD\CarsBundle\Entity\Reservations $reservations)
{
$this->reservations[] = $reservations;
return $this;
}
/**
* Remove reservations
*
* #param \CD\CarsBundle\Entity\Reservations $reservations
*/
public function removeReservation(\CD\CarsBundle\Entity\Reservations $reservations)
{
$this->reservations->removeElement($reservations);
}
/**
* Get reservations
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getReservations()
{
return $this->reservations;
}
}
The reservations entity is :
<?php
namespace CD\CarsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints as Asserts;
/**
* Reservations
*/
class Reservations
{
// Code for the entity "Reservations"
public function __toString()
{
return (string) $this->getId();
return (string) $this->getHeureDebut();
}
// YML GENERATED CODE
/**
* #var integer
*/
private $id;
/**
* #var \DateTime
*/
private $heureDebut;
/**
* #var \DateTime
*/
private $heureFin;
/**
* #var string
*/
private $nomAgent;
/**
* #var string
*/
private $prenomAgent;
/**
* #var string
*/
private $dga;
/**
* #var string
*/
private $direction;
/**
* #var string
*/
private $email;
/**
* #var string
*/
private $telephone;
/**
* #var string
*/
private $destination;
/**
* #var boolean
*/
private $reserve;
/**
* #var boolean
*/
private $annulation;
/**
* #var boolean
*/
private $remisage;
/**
* #var string
*/
private $adresseRemisage;
/**
* #var \DateTime
*/
private $dateDebutRemisage;
/**
* #var \DateTime
*/
private $dateFinRemisage;
/**
* #var string
*/
private $emailDirecteur;
/**
* #var boolean
*/
private $conducteur;
/**
* #var boolean
*/
private $mandataire;
/**
* #var boolean
*/
private $motifRdv;
/**
* #var boolean
*/
private $motifFormation;
/**
* #var boolean
*/
private $motifReunion;
/**
* #var boolean
*/
private $motifCollecte;
/**
* #var boolean
*/
private $motifInstallation;
/**
* #var boolean
*/
private $motifProgrammation;
/**
* #var boolean
*/
private $motifDepannage;
/**
* #var boolean
*/
private $motifVad;
/**
* #var string
*/
private $motifAutre;
/**
* #var string
*/
private $commentaires;
/**
* #var integer
*/
private $nombrePersonne;
/**
* #var string
*/
private $besoin;
/**
* #var string
*/
private $nomMandataire;
/**
* #var string
*/
private $prenomMandataire;
/**
* #var string
*/
private $emailMandataire;
/**
* #var boolean
*/
private $honneur;
/**
* #var boolean
*/
private $traite;
/**
* #var \CD\CarsBundle\Entity\Vehicules
*/
private $vehicules;
/**
* #var \Application\Sonata\UserBundle\Entity\User
*/
private $user;
/**
* #var \CD\CarsBundle\Entity\Pool
*/
private $pool;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set heureDebut
*
* #param \DateTime $heureDebut
* #return Reservations
*/
public function setHeureDebut($heureDebut)
{
$this->heureDebut = $heureDebut;
return $this;
}
/**
* Get heureDebut
*
* #return \DateTime
*/
public function getHeureDebut()
{
return $this->heureDebut;
}
/**
* Set heureFin
*
* #param \DateTime $heureFin
* #return Reservations
*/
public function setHeureFin($heureFin)
{
$this->heureFin = $heureFin;
return $this;
}
/**
* Get heureFin
*
* #return \DateTime
*/
public function getHeureFin()
{
return $this->heureFin;
}
/**
* Set nomAgent
*
* #param string $nomAgent
* #return Reservations
*/
public function setNomAgent($nomAgent)
{
$this->nomAgent = $nomAgent;
return $this;
}
/**
* Get nomAgent
*
* #return string
*/
public function getNomAgent()
{
return $this->nomAgent;
}
/**
* Set prenomAgent
*
* #param string $prenomAgent
* #return Reservations
*/
public function setPrenomAgent($prenomAgent)
{
$this->prenomAgent = $prenomAgent;
return $this;
}
/**
* Get prenomAgent
*
* #return string
*/
public function getPrenomAgent()
{
return $this->prenomAgent;
}
/**
* Set dga
*
* #param string $dga
* #return Reservations
*/
public function setDga($dga)
{
$this->dga = $dga;
return $this;
}
/**
* Get dga
*
* #return string
*/
public function getDga()
{
return $this->dga;
}
/**
* Set direction
*
* #param string $direction
* #return Reservations
*/
public function setDirection($direction)
{
$this->direction = $direction;
return $this;
}
/**
* Get direction
*
* #return string
*/
public function getDirection()
{
return $this->direction;
}
/**
* Set email
*
* #param string $email
* #return Reservations
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set telephone
*
* #param string $telephone
* #return Reservations
*/
public function setTelephone($telephone)
{
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* #return string
*/
public function getTelephone()
{
return $this->telephone;
}
/**
* Set destination
*
* #param string $destination
* #return Reservations
*/
public function setDestination($destination)
{
$this->destination = $destination;
return $this;
}
/**
* Get destination
*
* #return string
*/
public function getDestination()
{
return $this->destination;
}
/**
* Set reserve
*
* #param boolean $reserve
* #return Reservations
*/
public function setReserve($reserve)
{
$this->reserve = $reserve;
return $this;
}
/**
* Get reserve
*
* #return boolean
*/
public function getReserve()
{
return $this->reserve;
}
/**
* Set annulation
*
* #param boolean $annulation
* #return Reservations
*/
public function setAnnulation($annulation)
{
$this->annulation = $annulation;
return $this;
}
/**
* Get annulation
*
* #return boolean
*/
public function getAnnulation()
{
return $this->annulation;
}
/**
* Set remisage
*
* #param boolean $remisage
* #return Reservations
*/
public function setRemisage($remisage)
{
$this->remisage = $remisage;
return $this;
}
/**
* Get remisage
*
* #return boolean
*/
public function getRemisage()
{
return $this->remisage;
}
/**
* Set adresseRemisage
*
* #param string $adresseRemisage
* #return Reservations
*/
public function setAdresseRemisage($adresseRemisage)
{
$this->adresseRemisage = $adresseRemisage;
return $this;
}
/**
* Get adresseRemisage
*
* #return string
*/
public function getAdresseRemisage()
{
return $this->adresseRemisage;
}
/**
* Set dateDebutRemisage
*
* #param \DateTime $dateDebutRemisage
* #return Reservations
*/
public function setDateDebutRemisage($dateDebutRemisage)
{
$this->dateDebutRemisage = $dateDebutRemisage;
return $this;
}
/**
* Get dateDebutRemisage
*
* #return \DateTime
*/
public function getDateDebutRemisage()
{
return $this->dateDebutRemisage;
}
/**
* Set dateFinRemisage
*
* #param \DateTime $dateFinRemisage
* #return Reservations
*/
public function setDateFinRemisage($dateFinRemisage)
{
$this->dateFinRemisage = $dateFinRemisage;
return $this;
}
/**
* Get dateFinRemisage
*
* #return \DateTime
*/
public function getDateFinRemisage()
{
return $this->dateFinRemisage;
}
/**
* Set emailDirecteur
*
* #param string $emailDirecteur
* #return Reservations
*/
public function setEmailDirecteur($emailDirecteur)
{
$this->emailDirecteur = $emailDirecteur;
return $this;
}
/**
* Get emailDirecteur
*
* #return string
*/
public function getEmailDirecteur()
{
return $this->emailDirecteur;
}
/**
* Set vehicules
*
* #param \CD\CarsBundle\Entity\Vehicules $vehicules
* #return Reservations
*/
public function setVehicules(\CD\CarsBundle\Entity\Vehicules $vehicules = null)
{
$this->vehicules = $vehicules;
return $this;
}
/**
* Get vehicules
*
* #return \CD\CarsBundle\Entity\Vehicules
*/
public function getVehicules()
{
return $this->vehicules;
}
/**
* Set user
*
* #param \Application\Sonata\UserBundle\Entity\User $user
* #return Reservations
*/
public function setUser(\Application\Sonata\UserBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \Application\Sonata\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set pool
*
* #param \CD\CarsBundle\Entity\Pool $pool
* #return Reservations
*/
public function setPool(\CD\CarsBundle\Entity\Pool $pool = null)
{
$this->pool = $pool;
return $this;
}
/**
* Get pool
*
* #return \CD\CarsBundle\Entity\Pool
*/
public function getPool()
{
return $this->pool;
}
}
Thank you. Have a nice day.

I have figured it out.
In the controller, at the swiftmailer section, the line to the get the recipient's email is :
// Get the recipients' emails adresses (pool address)
$recipients = $entity->getPool()->getEmailPool();
Like this it works.
Thank you to all the people who read this post and if you have an other answer, feel free to post it.
Have a nice day!

Related

Editing entity - choicetype are reset

I am creating my first app on symfony, and am currently working on a form in order to edit an pretty big entity. My issue is : i have some choiceType in order to choose from definied values... BUT when i enter in the form, the default value of these choiceType is set to the first one in the list, not the value of the entity...
Same goes for an EntityType...
There is my buildform :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('classePSI', NumberType::class, array(
'attr' => array(
'min' => 0,
'max' => 5
)
))
->add('codeSA', TextType::class)
->add('nom', TextType::class)
->add('host', TextType::class)
->add('cluster', TextType::class)
->add('besoin', ChoiceType::class, array(
'choices' => array(
'0 - Non concerné' => 0,
'1 - A remonter' => 1,
'2 - Composant commun' => 2
)
))
->add('estVirtuel', ChoiceType::class, array(
'choices' => array(
'Reel' => false,
'Virtuel' => true
)
))
->add('instancePartage', TextType::class, array('required' => false))
->add('perimetre', EntityType::class, array(
'class' => 'GGMOPSIBundle:Perimetre',
'choice_label' => 'libellePerimetre',
'multiple' => false,
'expanded' => false,
'query_builder' => function (PerimetreRepository $repository) {
return $repository->getVisibleQB();
}
))
->add('type', EntityType::class, array(
'class' => 'GGMOPSIBundle:SousType',
'choice_label' => 'nom',
'multiple' => false,
'expanded' => false
))->add('save', SubmitType::class, array("label" => "Editer composant"));;
}
My entity :
namespace G\GMOPSIBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Composant
*
* #ORM\Table(name="gmo_psi_composant")
* #ORM\Entity(repositoryClass="G\GMOPSIBundle\Repository\ComposantRepository")
*/
class Composant
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="classePSI", type="integer")
*/
private $classePSI;
/**
* #var string
*
* #ORM\Column(name="codeSA", type="string", length=20)
*/
private $codeSA;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="host", type="string", length=255)
*/
private $host;
/**
* #var string
*
* #ORM\Column(name="cluster", type="string", length=255)
*/
private $cluster;
/**
* #var int
*
* #ORM\Column(name="besoin", type="integer",nullable=true)
*/
private $besoin=null;
/**
* #var bool
*
* #ORM\Column(name="estVirtuel", type="boolean")
*/
private $estVirtuel;
/**
* #var string
*
* #ORM\Column(name="InstancePartage", type="string", length=255,nullable=true)
*/
private $instancePartage;
/**
* #ORM\ManyToOne(targetEntity="G\GMOPSIBundle\Entity\Perimetre")
* #ORM\JoinColumn(nullable=true)
*/
private $perimetre;
/**
* #ORM\ManyToOne(targetEntity="G\GMOPSIBundle\Entity\SousType")
* #ORM\JoinColumn(nullable=true)
*/
private $type;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set classePSI
*
* #param integer $classePSI
*
* #return Composant
*/
public function setClassePSI($classePSI)
{
$this->classePSI = $classePSI;
return $this;
}
/**
* Get classePSI
*
* #return integer
*/
public function getClassePSI()
{
return $this->classePSI;
}
/**
* Set codeSA
*
* #param string $codeSA
*
* #return Composant
*/
public function setCodeSA($codeSA)
{
$this->codeSA = $codeSA;
return $this;
}
/**
* Get codeSA
*
* #return string
*/
public function getCodeSA()
{
return $this->codeSA;
}
/**
* Set nom
*
* #param string $nom
*
* #return Composant
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set host
*
* #param string $host
*
* #return Composant
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Get host
*
* #return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set cluster
*
* #param string $cluster
*
* #return Composant
*/
public function setCluster($cluster)
{
$this->cluster = $cluster;
return $this;
}
/**
* Get cluster
*
* #return string
*/
public function getCluster()
{
return $this->cluster;
}
/**
* Set besoin
*
* #param integer $besoin
*
* #return Composant
*/
public function setBesoin($besoin)
{
$this->besoin = $besoin;
return $this;
}
/**
* Get besoin
*
* #return integer
*/
public function getBesoin()
{
return $this->besoin;
}
/**
* Set estVirtuel
*
* #param boolean $estVirtuel
*
* #return Composant
*/
public function setEstVirtuel($estVirtuel)
{
$this->estVirtuel = $estVirtuel;
return $this;
}
/**
* Get estVirtuel
*
* #return boolean
*/
public function getEstVirtuel()
{
return $this->estVirtuel;
}
/**
* Set instancePartage
*
* #param string $instancePartage
*
* #return Composant
*/
public function setInstancePartage($instancePartage)
{
$this->instancePartage = $instancePartage;
return $this;
}
/**
* Get instancePartage
*
* #return string
*/
public function getInstancePartage()
{
return $this->instancePartage;
}
/**
* #return mixed
*/
public function getPerimetre()
{
return $this->perimetre;
}
/**
* #param mixed $perimetre
*/
public function setPerimetre($perimetre)
{
$this->perimetre = $perimetre;
}
/**
* #return Type
*/
public function getType()
{
return $this->type;
}
/**
* #param mixed $type
*/
public function setType($type)
{
$this->type = $type;
}
}
My editAction :
public function editAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$composant = $em->getRepository('GGMOPSIBundle:Composant')->find($id);
if (null === $composant) {
throw new NotFoundHttpException("Le composant d'id ".$id." n'existe pas.");
}
$form = $this->createForm(ComposantType::class, $composant);
$handle =$form->handleRequest($request);
if ($request->isMethod('POST') && $handle->isSubmitted() && $handle->isValid()) {
$em->flush();
$request->getSession()->getFlashBag()->add('notice', 'Composant bien modifié.');
return $this->redirectToRoute('g_gmopsi_viewcomposants');
}
return $this->render('GGMOPSIBundle:Composant:edit.html.twig', array(
'comp' => $composant,
'form' => $form->createView(),
));
}
Every textype is correctly pre-entered with values from entity so i don't know what to do...
Thanks in advance
If you are using Symfony < 3.0, try to add 'choices_as_values' => true
like this
->add('besoin', ChoiceType::class, array(
'choices' => array(
'0 - Non concerné' => 0,
'1 - A remonter' => 1,
'2 - Composant commun' => 2
),
'choices_as_values' => true
))
Ok i am just plain dumb. I had things like that in my twig :
{{ form_label(form.perimetre, "Perimetre : ") }}
{{ form_widget(form.perimetre,{'value' : comp.perimetre}) }}
Removing value atttribute fixes the issue.
{{ form_label(form.perimetre, "Perimetre : ") }}
{{ form_widget(form.perimetre) }}
Thanks loic anyway

An exception occurred while executing 'INSERT INTO tag (name, task_id) VALUES (?, ?)' with params ["qw", null]:

Please help me to resolve this error:
I have two entities, Task and Tag, in TaskType pretend add N tags, but when I keep generates the following error:
An exception occurred while executing 'INSERT INTO tag (name, task_id) VALUES (?, ?)' with params ["qw", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'task_id' cannot be null
Task:
class Task
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="Tag", mappedBy="task", cascade={"persist", "remove"})
*/
private $tags;
public function __construct() {
$this->tags = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set description
*
* #param string $description
*
* #return Task
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set tags
*
* #param string $tags
*
* #return Task
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Add tag
*
* #param \AppBundle\Entity\Tag $tag
*
* #return Task
*/
public function addTag(\AppBundle\Entity\Tag $tag)
{
$this->tags[] = $tag;
return $this;
}
// public function addTag(Tag $tag)
// {
// $this->tags->add($tag);
// }
/**
* Remove tag
*
* #param \AppBundle\Entity\Tag $tag
*/
public function removeTag(\AppBundle\Entity\Tag $tag)
{
$this->tags->removeElement($tag);
}
}
Tag:
class Tag
{
/**
* #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)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="Task", inversedBy="tags")
* #ORM\JoinColumn(name="task_id", referencedColumnName="id")
*/
private $task;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Tag
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set task
*
* #param \AppBundle\Entity\Task $task
*
* #return Tag
*/
public function setTask(\AppBundle\Entity\Task $task = null)
{
$this->task = $task;
return $this;
}
/**
* Get task
*
* #return \AppBundle\Entity\Task
*/
public function getTask()
{
return $this->task;
}
}
TaskType:
class TaskType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description')
->add('tags', 'collection', array(
'type' => new TagType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
))
->add('submit','submit');
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DeteccionBundle\Entity\Task'
));
}
/**
* #return string
*/
public function getName()
{
return 'task';
}
}
Controller:
public function newAction(Request $request)
{
$task = new Task();
//SE AGREGAN UN NUMERO DE Tags PARA LA task
// $tag1 = new Tag();
// $tag1->setName = 'tag1';
// $task->getTags()->add($tag1);
// $tag2 = new Tag();
// $tag2->setName = 'tag2';
// $task->getTags()->add($tag2);
// end dummy code
$form = $this->createForm(new TaskType(), $task);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('cpu_show', array('id' => $entity->getId())));
}
return $this->render('DeteccionBundle:Task:new.html.twig', array(
'task' => $task,
'form' => $form->createView(),
));
}
I appreciate your help
You should auto-set the task in your addTag like...
/**
* Add tag
*
* #param \AppBundle\Entity\Tag $tag
*
* #return Task
*/
public function addTag(\AppBundle\Entity\Tag $tag)
{
$this->tags[] = $tag;
$tag->setTask($this);
return $this;
}

Working with Doctrine 2 in Zend Framework 2 Form and fieldset using DoctrineHydrator

Client Entity
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Client
*
* #ORM\Table(name="client", uniqueConstraints={#ORM\UniqueConstraint(name="mail", columns=
* {"mail"}), #ORM\UniqueConstraint(name="pseudo", columns={"pseudo"})}, indexes=
* {#ORM\Index(name="FK_client_situation", columns={"situation"}),
*#ORM\Index(name="FK_client_city", columns={"ville"})})
* #ORM\Entity
*/
class Client
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="firstname", type="string", length=255, nullable=true)
*/
private $firstname;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=255, nullable=true)
*/
private $lastname;
/**
* #var \DateTime
*
* #ORM\Column(name="birthay", type="datetime", nullable=true)
*/
private $birthay;
/**
* #var string
*
* #ORM\Column(name="mail", type="string", length=255, nullable=true)
*/
private $mail;
/**
* #var string
*
* #ORM\Column(name="phone", type="text", nullable=true)
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="pseudo", type="string", length=255, nullable=true)
*/
private $pseudo;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=true)
*/
private $password;
/**
* #var integer
*
* #ORM\Column(name="situation", type="integer", nullable=true)
*/
private $situation;
/**
* #var integer
*
* #ORM\Column(name="ville", type="integer", nullable=true)
*/
private $ville;
/**
* #var string
*
* #ORM\Column(name="facebook", type="string", length=255, nullable=true)
*/
private $facebook;
/**
* #var string
*
* #ORM\Column(name="picture", type="string", length=255, nullable=true)
*/
private $picture;
/**
* #var integer
*
* #ORM\Column(name="newseltter", type="integer", nullable=true)
*/
private $newseltter;
/**
* #var \DateTime
*
* #ORM\Column(name="dateinscription", type="datetime", nullable=true)
*/
private $dateinscription;
/**
* #var \DateTime
*
* #ORM\Column(name="datedelete", type="datetime", nullable=true)
*/
private $datedelete;
/**
* #var string
*
* #ORM\Column(name="statut", type="string", length=50, nullable=true)
*/
private $statut;
/**
* #var string
*
* #ORM\Column(name="contenu", type="text", nullable=true)
*/
private $contenu;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstname
*
* #param string $firstname
* #return Client
*/
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 Client
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set birthay
*
* #param \DateTime $birthay
* #return Client
*/
public function setBirthay($birthay)
{
$this->birthay = $birthay;
return $this;
}
/**
* Get birthay
*
* #return \DateTime
*/
public function getBirthay()
{
return $this->birthay;
}
/**
* Set mail
*
* #param string $mail
* #return Client
*/
public function setMail($mail)
{
$this->mail = $mail;
return $this;
}
/**
* Get mail
*
* #return string
*/
public function getMail()
{
return $this->mail;
}
/**
* Set phone
*
* #param string $phone
* #return Client
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set pseudo
*
* #param string $pseudo
* #return Client
*/
public function setPseudo($pseudo)
{
$this->pseudo = $pseudo;
return $this;
}
/**
* Get pseudo
*
* #return string
*/
public function getPseudo()
{
return $this->pseudo;
}
/**
* Set password
*
* #param string $password
* #return Client
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set situation
*
* #param integer $situation
* #return Client
*/
public function setSituation($situation)
{
$this->situation = $situation;
return $this;
}
/**
* Get situation
*
* #return integer
*/
public function getSituation()
{
return $this->situation;
}
/**
* Set ville
*
* #param integer $ville
* #return Client
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* #return integer
*/
public function getVille()
{
return $this->ville;
}
/**
* Set facebook
*
* #param string $facebook
* #return Client
*/
public function setFacebook($facebook)
{
$this->facebook = $facebook;
return $this;
}
/**
* Get facebook
*
* #return string
*/
public function getFacebook()
{
return $this->facebook;
}
/**
* Set picture
*
* #param string $picture
* #return Client
*/
public function setPicture($picture)
{
$this->picture = $picture;
return $this;
}
/**
* Get picture
*
* #return string
*/
public function getPicture()
{
return $this->picture;
}
/**
* Set newseltter
*
* #param integer $newseltter
* #return Client
*/
public function setNewseltter($newseltter)
{
$this->newseltter = $newseltter;
return $this;
}
/**
* Get newseltter
*
* #return integer
*/
public function getNewseltter()
{
return $this->newseltter;
}
/**
* Set dateinscription
*
* #param \DateTime $dateinscription
* #return Client
*/
public function setDateinscription($dateinscription)
{
$this->dateinscription = $dateinscription;
return $this;
}
/**
* Get dateinscription
*
* #return \DateTime
*/
public function getDateinscription()
{
return $this->dateinscription;
}
/**
* Set datedelete
*
* #param \DateTime $datedelete
* #return Client
*/
public function setDatedelete($datedelete)
{
$this->datedelete = $datedelete;
return $this;
}
/**
* Get datedelete
*
* #return \DateTime
*/
public function getDatedelete()
{
return $this->datedelete;
}
/**
* Set statut
*
* #param string $statut
* #return Client
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return string
*/
public function getStatut()
{
return $this->statut;
}
/**
* Set contenu
*
* #param string $contenu
* #return Client
*/
public function setContenu($contenu)
{
$this->contenu = $contenu;
return $this;
}
/**
* Get contenu
*
* #return string
*/
public function getContenu()
{
return $this->contenu;
}
}
?>
ClienFieldset
<?php
namespace Application\Form;
use Application\Entity\Client;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class ClientFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('post');
//$em = Registry::get('entityManager');
$this->setHydrator(new DoctrineHydrator($objectManager,'Application\Entity\Client'))
->setObject(new Client());
$this->setLabel('Post');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden'
)
));
$this->add(array(
'name' => 'mail',
'options' => array(
'label' => 'Title for this Post'
),
'attributes' => array(
'type' => 'text'
)
));
$this->add(array(
'name' => 'password',
'options' => array(
'label' => 'Text-Content for this post'
),
'attributes' => array(
'type' => 'text'
)
));
}
/**
* Define InputFilterSpecifications
*
* #access public
* #return array
*/
public function getInputFilterSpecification()
{
return array(
'mail' => array(
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
array('name' => 'StripTags')
),
'properties' => array(
'required' => true
)
),
'password' => array(
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
array('name' => 'StripTags')
),
'properties' => array(
'required' => true
)
)
);
}
}
?>
Client Form
<?php
namespace Application\Form;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
class ClientForm extends Form
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('post');
// The form will hydrate an object of type "BlogPost"
$this->setHydrator(new DoctrineHydrator($objectManager));
// Add the user fieldset, and set it as the base fieldset
$clientFieldset = new ClientFieldset($objectManager);
$clientFieldset->setUseAsBaseFieldset(true);
$this->add($clientFieldset);
$this->add(array(
'name' => 'security',
'type' => 'Zend\Form\Element\Csrf'
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton'
)
));
$this->setValidationGroup(array(
'security',
'post' => array(
'title',
'text'
)
));
}
}
?>
Index Action
<?php
public function indexAction()
{
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
// Create the form and inject the ObjectManager
$form = new ClientForm($objectManager);
// Create a new, empty entity and bind it to the form
$Client = new Client();
$form->bind($Client);
if ($this->request->isPost()) {
$form->setData($this->request->getPost());
if ($form->isValid()) {
$objectManager->persist($Client);
$objectManager->flush();
}
}
return array('form' => $form);
}
?>
#index View
<table class="table">
<?php
if($this->form){
echo $this->form()->openTag($form);
echo $this->formRow($form->get('id'));
echo $this->formRow($form->get('mail'));
echo $this->form()->closeTag();
}
</table> ?>
When i execute My Code i get this Error..
Warning:
include(/var/www/Colocation/Colocation/module/Visitor/config/../view/error/index.phtml):
failed to open stream: No such file or directory in
/var/www/Colocation/Colocation/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php
on line 506
Warning: include(): Failed opening '/var/www/Colocation/Colocation/module/Visitor/config/../view/error/index.phtml'
for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in
/var/www/Colocation/Colocation/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php
on line 506
Pleaz Help me!
The php warning says that it cannot find the file error/index.phtml.
It is looking for this file because somewhere in your code there is an error, which would lead to the error page.
Default error page files are located in the Application module (module/Application/view/error/), but in your case, it is trying to find these files in the 'Visitor' module.
Perhaps in the 'Visitor' module you overwritten the Application's module 'view_manager' configs, so you can try ONE of the follow:
Open the 'Visitor' module config file and comment or remove all error related configs, using this config for the 'view_manager' should be enough
'view_manager' => array(
'template_path_stack' => array(
'visitor' => __DIR__ . '/../view',
),
),
Create error page templates in your 'Visitor' module like the ones you can find in the Application module. Do this only if you want to customize your error page template, keeping unchanged the Application error template, otherwise use the first solution.
After you finish you should be able to see another error but this time related to your code!

symfony2 validation of child entity prevents editing of parent entity

I have run into this problem with a couple of my entities now so I thought to try and get a hang of what really goes on, and I turn to my best source here (will add a bounty to this question as soon as it is eligible).
My user is part of a user group. I have a validator for the userGroup entity to make sure no two userGroups have the same name.
The problem is that when I go to editing a user, and try to select that userGroup for the user, symfony2 is behaving as if I were trying to create another userGroup with that same name, when in reality all I am doing is I am trying to select that userGroup for the user.
A user entity
<?php
// src/BizTV/UserBundle/Entity/User.php
namespace BizTV\UserBundle\Entity;
use BizTV\UserBundle\Validator\Constraints as BizTVAssert;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use BizTV\BackendBundle\Entity\company as company;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser implements AdvancedUserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
//TODO: Add constraint on $name * #BizTVAssert\NameExists (and finish coding this constraint)
/**
* #var object BizTV\BackendBundle\Entity\company
*
* #ORM\ManyToOne(targetEntity="BizTV\BackendBundle\Entity\company")
* #ORM\JoinColumn(name="company", referencedColumnName="id", nullable=false)
*/
protected $company;
/**
* #var object BizTV\UserBundle\Entity\UserGroup
* #ORM\ManyToOne(targetEntity="BizTV\UserBundle\Entity\UserGroup")
* #ORM\JoinColumn(name="userGroup", referencedColumnName="id", nullable=true)
*/
protected $userGroup;
/**
* #ORM\ManyToMany(targetEntity="BizTV\ContainerManagementBundle\Entity\Container", inversedBy="users")
* #ORM\JoinTable(name="access")
*/
private $access;
/**
* #var object BizTV\ContainerManagementBundle\Entity\Container
*
* This only applies to the BizTV server user accounts or "screen display accounts". Others will have null here.
*
* #ORM\ManyToOne(targetEntity="BizTV\ContainerManagementBundle\Entity\Container")
* #ORM\JoinColumn(name="screen", referencedColumnName="id", nullable=true)
*/
protected $screen;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
protected $isServer;
public function __construct()
{
parent::__construct();
$this->access = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set company
*
* #param BizTV\BackendBundle\Entity\company $company
*/
public function setCompany(\BizTV\BackendBundle\Entity\company $company)
{
$this->company = $company;
}
/**
* Get company
*
* #return BizTV\BackendBundle\Entity\company
*/
public function getCompany()
{
return $this->company;
}
/**
* Add access
*
* #param BizTV\ContainerManagementBundle\Entity\Container $access
*/
public function addContainer(\BizTV\ContainerManagementBundle\Entity\Container $access)
{
$this->access[] = $access;
}
/**
* Get access
*
* #return Doctrine\Common\Collections\Collection
*/
public function getAccess()
{
return $this->access;
}
/**
* Set screen
*
* #param BizTV\ContainerManagementBundle\Entity\Container $screen
*/
public function setScreen(\BizTV\ContainerManagementBundle\Entity\Container $screen)
{
$this->screen = $screen;
}
/**
* Get screen
*
* #return BizTV\ContainerManagementBundle\Entity\Container
*/
public function getScreen()
{
return $this->screen;
}
/**
* Set isServer
*
* #param boolean $isServer
*/
public function setIsServer($isServer)
{
$this->isServer = $isServer;
}
/**
* Get isServer
*
* #return boolean
*/
public function getIsServer()
{
return $this->isServer;
}
/**
* Set userGroup
*
* #param BizTV\UserBundle\Entity\UserGroup $userGroup
*/
public function setUserGroup(\BizTV\UserBundle\Entity\UserGroup $userGroup = null)
{
$this->userGroup = $userGroup;
}
/**
* Get userGroup
*
* #return BizTV\UserBundle\Entity\UserGroup
*/
public function getUserGroup()
{
return $this->userGroup;
}
}
The UserGroup entity that the User is linked to:
<?php
namespace BizTV\UserBundle\Entity;
use BizTV\UserBundle\Validator\Constraints as BizTVAssert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* BizTV\UserBundle\Entity\UserGroup
*
* #ORM\Table()
* #ORM\Entity
*/
class UserGroup
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $name
* #BizTVAssert\NameExists
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotBlank(message = "Du måste ange ett gruppnamn")
*/
private $name;
/**
* #var object BizTV\BackendBundle\Entity\company
*
* #ORM\ManyToOne(targetEntity="BizTV\BackendBundle\Entity\company")
* #ORM\JoinColumn(name="company", referencedColumnName="id", nullable=false)
*/
protected $company;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set company
*
* #param BizTV\BackendBundle\Entity\company $company
*/
public function setCompany(\BizTV\BackendBundle\Entity\company $company)
{
$this->company = $company;
}
/**
* Get company
*
* #return BizTV\BackendBundle\Entity\company
*/
public function getCompany()
{
return $this->company;
}
}
The NameExistsValidator
<?php
namespace BizTV\UserBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Doctrine\ORM\EntityManager as EntityManager;
class NameExistsValidator extends ConstraintValidator
{
private $container;
private $em;
public function __construct(Container $container, EntityManager $em) {
$this->container = $container;
$this->em = $em;
}
public function isValid($value, Constraint $constraint)
{
$em = $this->em;
$container = $this->container;
$company = $this->container->get('security.context')->getToken()->getUser()->getCompany();
//Fetch entities with same name
$repository = $em->getRepository('BizTVUserBundle:UserGroup');
//$repository = $this->getDoctrine()->getRepository('BizTVContainerManagementBundle:Container');
$query = $repository->createQueryBuilder('c')
->where('c.company = :company')
->setParameter('company', $company)
->orderBy('c.name', 'ASC')
->getQuery();
$groups = $query->getResult();
foreach ($groups as $g) {
if ($g->getName() == $value) {
$this->setMessage('Namnet '.$value.' är upptaget, vänligen välj ett annat', array('%string%' => $value));
return false;
}
}
return true;
}
}
User edit form
<?php
namespace BizTV\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\CallbackValidator;
use Symfony\Component\Form\FormValidatorInterface;
use Symfony\Component\Form\FormError;
use Doctrine\ORM\EntityRepository;
class editUserType extends AbstractType
{
function __construct($company)
{
$this->company = $company;
}
public function buildForm(FormBuilder $builder, array $options)
{
$company = $this->company;
$builder
->add('locked', 'checkbox', array('label' => 'Kontot är låst, användaren kan inte logga in '))
->add('username', 'text', array('label' => 'Användarnamn '))
;
$builder
->add('userGroup', 'entity', array(
'label' => 'Användargrupp',
'empty_value' => 'Ingen grupptillhörighet',
'property' => 'name',
'class' => 'BizTV\UserBundle\Entity\UserGroup',
'query_builder' => function(\Doctrine\ORM\EntityRepository $er) use ($company) {
$qb = $er->createQueryBuilder('a');
$qb->where('a.company = :company');
$qb->setParameters( array('company' => $company) );
$qb->orderBy('a.name', 'ASC');
return $qb;
}
));
$builder
->add('email', 'email', array('label' => 'Epost '))
->add('plainPassword', 'repeated', array('type' => 'password', 'first_name' => 'Nytt lösenord ', 'second_name' => 'Upprepa lösenord ',));
$builder
->add('roles', 'choice', array(
'label' => 'Roller',
'expanded' => true,
'multiple' => true,
'choices' => array(
'ROLE_CONTENT' => 'Innehåll (Användaren kan lägga till, redigera och ta bort innehåll där du nedan beviljar åtkomst)',
'ROLE_LAYOUT' => 'Skärmlayout (Användaren kan skapa ny skärmlayout, redigera befintlig eller ta bort gällande skärmlayout där du nedan beviljar åtkomst)',
'ROLE_VIDEO' => 'Videouppladdning (Användaren har rätt att ladda upp videofiler till företagets mediabibliotek)',
'ROLE_ADMIN' => 'Administratör (Användaren är administratör med fulla rättigheter till allt precis som det konto du nu är inloggad på, var mycket restriktiv med att tilldela denna behörighet).',
),
))
;
$builder
->add('access', 'entity', array(
'label' => 'Behörigheter',
'multiple' => true, // Multiple selection allowed
'expanded' => true, // Render as checkboxes
'property' => 'select_label',
'class' => 'BizTV\ContainerManagementBundle\Entity\Container',
'query_builder' => function(\Doctrine\ORM\EntityRepository $er) use ($company) {
$qb = $er->createQueryBuilder('a');
$qb->innerJoin('a.containerType', 'ct');
$qb->where('a.containerType IN (:containers)', 'a.company = :company');
$qb->setParameters( array('containers' => array(1,2,3,4), 'company' => $company) );
$qb->orderBy('ct.id', 'ASC');
return $qb;
}
));
$builder-> addValidator(new CallbackValidator(function(FormInterface $form){
$email = $form->get('email')->getData();
if (empty( $email )) {
$form['email']->addError(new FormError("Du måste ange en epostadress för användaren"));
}
}));
$builder-> addValidator(new CallbackValidator(function(FormInterface $form){
$username = $form->get('username')->getData();
if (strpos($username,'#') !== false) {
$form['username']->addError(new FormError("Användarnamnet får inte innehålla tecknet #"));
}
}));
$builder-> addValidator(new CallbackValidator(function(FormInterface $form){
$username = $form->get('username')->getData();
if (empty($username)) {
$form['username']->addError(new FormError("Du måste ange ett namn för användaren"));
}
}));
//TODO check if username exists
}
public function getName()
{
return 'biztv_userbundle_newusertype';
}
}
Your NameExistsValidator does this:
Fail if I find any user-group with the name I'm checking.
But I think you want it to do this:
Fail if I find another user-group with the name I'm checking.
In other words: the validator needs the complete UserGroup entity (or at least its id and name) to check for a user-group with the same name but different id.
Symfony 2 already has a UniqueEntity validator, why don't you use it?
Using annotations this would look something like this:
/**
* #ORM\Entity
* #AssertUniqueEntity(fields={"name"}, message="This name already exists")
*/
class UserGroup
{
One possible and simplest solution is to define Validation Groups. For example, when you create a group, you can use the validation group named 'create' or 'groups' and when you create a user does not specify a group. Then validator will not apply to user creation process.
Validation Groups can be assigned dynamically in the form class. An example of this you can see in the documentation.

form symfony 2 many many self reference entity

I would like to create a form with a collection of self reference entity.
I need a form to create new Product ,this form will have a select field (child) with existing products.
I have a product entity and this entity include a child field (child is a product too).
Product entity :
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", length=20)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
protected $title;
/**
* #var string
*
* #ORM\Column(name="manufacturer_reference", type="string", length=255, nullable=true)
*/
protected $manufacturer_reference;
/**
* #var string
*
* #ORM\Column(name="resume", type="text", nullable=true)
*/
protected $resume;
/**
* #var boolean
*
* #ORM\Column(name="is_salable", type="boolean", options={"default" = 1})
*/
protected $is_salable = 1;
/**
* #var boolean
*
* #ORM\Column(name="is_active", type="boolean", options={"default" = 1})
*/
protected $is_active = 1;
/**
* #ORM\ManyToOne(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductCategory")
* #ORM\JoinColumn(name="product_category_id", referencedColumnName="id", nullable=true)
*/
protected $product_category;
/**
* #ORM\ManyToOne(targetEntity="\Hexanet\Common\CatalogBundle\Entity\Manufacturer")
* #ORM\JoinColumn(name="manufacturer_id", referencedColumnName="id", nullable=true)
*/
protected $manufacturer;
/**
* #ORM\ManyToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\Product", mappedBy="parents" )
*/
protected $children;
/**
* #ORM\ManyToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\Product")
* #ORM\JoinTable(name="product_to_product",
* joinColumns={#ORM\JoinColumn(name="child_product_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="parent_product_id", referencedColumnName="id")}
* )
*/
protected $parents;
/**
* #ORM\OneToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductPrice", mappedBy="product" )
*/
protected $product_prices;
/**
* #ORM\OneToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase", mappedBy="product")
*/
protected $product_prices_purchase;
/**
* #ORM\OneToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom", mappedBy="product")
*/
protected $product_prices_custom;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Product
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set product category
*
* #param \Hexanet\Common\CatalogBundle\Entity\ProductCategory $product_category
* #return Product
*/
public function setProductCategory(\Hexanet\Common\CatalogBundle\Entity\ProductCategory $product_category = null)
{
$this->product_category = $product_category;
return $this;
}
/**
* Get product category
*
* #return \Hexanet\Common\CatalogBundle\Entity\ProductCategory
*/
public function getProductCategory()
{
return $this->product_category;
}
/**
* Set resume
*
* #param string $resume
* #return Product
*/
public function setResume($resume)
{
$this->resume = $resume;
return $this;
}
/**
* Get resume
*
* #return string
*/
public function getResume()
{
return $this->resume;
}
/**
* Set manufacturer reference
*
* #param string $title
* #return Product
*/
public function setManufacturerReference($ref)
{
$this->manufacturer_reference = $ref;
return $this;
}
/**
* Get manufacturer reference
*
* #return string
*/
public function getManufacturerReference()
{
return $this->manufacturer_reference;
}
/**
* Set is salable
*
* #param boolean $active
* #return Product
*/
public function setIsSalable($salable)
{
$this->is_salable = $salable;
return $this;
}
/**
* Get is salable
*
* #return boolean
*/
public function getIsSalable()
{
return $this->is_salable;
}
/**
* Set is active
*
* #param boolean $active
* #return Product
*/
public function setIsActive($active)
{
$this->is_active = $active;
return $this;
}
/**
* Get is active
*
* #return boolean
*/
public function getIsActive()
{
return $this->is_active;
}
/**
* Set manufacturer
*
* #param $manufacturer
* #return Product
*/
public function setManufacturer($manufacturer)
{
$this->manufacturer = $manufacturer;
return $this;
}
/**
* Get manufacturer
*
*/
public function getManufacturer()
{
return $this->manufacturer;
}
/**
* Constructor
*/
public function __construct()
{
$this->parents = new \Doctrine\Common\Collections\ArrayCollection();
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
$this->product_prices = new \Doctrine\Common\Collections\ArrayCollection();
$this->product_prices_purchase = new \Doctrine\Common\Collections\ArrayCollection();
$this->product_prices_custom = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add child
*
* #param \Hexanet\Common\CatalogBundle\Entity\Product $product
* #return Product
*/
public function addChild(\Hexanet\Common\CatalogBundle\Entity\Product $product)
{
die(var_dump($product));
$this->children[] = $product;
return $this;
}
/**
* Remove child
*
* #param \Hexanet\Common\CatalogBundle\Entity\Product $product
*/
public function removeChild(\Hexanet\Common\CatalogBundle\Entity\Product $product)
{
$this->children->removeElement($product);
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Add parent
*
* #param \Hexanet\Common\CatalogBundle\Entity\Product $product
* #return Product
*/
public function addParent(\Hexanet\Common\CatalogBundle\Entity\Product $product)
{
$this->parents[] = $product;
return $this;
}
/**
* Remove parent
*
* #param \Hexanet\Common\CatalogBundle\Entity\Product $price
*/
public function removeParent(\Hexanet\Common\CatalogBundle\Entity\Product $product)
{
$this->parents->removeElement($product);
}
/**
* Get parents
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getParents()
{
return $this->parents;
}
/**
* Add product price
*
* #param \Hexanet\Common\CatalogBundle\Entity\ProductPrice $price
* #return Product
*/
public function addProductPrice(\Hexanet\Common\CatalogBundle\Entity\ProductPrice $price)
{
$this->product_prices[] = $price;
return $this;
}
/**
* Remove product price
*
* #param \Hexanet\Common\CatalogBundle\Entity\ProductPrice $price
*/
public function removeProductPrice(\Hexanet\Common\CatalogBundle\Entity\ProductPrice $price)
{
$this->product_prices->removeElement($price);
}
/**
* Get product prices
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProductPrices()
{
return $this->product_prices;
}
/**
* Add product price purchase
*
* #param \Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price
* #return Product
*/
public function addProductPricePurchase(\Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price)
{
$this->product_prices_purchase[] = $price;
return $this;
}
/**
* Remove product price purchase
*
* #param \Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price
*/
public function removeProductPricePurchase(\Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price)
{
$this->product_prices_purchase->removeElement($price);
}
/**
* Get product prices purchase
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProductPricesPurchase()
{
return $this->product_prices_purchase;
}
/**
* Add product price custom
*
* #param \Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price
* #return Product
*/
public function addProductPriceCustom(\Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price)
{
$this->product_prices_custom[] = $price;
return $this;
}
/**
* Remove product price custom
*
* #param \Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price
*/
public function removeProductPriceCustom(\Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price)
{
$this->product_prices_custom->removeElement($price);
}
/**
* Get product prices custom
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProductPricesCustom()
{
return $this->product_prices_custom;
}}
for the form i have this :
class ProductType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('manufacturer_reference')
->add('resume')
->add('product_category', 'entity', array(
'class' => 'HexanetCatalogBundle:ProductCategory',
'property' => 'title',
))
->add('children', 'collection', array(
'type' => new ProductChildrenType,
'allow_add' => true));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Hexanet\Common\CatalogBundle\Entity\Product'
));
}
public function getName()
{
return 'hexanet_common_catalogbundle_producttype';
}}
The problem is there, i dont know how to create the ProductChildrenType builder :
class ProductChildrenType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', 'entity', array(
'class' => 'HexanetCatalogBundle:Product',
'property' => 'title',
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Hexanet\Common\CatalogBundle\Entity\Product'
));
}
public function getName()
{
return 'hexanet_common_catalogbundle_productchildrentype';
}}
->add('product', 'entity',...) I have the error :
Neither property "product" nor method "getProduct()" nor method "isProduct()" exists in class "Hexanet\Common\CatalogBundle\Entity\Product".
Thx for the Help
I have a similar case for a store, so i can add extra products on the admin area, so i can offer them on checkout...
My partner at work and me solved this problem yesterday, so if you're still interested, here we go....
We are using Symfony 2.6.x , i haven't tested it on older versions of symfony yet.
->add('myExtras', 'collection', array(
'type' => 'entity',
'options' => array(
'class' => 'StoreBundle:Productos',
'placeholder' => '-- Select an extra product --',
'property' => 'name',
'query_builder' => function (EntityRepository $er) use( $options ) {
return $er->createQueryBuilder('p')
->where('p.asociable = :asociable')
->andWhere('p.id != :selfid')
->setParameters( array('adjuntable' => '1', 'selfid' => $options['selfid'] ));
},
'label' => 'Extra Product'
),
'by_reference' => false,
'allow_add' => true,
'allow_delete' => true
))
instead of using a collection of form type for "children", we used a collection of type "entity", and we used a querybuilder to control the conditions we needed to get the right options to show.
using this we stopped having the messages, that you're getting... and for saving and removing the relation, when we add the children, we had to tell the children to set the parent... and for removing the same, first tell the children to remove the parent from the parent's list, and then remove the children from the children list... (in code is easier to see)
in the entity i have to collections myExtras (childrens) and imExtraOf (parents), so when adding a children, i have to tell the children i'm receiving the counterpart ->addImExtraOf (i am your father function) ... then we add the product to our extra list. and for removing, the same, we call first ->removeImExtraOf , if you don't do it this way, the relation will not be saved.
the Entity :
public function addMyExtra(Productos $extra)
{
$extra->addImExtraOf($this);
if( !$this->myExtras->contains($extra) ) {
$this->myExtras[] = $extra;
}
return $this;
}
public function removeMyExtra(Productos $extra)
{
$extra->removeImExtraOf($this);
$this->myExtras->removeElement($extra);
}
the orm mapping (yml): (myExtras = children, imExtraOf = parents )
manyToMany:
myExtras:
targetEntity: Productos
cascade: [ persist ]
mappedBy: imExtraOf
inversedBy: null
joinTable:
name: productos_has_productos
joinColumns:
-
name: extra_id
referencedColumnName: id
inverseJoinColumns:
-
name: base_id
referencedColumnName: id
orderBy: null
imExtraOf:
targetEntity: Productos
cascade: [ persist ]
mappedBy: null
inversedBy: myExtras
joinTable:
name: productos_has_productos
joinColumns:
-
name: base_id
referencedColumnName: id
inverseJoinColumns:
-
name: extra_id
referencedColumnName: id
orderBy: null
hope it helps someone.