Placeholder for form_widget choices on Twig

佐手、 提交于 2020-02-02 11:27:24

问题


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();

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'} }) }}

回答1:


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




回答2:


On the createFormHandler its the empty_data option. You can use the placeholder option but its possible that you get some trouble in older Browsers.

Normally i disable that HTML5 functions and do it with Javascript.

http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

Here is a cool jQuery plugin to fix that problem in older Browsers.

Setting the value from your controller make not really sense. You can set a key in your form and translate them for example.

You can add the attribute only on text fields. Your second method on a Selext-Box is not working because there is not attribute placeholder on that element. So you can use the placeholder in your FormType but that is changed to an option field in background.




回答3:


Here is an example how I am currently adding placeholders (My select list can be different then yours, but you can play around of this snippet):

{% form_theme cart_form _self %}

{% block choice_widget %}
    {% if form.vars.choices is defined %}
        {% for choices in form.vars.choices %}
            <div class="row">    
                <div class="col-md-6">
                    <select name="{{ form.vars.full_name }}" class="form-control">
                        <option value="__none">--Choose</option>
                        {% for choice in choices %}
                            <option value="{{ choice.value }}">{{ choice.label }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
        {% endfor %}
    {% endif %}
{% endblock %}


来源:https://stackoverflow.com/questions/27655754/placeholder-for-form-widget-choices-on-twig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!