Give formbuilder class value as 'hidden' - symfony

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?

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.

how to set sonata form data_class on edit

im stuck with following error message on a project with symfony 2.8 and sonata admin/media bundle. i log in sonata and navigate to the list view were i have an edit button. i click the edit button and get following error.
error message:
The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class DateTime. You can avoid this error by setting the "data_class" option to "DateTime" or by adding a view transformer that transforms an instance of class DateTime to scalar, array or an instance of \ArrayAccess.
i found some answers via stackoverflow saying that the data_class needs to be set on the specific formtype. but thats sonata, were can i find the form i have to work on?
You can describe it in your admin class
protected function configureFormFields(FormMapper $form)
{
$form->add('date', 'datetime', array('data_class' => 'DateTime'));
}

Non-mapped form, EntityType and data attribute

I use an EntityType to create a form, but not mapped on an entity. The form is long and the user re-use the same options many times, then when he valid the form, if it's valid, I store the $form->getData() in session.
When I generate the form I inject the $data. It works well for all options, except the EntityType, I don't understand why...
In the $data, I've an ArrayCollection with the objects selected in the EntityType, but the form doesn't select it. I've used mapped = false, because if I remove it I've an error:
Entities passed to the choice field must be managed. Maybe persist them in the entity manager?
Someone I've an idea how to do ?
Settings mapped = false shouldn't be the solution in this case, because you need to write the stored data into this field, right? so mapped = false avoid it (see more about mapped option here)
The problem here is that the EntityType need to get the id value from each item and it requires that these items are managed actually by EntityManager:
Entities passed to the choice field must be managed. Maybe persist them in the entity manager?
An entity is in MANAGED state when its persistence is managed by an EntityManager. In other words, an entity is managed if its fetched from the database or registered as new through EntityManager#persist.
In you case, these entities comes from session, so you have two option:
Re-query the stored entities from database:
if (isset($data['foo']) && $data['foo'] instanceof Collection) {
$data['foo'] = $this->getDoctrine()->getRepository(Foo::class)->findBy([
'id' => $data['foo']->toArray(),
]);
}
Or, set a custom choice_value option to avoid the default one:
$form->add('foo', EntityType::class, [
'class' => Foo::class,
'choice_value' => 'id', // <--- default IdReader::getIdValue()
]);

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.

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

Resources