Configure the form root element with Symfony Forms 3

While creating the forms with Form component from Symfony you can write your own Type classes which builds the forms. It’s pretty simple to add your own fields and all the required stuff for it.

class SignUpType extends AbstractType {
  public function buildForm(FormBuilderInterface $builder, array $options) {
  $builder
    ->add('email', Type\EmailType::class, array(
      'label' => __('Email', Plugin::NAME),
      'required' => false,
      'constraints' => array(
         new Constraints\NotBlank(array(
           'groups' => array('personal', 'company'),
         )),
         new Constraints\Email(array(
           'groups' => array('personal', 'company'),
         )),
      ),
     'validation_groups' => array('personal', 'company'),
     'attr' => array(
       'data-form-element-role' => 'conditional-listener',
       'class' => 'regular-text',
     ),
    ))
    ;
  }
}

But that if you want to configure out the root form element. For example, setup few additional classes and data attributes for your tag? Just add configureOptions() method and fill all the required stuff inside.

class SignUpType extends AbstractType {

  // buidForm here

  public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
      'attr' => array(
        'data-form-type' => 'conditional-form',
        'id' => 'your-id',
      ),
    ));
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s