gpt4 book ai didi

php - 在 Twig 模板中呈现自定义 formType 选项

转载 作者:搜寻专家 更新时间:2023-10-31 21:23:45 25 4
gpt4 key购买 nike

我在 Symfony 2.8 中遇到了这个问题:我无法通过将查询传递给表单选项来呈现自定义变量。

请参阅下面的代码,我已经尝试过:

这是我的 Controller :

$form = $this->createForm('AppBundle\Form\FooAdminType', $res, array('attr' => array('fooOnes' => $Choices)));  
//when $choices is my dql query

这是我的表单类型:

public function buildForm(FormBuilderInterface $builder, array $options) {      
$builder->add('bar', EntityType::class, array(
'class' => 'AppBundle:Foo',
'choices' => $options['attr']['FooOnes'],
'required' => true,
'property' => 'name',
'attr' => array(
'class' => 'col-lg-2 control-label text-center'
)
))

最后,我的 Twig 模板

{% for foo in form.bar %}
{{ form_widget(foo) }}
{% endfor %}

...如果没有 for block ,将呈现表单。对于 for block ,我有这个错误:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string") in form_div_layout.html.twig at line 277.

PS: 我在实体中定义了public function __toString()

最佳答案

如果不测试您的代码,按照您现在设置的方式,您将呈现一个选择元素。因此,循环遍历它没有任何意义。

您需要将属性 expanded 设置为 true 以便您能够使用 for 循环。这样,您将呈现单选按钮或复选框,具体取决于多个值。

对于复选框:

public function buildForm(FormBuilderInterface $builder, array $options) {      
$builder
->add('bar', EntityType::class, array(
'class' => 'AppBundle:Foo',
'choices' => $options['attr']['FooOnes'],
'required' => true,
'expanded' => true,
'multiple' => true,
'property' => 'name',
'attr' => array(
'class' => 'col-lg-2 control-label text-center'
)
))

关于php - 在 Twig 模板中呈现自定义 formType 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40840343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com