2014-03-13 16 views
0

如果我嘗試在樹枝中呈現有條件添加的表單元素,我當前正在收到錯誤。表單元素通過表單事件偵聽器機制添加(或不添加),並且只應添加表單元素(如果設置了特定的表單選項)。傳遞給Symfony的\元器件\表格Symfony2 twig在有條件添加的表單域上拋出呈現錯誤

錯誤

參數1 \ FormRenderer :: searchAndRenderBlock()必須的Symfony \元器件\表格\ FormView的的一個實例,給定的零

表格
<?php 
namespace Vendor\ProjectBundle\Form\Type; 

// [...] 

abstract class AbstractContextualInfoFormType extends AbstractFormType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->add('user', new UserFormType($this->getTranslator(), $this->getDoctrine()), array('error_bubbling' => true, 'validation_groups' => 'ValidationGroup')); 

     $creditcardForm = new CreditcardFormType($this->getTranslator(), $this->getDoctrine()); 
     $creditcardForm->setProcess($options['process']); 
     $creditcardForm->setProvider($options['provider']); 
     if (array_key_exists('cvc', $options)) { 
      $creditcardForm->setRequireCvc($options['cvc']); 
     } 

     if (array_key_exists('types', $options)) { 
      $creditcardForm->setAllowedCreditcardTypes($options['types']); 
     } 

     $builder->addEventListener(
      FormEvents::PRE_SET_DATA, 
      function (FormEvent $event) use ($options) { 
       if (!array_key_exists('disable_creditcard', $options) OR (array_key_exists('disable_creditcard', $options) AND $options['disable_creditcard'] === true)) { 
        $creditcardForm = new CreditcardFormType($this->getTranslator(), $this->getDoctrine()); 
        $creditcardForm->setProcess($options['process']); 
        $creditcardForm->setProvider($options['provider']); 
        if (array_key_exists('cvc', $options)) { 
         $creditcardForm->setRequireCvc($options['cvc']); 
        } 

        if (array_key_exists('types', $options)) { 
         $creditcardForm->setAllowedCreditcardTypes($options['types']); 
        } 

        $form = $event->getForm(); 

        $form->add('creditcard', $creditcardForm, array('error_bubbling' => true)); 
       } 
      } 
     ); 
    } 
} 

// [...] 

正如你所看到的,我試着添加信用卡表格,只有當選項disable_creditcard沒有設置。直到那一刻我嘗試瀏覽,我實現表單的頁面這一切工作正常:

模板

{% if not disable_creditcard %} 
<div id="detail_creditcard" class="creditcard"> 
<legend>{{ 'creditcard.content.title'|trans }}</legend> 
<div class="alert alert-info"> 
    <i class="icon-info-sign"></i> 
    Bla bla bla text 
</div> 
    **{{ form_row(form_data.creditcard.owner) }}** 
    {{ form_row(form_data.creditcard.number) }} 
    {{ form_row(form_data.creditcard.type) }} 
    {{ form_row(form_data.creditcard.validity) }} 
    {{ form_rest(form_data.creditcard) }} 
</div> 
{% endif %} 

我也有包圍的條件,如果試了一下,但是,這並不在所有的工作...我認爲樹枝需要「未定義」的信用卡表格元素,但無法找到它。

這樣做的正確方法是什麼?我很感謝您的幫助。 :-)

謝謝!

回答

1

試試這個:

{% if form_data.creditcard is defined %} 

... your conditional code here 

{% endif %}