I have a form that I want to use for both an and edit, but want to change the fields and validation accordingly.
I am changing what the form displays by looking at the 'name' option passed when running the createForm
method in the controller.
In controller:
public function createAction(Request $request)
{
$client = new Client();
$form = $this->createForm('client', $client, array('name' => 'add'));
$request = $this->getRequest();
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$client->save();
}
}
return $this->render('Bundle:client:clientAdd.html.twig', array(
'form' => $form->createView(),
));
}
In the ClientType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id');
if ('add' === $options['name']) {
$builder->add('name');
}
if ('edit' === $options['name']) {
$builder->add('age');
}
$builder->add('save', 'submit', array(
'label' => 'Save'
));
}
The validation (as defined in my validation.yml) has rules for all fields and it will throw an error for the field in add mode that is not present.
How can I get the validation to be conditional?