How to set default value for symfony form field (user field) following connected user after ManyToMany relationship between objects

In my symfony 2.7 application, I have a custom object based on FOSUserBundle . The user must be connected to access the addAction () form.

My custom object is associated with another object called parc. This is the code of my two objects.

Users.php

class Users extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; public function __construct() { parent::__construct(); $this->parcs = new \Doctrine\Common\Collections\ArrayCollection(); } /** * @var \Doctrine\Common\Collections\Collection * * @ORM\ManyToMany(targetEntity="Parcs", inversedBy="users") * @ORM\JoinTable(name="users_parcs", * joinColumns={ * @ORM\JoinColumn(name="user_id", referencedColumnName="id") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="parc_id", referencedColumnName="id") * } * ) */ private $parcs; /** * Get parcs * * @return \Doctrine\Common\Collections\Collection */ public function getParcs() { return $this->parcs; } /** * Set parcs * * @return \Doctrine\Common\Collections\Collection */ public function setParcs($parcs) { return $this->parcs; } 

Parcs.php

 class Parcs { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\ManyToMany(targetEntity="Users", mappedBy="parcs") */ private $users; public function __construct() { $this->users = new \Doctrine\Common\Collections\ArrayCollection(); } //rest of my entity attributes, object, properties etc // getters and setters /** * Get users * * @return \Doctrine\Common\Collections\Collection */ public function getUsers() { return $this->users; } /** * Set users * * @return \Doctrine\Common\Collections\Collection */ public function setUsers($users) { return $this->users; } /** * Add user * * @param \MySpace\MyBundle\Entity\Users $user * * @return Parcs */ public function addUser(\MySpace\MyBundle\Entity\Users $user) { $this->users[] = $user; return $this; } 

Using FOSUserBundle to access the connected user, in my twig view I do this: {{ app.user.username }} , which returns me the username of the current user.

Now I would like to get this value in my symfony form (for user field) when I would like to add parc. This is my form of parcsType.php :

 public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('parcName') ->add('users') ; } 

This is my form in twig view:

 <form action="{{ path('addParcs_process') }}" method="POST" {{ form_enctype(form) }}> <div> {{ form_label(form.parcName, "Enter the parc name: ", {'label_attr': {'class': 'control-label'}}) }} {{ form_errors(form.parcName) }} {{ form_widget(form.parcName) }} </div> <div> {{ form_label(form.users, "Vous ajoutez ce parc en tant que: ", {'label_attr': {'class': 'control-label'}}) }} {{ form_errors(form.users) }} {{ form_widget(form.users, {'attr': {'value': app.user.username }}) }} </div> <input type="submit" value="Ajouter" class="btn btn-success"/> </form> 

As you can see, I set the default value for my user field {{ app.user.username }} and it works, my user field returns me the current user. But when I submit the form, the user field and the association ( ManyToMany ) between Parcs.php and Users.php not saved / not cleared.

This is my controller code:

 public function addParcsAction() { if (!$this->get('security.context')->isGranted('ROLE_EDIT')) { throw new HttpException("403"); } $em=$this->getDoctrine()->getManager(); $parc = new Parcs; $form=$this->createForm(new ParcsType(), $parc); $form->add('user'); $request = $this->getRequest(); if ($request->isMethod('POST') | ($form->isValid())) { $form->bind($request); $currentUser=$this->container->get('security.context')->getToken()->getUser(); $parc->setUsers($currentUser); $parc = $form->getData(); $em->persist($parc); $em->flush(); return $this->redirect($this->generateUrl('indexParc')); } else { return $this->render('MySpaceMyBundle:Parcs:addParcs.html.twig', array('form' => $form->createView() )); } } 

The view works well when I enter a value for the name parc, the data is logged in my database, but not the user value and the ManyToMany association.

+5
source share
2 answers

I found a solution

As explained here , the responsibility for managing the connection rests solely with the party.

The problem is not with the $parc->addUser($currentUser); but that this Parcs object was not the owner to manage this relationship when he would like to save the data.

So, I returned the properties of the owner of the object. In Parcs.php relation should be like this:

 /** * @var \Doctrine\Common\Collections\Collection * * @ORM\ManyToMany(targetEntity="Users", inversedBy="parcs") * @ORM\JoinTable(name="parcs_users", * joinColumns={ * @ORM\JoinColumn(name="parc_id", referencedColumnName="id") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="user_id", referencedColumnName="id") * } * ) */ private $users; 

I need to delete the relation in Users.php to write this:

 /** * @var \Doctrine\Common\Collections\Collection * * @ORM\ManyToMany(targetEntity="Parcs", mappedBy="users") */ private $parcs; 

And this is my controller for addAction() :

 public function addParcsAction() { if (!$this->get('security.context')->isGranted('ROLE_EDIT')) { throw new HttpException("403"); } $em=$this->getDoctrine()->getManager(); $parc = new Parcs; $currentUser = $this->container->get('security.context')->getToken()->getUser(); $parc->addUser($currentUser); $form = $this->createForm(new ParcsType(), $parc); $request = $this->getRequest(); if ($request->isMethod('POST') | ($form->isValid())) { $form->bind($request); $parc = $form->getData(); $em->persist($parc); $em->flush(); return $this->redirect($this->generateUrl('indexParc')); } else { return $this->render('MySpaceMyBundle:Parcs:addParcs.html.twig', array('form' => $form->createView() )); } } 

Thank you very much in answering, noting here that it is not $ parc-> addUser ($ currentUser); who was making trouble, but the owner of the relationship side.

+3
source

Before creating a form, you need to add a User object to the Parc object. So you don’t even need the {'attr': {'value': app.user.username }} .

Can you try this:

 public function addParcsAction() { if (!$this->get('security.context')->isGranted('ROLE_EDIT')) { throw new HttpException("403"); } $em=$this->getDoctrine()->getManager(); $parc = new Parcs; $currentUser = $this->container->get('security.context')->getToken()->getUser(); $parc->addUser($currentUser); $form = $this->createForm(new ParcsType(), $parc); $request = $this->getRequest(); if ($request->isMethod('POST') | ($form->isValid())) { $form->bind($request); $parc = $form->getData(); $em->persist($parc); $em->flush(); return $this->redirect($this->generateUrl('indexParc')); } else { return $this->render('MySpaceMyBundle:Parcs:addParcs.html.twig', array('form' => $form->createView() )); } } 

Thus, your form will be generated by the current user as the default value in the users form field

+3
source

Source: https://habr.com/ru/post/1232013/


All Articles