如果我尝试在树枝中渲染有条件添加的表单元素,我当前会收到错误。表单元素是通过表单事件侦听器机制添加(或不添加),并且只应在设置了特定表单选项时添加表单元素。
传递给Symfony \ Component \ Form \ FormRenderer :: searchAndRenderBlock()的参数1必须是Symfony \ Component \ Form \ FormView的实例,null给定
<?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 %}
我也尝试了一个包围条件 - 如果,但这根本不起作用...我认为twig需要“未定义”的信用卡表单元素,但无法找到它。
这样做的正确方法是什么?非常感谢你的任何帮助。 : - )
谢谢!
答案 0 :(得分:1)
试试这个:
{% if form_data.creditcard is defined %}
... your conditional code here
{% endif %}