Symfony2 custom shortcut

I had a small but annoying problem with the symfony2 Field component. For example, I would like to output an array of form fields in a branch template:

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

And here is the text box configuration:

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

But unfortunately, when the engine displays this output, I get "FieldName" as a label instead of "MyCustomLabel". I would not have a problem if I displayed the form fields not in (in this case, I can just add a label to the template for each field). But the script does not know the specific number and configuration of the form fields before execution. So I need to implement a loop method for rendering fields. And I also want to stay in the bow record ... I will be happy for the good advice :)

+6
forms symfony twig rendering
source share
6 answers
+1
source share

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

please do not change the field name, but you can play with Label inside the array.

Enjoy it!

+7
source share

The easiest way to do this in a template is to pass the second argument to form_label

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

The answer is for Symfony 2.1 users who stumble upon this, hoping for an answer, there is almost always @rikinadhyapak's answer.

if you extended the FormType class of some package, such as FOSUserBundle, in the 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 
+2
source share

I would honestly hold on to exploring the Symfony form component for a couple of weeks. Symfony developers are overhauling API forms. From what I understand, most of them are done, and the transfer request was sent to the main repository .

0
source share

For Symfony 2.3, you can replace the shortcut using the following events:

 $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 that.

0
source share

All Articles