6
votes

I had a little but unpleasant problem with symfony2 Field component. For example, I would like to output array of form fields in twig template:

{% for field in form %}
    {{ form_label( field ) }}: {{ form_field( field ) }}
{% endfor %}

And here is text field configuration:

$field = new TextField( 'FieldName', array(
    'label' => 'MyCustomLabel',
) );

But unfortunately when engine renders this output i get 'FieldName' as label instead of 'MyCustomLabel'. I would not have problems if i outputting form fields not in for (in that case i can just add a label in template for each field). But the script doesn't know certain quantity and configuration of form fields before execution. So, I need to implement cycle method for field rendering. And I also want to stay in twig notation...I will be pleased for a good advise :)

6
Did you solve it? How can i set custom label? - umpirsky

6 Answers

8
votes

If you want to change the label, than follow the steps. 1) Create form class. 2) add('fieldName',null,array('label' => 'My New Label:'))

please do not change fieldName, but you can play with Label within an array.

Enjoy!

4
votes

The easiest way to do it in template - pass the second argument to the form_label

<div class="form-group">
    {{ form_label(form.email, 'Email:') }} <- this row
    {{ form_widget(form.email, {'attr': {'class': 'form-control'}}) }}
</div>
3
votes

An answer for the Symfony 2.1 users who stumble onto this hoping for an answer, it's almost there is the @rikinadhyapak answer.

if you have extended the FormType class of some bundle like FOSUserBundle, in your buildForm method:

    $field = $builder->get('username');         // get the field
    $options = $field->getOptions();            // get the options
    $type = $field->getType()->getName();       // get the name of the type
    $options['label'] = "Login Name";           // change the label
    $builder->add('username', $type, $options); // replace the field
1
votes

I would honestly hold off on learning the Symfony Form component for a couple weeks. Symfony devs are doing a major-overhaul on the Form API. From what I understand, most of it is done, and a pull request has been submitted to the main repository.

1
votes

For Symfony 2.3 you can replace the label using the events as the following:

$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event)
{
    $form = $event->getForm();
    $object = $event->getData();

    $field = $form->get('fieldname');
    $config = $field->getConfig();
    $options = $config->getOptions();
    $options['label'] = 'New label'; // change the label
    $form->add($field->getName(), $config->getType()->getName(), $options); // replace the field

});

but I would avoid this.