Modifying form fields and properties in Symfony 2.5 by customizing them as needed in different stages of the controller and views

Sometimes you may need to modify the standard form type by customizing some of the form fields, adding form fields, changing the list of form choices, omitting certain input, and making other changes. It’s easier to alter an existing form type than duplicating it just to make a few modifications, which helps follow the DRY principle (Don’t Repeat Yourself!)

Symfony encourages, and makes it easy to stay with OOP (Object Oriented Principles) by keeping to DRY, so you not only write less code, you will have less to maintain. Not to mention your code is more reliable, which is why it is recommended to reuse form types and modify them as needed in different situations, just like you would other objects in your system.

Here are some more helpful Symfony form tips and snippets.

Set the form action inside buildForm():


public function buildForm(FormBuilderInterface $builder, array $options)
{
   $builder->setAction($path);
}

Change the forms “action” url path in the createForm():

$form = $this->createForm(new WhateverFormType(), $object, array(
          'action' => $this->generateUrl('action_route'),
));

 

Customize form values and attributes in the createFormBuilder():

$form = $this->createFormBuilder($task)
  ->setAction($this->generateUrl('target_route'))
  ->setMethod('POST')
  ->add('task', 'text')
  ->add('dueDate', 'date)
  ->add('save', 'submit')
  ->getForm();

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *