更新时间:2023-11-19 22:56:34
我发现了解决方法,
在Controller中创建表单的方式是错误的!
我必须执行以下操作:
the way I was creating the form in Controller was wrong! I had to do the following:
$pricingForm = $this->createFormBuilder(array('prices'=>$prices))
->add('prices','collection',array(
'required' => true,
'allow_add' => true,
'type' => new PricingType(),
))
->getForm()
;
在使用集合时必须 allow_add => true,否则将不将任何PricingType实体集合添加到表单中。
"allow_add => true" is necessary when working with collection, otherwise it will NOT add any of PricingType collection of entities to the form.
然后,因为表单是在控制器 $ this-> ; createFormBuilder(array('prices'=> $ prices))
, $ prices
数组必须作为具有相同数组键名的数组传递作为 -> add('prices','collection',array(...)
中使用的那个,即'prices
$ prices
是一个定价对象数组 array(0 => new Pricing())
。
Then, because the form is built inside the controller "$this->createFormBuilder(array('prices'=>$prices))
" , $prices
array must be passed as an array with array keyname same as the one used in "->add('prices','collection',array(...)
" , which is 'prices'
so Symfony will know what to bind where. $prices
is an array of Pricing objects array(0 => new Pricing())
.
在我的PricingType中,我有:
In my PricingType I have:
class PricingType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('price', 'text', array(
'label' => false,
'required' => true
))
->add('enabled','checkbox',array(
'label' => 'Use this currency',
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'XXX\XXX\Entity\Pricing',
'csrf_protection' => false
));
}
public function getName()
{
return 'pricingtype';
}
}
在这里,我需要控制标签属性。我找不到方法(如果有人知道,请发布操作方法)。我重写了我的树枝模板,如下所示:
Here I need to have control over label attribute. I could not find the way for it( if anyone knows please post how to). I override my twig template as follows:
在顶部,我们需要下一行代码:
On the top we need next line of code:
{% form_theme form_pricing _self %}
然后按如下所示覆盖行和小部件(这是调试的噩梦):
Then override row and widget as follows (it was a nightmare to debug):
{% block _form_prices_entry_row %}
{% spaceless %}
{{ form_widget(form) }}
{% endspaceless %}
{% endblock %}
{% block _form_prices_entry_widget %}
{% spaceless %}
{{ form_row(form.price, { 'label' : form.vars.value.getCurrency().getTitle() } ) }}
{{ form_row(form.enabled) }}
{% endspaceless %}
{% endblock %}
然后在正文中呈现如下表单元素:
In the body then, render form elements as follows:
{% for price in form_pricing.prices %}
<div class="price-row">{{ form_row(price) }}</div>
{% endfor %}
我真的希望这对您有所帮助。调试尤其是树枝文件是一个真正的噩梦,这要归功于我聪明的同事。
I really hope this will help you guyz. It was a real nightmare to debug especially the twig file, I did it thanks to my clever colleague.