2015-09-22 32 views
5

Nella mia applicazione symfony 2.7, ho l'entità utente basata su FOSUserBundle. Un utente deve essere connesso per poter accedere a un modulo addAction().come impostare il valore predefinito su un campo modulo symfony (campo Utente) seguendo l'utente connesso, seguendo la relazione ManyToMany tra le entità

L'entità utente è collegata con un'altra entità denominata parc. Questo è il codice delle mie due entità.

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; 
    } 

Utilizzando la FOSUserBundle, al fine di accedere per l'utente connesso, a mio avviso ramoscello Faccio questo: {{ app.user.username }} , che mi restituisce il nome utente dell'utente corrente.

Ora, vorrei recuperare questo valore nel mio modulo symfony (per l'utente campo) quando vorrei aggiungere un parc. Questa mia parcsType.php modulo:

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

Questa è la mia forma nella vista ramoscello:

<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> 

Come potete vedere, ho impostato il valore di default del mio campo utente con {{ app.user.username }}, e funziona, il mio campo utente mi restituisce l'utente corrente. Ma quando invio il modulo, il campo utente e l'associazione (ManyToMany) tra Parcs.php e Users.php non vengono mantenuti/scaricati.

Questo è il mio codice di controllo:

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())); 
     } 
} 

la presentazione funziona bene, quando entro in valore per il nome parco dei dati è registrata nel mio database, ma non il valore degli utenti e l'associazione ManyToMany.

+1

Perché se si crea una relazione con l'utente, è necessario passare l'oggetto utente non solo il nome utente. – malcolm

+0

@malcolm nell'uso del metodo ** {{app.user.username}} **, come posso utilizzare l'oggetto Utente? –

+0

dopo aver associato la richiesta è possibile ottenere l'utente corrente nel controller e impostarlo '$ parc-> setUsers ($ utente);' Non è necessario il campo modulo per quello. – malcolm

risposta

3

ho trovato la soluzione,

Come spiegato here, solo il lato proprietario è responsabile della gestione della connessione.

Il problema non era con il metodo $parc->addUser($currentUser);, è solo che quell'entità Parcs non era il proprietario per gestire questa relazione quando si desidera mantenere i dati.

Quindi ho invertito le proprietà del proprietario dell'entità.Nel Parcs.php il rapporto deve essere così:

/** 
* @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; 

devo togliere la relazione in Users.php al fine di scrivere questo:

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

E questo mio controller per il 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())); 
     } 
} 

Grazie molte rispondendo, ho notato che non era $ parc-> addUser ($ currentUser); chi stava facendo problemi, ma il lato proprietario della relazione.

3

È necessario aggiungere l'oggetto Utente all'oggetto Parc prima di creare il modulo. In questo modo non hai nemmeno bisogno della parte {'attr': {'value': app.user.username }}.

Puoi provare questo:

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())); 
     } 
} 

In questo modo il modulo sarà generato con l'utente corrente come valore di default nel vostro users campo modulo

+0

Infatti, aggiungendo il metodo '$ parc-> addUser ($ currentUser);', il campo modulo utente viene compilato dall'utente corrente. Rimuovo '{'attr': {'value': app.user.username}}' nella mia vista di ramoscello, ma quando procedo alla ** addAction() **, la relazione tra parc e user non è persistente, i dati del parc sono registrati nel database, ma non i dati dell'utente. –