Twig 上 form_widget 选项的占位符选项、Twig、form_widget

2023-09-07 00:43:30 作者:清酒醉欢颜

在控制器端使用 PHP,我可以使用 createFormBuilder() 向我的字段添加占位符:

Using PHP on controller side, i can add a placeholder to my field using the createFormBuilder():

$form = $this->createFormBuilder($company)
                ->add('name', 'text')
                ->add('cities', 'entity', array(
                    'class' => 'NexBaseBundle:City',
                    'property' => 'name',
                    'placeholder' => 'Choose an option',
                ))
                ->getForm();

我希望使用 Twig 添加占位符,对于简单的字段,我可以像这样使用 attr:

I am looking to add a placeholder using Twig, for simple fields i can use attr like this :

{{ form_widget(form.name, {'attr': {'placeholder': 'My placeholder'} }) }}

我试过了,但没有运气:

I have tried with this but no luck:

{{ form_widget(form.cities, {'attr': {'placeholder': 'Choose your city'} }) }}

推荐答案

你不能因为html5上的选择框"没有属性placeholder",你的formbuilder中的属性placeholder"是empty_value

You can't because the "select box" on html5 does not have an attribute "placeholder", your attribute "placeholder" in your formbuilder is an alternative of empty_value

https://github.com/symfony/symfony/issues/5791