MrGlass
MrGlass

Reputation: 9262

Unset a form field value in symfony2 controller

In a typical Symfony2 form, when a field is invalid, the form is presented again to the user with all fields repopulated and an error on the specific field that has an issue.

In my form, I want to force the user to reenter the values of one field (for security reasons), but keep the rest of the fields populated. Is there any way to unset/clear a fields value from the controller in SF2?

Upvotes: 0

Views: 1325

Answers (2)

j_goldman
j_goldman

Reputation: 331

After you change the value on the object as shown in the answer below, you need to create the form again and pass the object to the form when you do...

$form = $this->createForm(new YourFormType(), $object);

return $this->render('YourBundle:YourEntityName:yourTemplate.html.twig, (array(
    'entity'=>$entity,
    'form'=>$form->createView()
));

Upvotes: 1

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

Just set it to null — or whatever an empty value is — on the model object itself.

if ($form->isValid()) {
    // ...
} else {
    $object->setSomeField(null);
}

Upvotes: 1

Related Questions