Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate "(optional)" on Symfony2 form

Tags:

symfony

I have some form types which are not required. The form labels should be localized, and that is easy.

But when you configure a certain form type as 'required'=>'false', a word "(optional)" appears just after the type label.

What would be the right way to translate "optional", or to disable it?

Btw. I don't see any way at all now.

Thank you

 "require": {
     "php": ">=5.3.3",
     "symfony/symfony": "v2.3.0",
     "doctrine/orm": ">=2.2.3,<2.4-dev",
     "doctrine/doctrine-bundle": "1.2.*",
     "twig/extensions": "1.0.*",
     "symfony/assetic-bundle": "2.1.*",
     "symfony/swiftmailer-bundle": "2.3.*",
     "symfony/monolog-bundle": "2.3.*",
     "sensio/distribution-bundle": "2.3.*",
     "sensio/framework-extra-bundle": "2.3.*",
     "sensio/generator-bundle": "2.3.*",
     "jms/security-extra-bundle": "1.4.*@dev",
     "jms/di-extra-bundle": "1.3.*@dev",
     "twitter/bootstrap" : "dev-master",
     "cg/kint-bundle": "dev-master",
     "raveren/kint": "dev-master",
     "mopa/bootstrap-bundle": "dev-master",
     "sonata-project/intl-bundle": "dev-master",
     "egeloen/ckeditor-bundle": "2.*"
},
like image 453
Đuro Mandinić Avatar asked Dec 27 '22 02:12

Đuro Mandinić


1 Answers

The "optional" string rendering is being introduced by the mopa/bootstrap-bundle.

It can be found in the bundle's Resources/views/Form/fields.html.twig.

The "optional" string is added in the block form_label_asterisk:

{% block label_asterisk %}
    {% if required %}
        {% if render_required_asterisk %}
             <span>*</span>
        {% endif %}
    {% else %}
        {% if render_optional_text %}
            <span>{{ "(optional)"|trans({}, translation_domain) }}</span>
        {% endif %}
    {% endif %}
{% endblock label_asterisk %}

As you can see the rendering requires you to set a translation_domain for the optional string to be translated. The correct implementation would have been using a fallback to 'messages'

...
<span>{{ "(optional)"|trans({}, translation_domain|default('messages')) }}</span>
...

Solution:

Remove the optional rendering completely by adding to your config.yml:

# app/config/config.yml
parameters:
    mopa_bootstrap.form.render_optional_text: false

... or add render_optional_text => false to your form options.

The BootstrapBundle's overriding of the default form-type can be found here.

Alternatively you can remove the optional string by overriding the block in a single form

{% form_theme form _self %}

{% block label_asterisk %}
    {% if required %}
        {% if render_required_asterisk %}
             <span>*</span>
        {% endif %}
    {% endif %}
{% endblock label_asterisk %}

More information about overriding form elements can be found in my answer here.

like image 157
Nicolai Fröhlich Avatar answered May 21 '23 16:05

Nicolai Fröhlich