2013-09-29 43 views
3

我正在使用表單生成器來創建表單以供在應用程序中使用。在表單中,用戶需要能夠選擇他們關聯的事件列表。但是,我無法弄清楚我可以如何將用戶ID傳遞給表單構建器?如何將值傳遞給Symfony2中的Form Builder?

我的代碼是這樣的時刻:

EvType.php

<?php 
// src/Acme/MembersBundle/Form/Type/EvType.php 
// This is to handle forms for the Members Form 
namespace Acme\MembersBundle\Form; 

use Doctrine\ORM\EntityRepository; 
use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolverInterface; 

class EvType extends AbstractType 
{ 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 

     $centre = $this->centre; 

     $builder->add('id', 'integer', array('required'=>false)); 
     $builder->add('list','entity', array('class'=>'Acme\InstructorBundle\Entity\MapLists', 'property'=>'name', 
                 'query_builder' => function(EntityRepository $br) { 
                  return $br->createQueryBuilder('ml') 
                   ->where('ml.user = :user') 
                   ->setParameter('user','1'); 
                 })); 
     $builder->add('eventHorse', 'text', array('required'=>false)); 
    } 

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

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class'  => 'Acme\InstructorBundle\Entity\MapListCentreMembers', 
      'csrf_protection' => false, 
      'csrf_field_name' => '_token', 
      // a unique key to help generate the secret token 
      'intention'  => 'task_item', 
     )); 
    } 

} 

->setParameter('user','1');是,我希望能夠從形式傳遞用戶的ID。現在,我靜態分配了用戶ID。

DefaultController.php

// User ID 
$userid = $mem['userID']; 

// Get Tests from Entity for Form use 
$memberEV = $dm->getRepository('InstructorBundle:MapListMembers')->find($memberint); 

// Generate Form to edit Tests & Achievements 
$ev = $this->createForm(new EvType(), $memberEV); 

回答

9

你可以簡單地通過在__construct的值。

見下文:

EvType.php

class EvType extends AbstractType 
{ 
    private $user; 

    public function __construct($user) 
    { 
     $this->user = $user; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $user = $this->user; 
     .... 
    } 

DefaultController.php

$ev = $this->createForm(new EvType($user), $memberEV); 
+0

也許你應該給一個嘗試這種解決方案,回顧configureOptions(),setDefaults ([ 'custom_option'= []])。我推薦閱讀:https://stackoverflow.com/questions/10920006/pass-custom-options-to-a-symfony2-form –

相關問題