2015-04-23 73 views
12

所以我對Symfony很陌生,我試圖讓控制器根據控制器動作構建略微不同的窗體。現在,我有這個Symfony2:將選項傳遞給buildForm

//in Controller 

public function addLocationEntryAction(Request $request) 
{ 
    $entry = new Entry(); 
    $form = $this->get('form.factory')->create(new EntryType('addLocation'), $entry); 

    return $this->render('OOTNBlogBundle:Blog:addEntry.html.twig', array(
     'form' => $form->createView() 
    )); 
} 

public function addArticleEntryAction(Request $request) 
{ 
    $entry = new Entry(); 
    $form = $this->get('form.factory')->create(new EntryType('addArticle'), $entry); 

    return $this->render('OOTNBlogBundle:Blog:addEntry.html.twig', array(
     'form' => $form->createView() 
    )); 
} 

而且

//in EntryType 

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

    $builder 
     ->add('title',  'text') 
     ->add('continent', 'text', array('required' => false)) 
     ->add('country', 'text', array('required' => false)) 
     ->add('category', 'text', array('required' => false)) 
     ->add('author',  'hidden') 
     ->add('type',  'hidden') 
     ->add('text',  'textarea') 
     ->add('post',  'submit') 
    ; 
} 

我想從控制器buildForm傳遞一個選項,這樣我可以做這樣的事情:

public function buildForm(FormBuilderInterface $builder, array $options, $option) 
{ 
    $builder 
     ->add('title',  'text') 
    ; 

    if($option == 'addLocation') 
    { 
     $builder 
      ->add('continent', 'text', array('required' => false)) 
      ->add('country', 'text', array('required' => false)) 
     ; 
    } 
    elseif($option == 'addArticle') 
    { 
     $builder 
      ->add('category', 'text', array('required' => false)) 
     ; 
    } 

    $builder 
     ->add('author',  'hidden') 
     ->add('type',  'hidden') 
     ->add('text',  'textarea') 
     ->add('post',  'submit') 
    ; 
} 

我該怎麼做?我已經在這裏查看了Symfony文檔和類似的問題,但似乎沒有什麼適合我的情況。我不知道。

回答

15

有沒有必要創建一個額外的參數,只需使用options來傳遞自定義數據。在以下示例中,我強制要求age屬性,您可以將其設置爲可選或指定默認值。瞭解更多關於OptionsResolverhere

class ExampleType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     var_dump($options['age']); 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setRequired(array(
      'age' 
     )); 

    } 
} 

創建:

$form = $this->get('form.factory')->create(new ExampleType(), $entry, array(
    'age' => 13 
)); 
+0

工作很漂亮,謝謝你 – Afunakwa

+0

@ b.b3rn4rd最好的答案!清晰,簡單,有效。在我的情況下,它也能很好地工作 –

+2

請注意'setDefaultOptions'已被棄用,以''configureOptions'爲優先。 http://symfony.com/blog/new-in-symfony-2-7-form-and-validator-updates#deprecated-setdefaultoptions-in-favor-of-configureoptions – DarksteelPenguin