2012-08-13 79 views
2

我在Symfony2的一個形式類型:如何使symfony2表單自動在表單類型中輸入當前登錄用戶的ID?

namespace Acme\SomethingBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilder; 

class GuestType extends AbstractType 
{ 
    public function buildForm(FormBuilder $builder, array $options) 
    { 
     $builder 
      ->add('name') 
      ->add('email') 
      ->add('address') 
      ->add('phone') 
      ->add('created_at') 
      ->add('updated_at') 
      ->add('is_activated') 
      ->add('user','entity', array('class'=>'Acme\SomethingBundle\Entity\User', 'property'=>'id')); 
    } 

    public function getName() 
    { 
     return 'acme_somethingbundle_guesttype'; 
    } 
} 

動作:

<h1>Guest creation</h1> 
<form action="{{ path('guest_create') }}" method="post" {{ form_enctype(form) }}> 
    {{ form_widget(form) }} 
    <p> 
     <button type="submit">Create</button> 
    </p> 
</form> 

<ul class="record_actions"> 
    <li> 
     <a href="{{ path('guest') }}"> 
      Back to the list 
     </a> 
    </li> 
</ul> 

'用戶' 屬性採用的用戶ID的實體作爲變量

/** 
    * Displays a form to create a new Guest entity. 
    * 
    */ 
    public function newAction() 
    { 
     $entity = new Guest(); 
     $form = $this->createForm(new GuestType(), $entity); 

     return $this->render('AcmeSomethingBundle:Guest:new.html.twig', array(
      'entity' => $entity, 
      'form' => $form->createView() 
     )); 
    } 

    /** 
    * Creates a new Guest entity. 
    * 
    */ 
    public function createAction() 
    { 
     $entity = new Guest(); 
     $request = $this->getRequest(); 
     $form = $this->createForm(new GuestType(), $entity); 
     $form->bindRequest($request); 

     if ($form->isValid()) { 
      $em = $this->getDoctrine()->getEntityManager(); 
      $em->persist($entity); 
      $em->flush(); 

      return $this->redirect($this->generateUrl('guest_show', array('id' => $entity->getId()))); 

     } 

     return $this->render('AcmeSomethingBundleBundle:Guest:new.html.twig', array(
      'entity' => $entity, 
      'form' => $form->createView() 
     )); 
    } 

枝條模板並以樹枝形式顯示爲下拉框。我希望當前登錄(經過身份驗證的)用戶的ID自動插入並隱藏(如果可能) - 在「用戶」字段中。我知道我得到一個用戶的ID與

$user = $this->get('security.context')->getToken()->getUser(); 
$userId = $user->getId(); 

但我不能讓它的工作。

回答

7

你必須給該組中的客戶對象的用戶的形式注入之前,如果你想擁有它的形式,和編輯用戶:

$entity = new Guest(); 
$entity->setUser($this->get('security.context')->getToken()->getUser()); 
$form = $this->createForm(new GuestType(), $entity); 

否則,如果它不可編輯的,您應該從表格中刪除此字段並在isValid()測試後設置用戶。

+0

非常感謝 – Radolino 2012-08-13 08:06:36

相關問題