Unset a form field value in symfony2 controller - symfony

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?

Just set it to null — or whatever an empty value is — on the model object itself.
if ($form->isValid()) {
// ...
} else {
$object->setSomeField(null);
}

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()
));

Related

Within a Callback validator for a Symfony sub-form collection, how do I get the value of a different field?

Let's say I have a Callback validator attached to a field in a collection sub-form that looks like this:
$callback = new Callback([
'callback' => function($obj, $context) {
// Value of field to validate, no problem
$value = $context->getValue();
// Get the form, but gets my parent form
$form = $context->getRoot();
// Try and get other field value I need to validate current field,
// but gets "child "otherfield" does not exist" error.
$otherValue = $form->get('otherfield')->getData();
// continue validation logic...
}
]);
I need the value of another field from the specific form instance for the collection item, but I can't find a way to access the child form instance. How do I do this? I can access the list of forms for the collection by using the parent field that holds the collection, but I need the specific instance that this is validating.
It's Symfony version 3.3, but I can't find anything in a later version, either.

Give formbuilder class value as 'hidden'

I would like to give formBuilder User Entity as hidden value.
$form->add('user','hidden',array("data" => $user))
$user is User Entity.
However it shows this error.
Expected argument of type "Acme\UserBundle\Entity\User", "string" given
If I use 'null' instead of 'hidden'
$form->add('user',null,array("data" => $user))
it doesn't show the error and shows the select box of user Entity.
However I would like to use hidden.
How can I make it??
You did't specify the field type correctly - this is the correct way:
...
$formBuilder->add('user', HiddenType::class);
...
...
$form = $formBuilder->getForm();
$form->get('user')->setData($user->getId());
But you can't assign entity to the hidden field, so you can assign user's id for user identification.
Another option is to make data transformer and define own EntityHiddenType - more on this here: symfony : can't we have a hidden entity field?

Symfony-Disabling specific field validations from controller

I am using Symfony 2.7.6. I have created an entity called employee and its interactive forms are generated using doctrine crud generator. Entity have the following fields
1. id
2. firstname
3. lastname
4. email
5. username
6. password
validations are working as expected from user registration form for all the fields.
ISSUE: I have created a login form and i want to suppress validation for the fields firstname, lastname and email and exclude these elements from rendering on my page
I have modified my controller like this for rendering my form
$entity = $em->getRepository('XXXEmployeeBundle:Employee');
$form = $this->createForm(new \XXX\EmployeeBundle\Form\EmployeeType(), $entity, array(
'action' => $this->generateUrl('user_login'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Update'));
$form->remove('firstname');
$form->remove('lastname');
$form->remove('email');
$form->handleRequest($request);
This works fine when the from is rendering as the fields are excluded from the form. But my $form->isvalid() is returning false. As I have printed the errors using $form->getErrorsAsString() method, its showing like:
firstname: ERROR: First name cannot be empty. lastname: ERROR: Last name code cannot be empty. employeeFirstName: ERROR: Employee first name cannot be empty. email: ERROR: Email cannot be empty.
Is this the right method to achieve this functionality?? Please help me in solving the issue. Thanks
In your entity you mush include nullable=true like this
/**
* #ORM\Column(type="string", nullable=true)
*
* #var string
*/
protected $nombre;
And telling doctrine that is nullable, neither backend/frontend check the value.
Greetings !
I think problem in logic.
When you create registration form - you want to create and save new
entity.
When you create login form - you want to compare login and
password between form and entity.
So. You should create special form class for login (not from registration) and don't set data-enitity (second parameter in createForm function)
And, please check if you have the same form object in controller action that handles this form.
You can make a work around
Get all form's errors within your controller by
$form->getErrors()
and then loop over them, if it's the error you know it would happen, just bypass it on purpose and process further.
if ($form->isSubmitted()) { // remove $form->isValid() check
foreach($form->getErrors() as $error) {
// check if it's expected error, then do nothing and proceed further for user
// if it's unexpected throw an exception, catch them below and add error message to session flashbag. or something similar
}
}

Symfony creates empty association when checkbox used on embedded form

I have a form for Person that has an embedded form for Address (bi-directional one to one relationship, with Address as the owning side w/ FK).
If a user submits the form, Symfony will initialize an empty Address object and assign it to the $address property on the $person object. Instead, I want Symfony to recognize all the form fields for Address were blank and it should NOT initialize an empty Address object.
Is this possible?
EDIT: I discovered that this only happens when I have a checkbox on the embedded form type. If there is no checkbox, Symfony will NOT create an empty association object. I think the problem is an unchecked checkbox is assumed to be a "false" value, so Symfony has no choice but to interpret that as a submitted value. Still looking for a reasonable workaround.
It's possible to do this with form events
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html
Search for FORM_SUBMIT
However, I find it a bit convoluted.
Consider instead treating Person and Address as independent objects then setting the relation in your controller after checking Address. Something like:
$person = new Person();
$address = new Address();
$formData = array('person' => $person, 'address' => $address);
$builder = $this->formFactory->create('form',$formData);
$builder->add('person', new PersonFormType());
$builder->add('address', new AddressFormType());
...
if ($form->isValid()
{
if ($address was filled in properly)
{
$person->setAddress($address);
}
---
I find the above approach a bit easier to understand than going through the form event stuff.

How I can do a confirmation window?

I want to create a confirmation window when I fill in a form.
Right now, I fill in the form and if the form is valid, the entity is persisted and returned a view with my entity as a parameter. But this isn't what I want.
If the form is valid I don't want to persist the entity. If it's valid, would have to show a view using my parameter(entity) and then if my user clicks the button to confirm, persist the entity and redirect to other view. If my user clicks the button to return, I use the JavaScript function: javascript:history.back(1).
How I can do this?
An easy way is to store your bound entity in session (a flash) and retrieve it after confirmation for persistence.
In your "saveForm" action:
if ($form->isValid()) {
$myEntity = $form->getData();
$this->get('session')->setFlash('my_entity', $myEntity);
return $this->render('MyBundle:Controller:confirmation.html.twig', array(
'entity' => $myEntity
));
}
And in your "confirmSave" action:
$myEntity = $this->get('session')->getFlash('my_entity');
$this->em->persist($myEntity);
$this->em->flush();
It's just a basic example an it needs to be adaped to your project.

Resources