How to create arbitrary form fields in Symfony2? - symfony

I've been reading about Symfony2 forms (http://symfony.com/doc/current/book/forms.html) and I've been searching the net for ways to customize my form without any success.
my first problem is about creating arbitrary form fields in my form. Fields which are not based on my DB model/entity. I do not want to save the values in the form fields but I do not need them when processing the form.
e.g. I want 2 radio fields to appear on my approval page. "approve", "rejected". when I try to add the approved radio button on my form, I get an error that says "approve" doesn't have the get/set functions.
$em = $this->getDoctrine()->getEntityManager();
$application = $em
->getRepository('MyApp\GenericBundle\Entity\Application')
->find($applicationId);
$form = $this->createFormBuilder($application)
->setMethod('POST')
->add('approved', 'radio')
->getForm();
Thanks for the help

Use the mapped attribute that allows you to prevent the field from being persisted
$form = $this->createFormBuilder($application)
->setMethod('POST')
->add('approved', 'radio', array('mapped' => false))
->getForm();
Doc: http://symfony.com/doc/current/reference/forms/types/form.html#mapped

If you're trying to perform two actions on the form you could use alternate submit buttons; One for "Approve" one for "Reject"
http://symfony.com/blog/new-in-symfony-2-3-buttons-support-in-forms
http://symfony.com/doc/master/book/forms.html#submitting-forms-with-multiple-buttons

Related

Form tests: How to submit a collection to an existing form? [duplicate]

This question already has answers here:
Symfony2: Test on ArrayCollection gives "Unreachable field"
(4 answers)
Closed 6 years ago.
I use two ways to test my forms:
By using $form = …->form();
Then setting the values of the $form array (more precisely this is a \Symfony\Component\DomCrawler\Form object):
Full example from the documentation:
$form = $crawler->selectButton('submit')->form();
// set some values
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';
// submit the form
$crawler = $client->submit($form);
By sending the POST data directly:
The previous code doesn't work with forms which manage collections (relying on fields created by Javascript) because it throws an error if the field doesn't exist. That's why I also use this other way.
Full example from the documentation:
// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));
This solution is the only way I know to test forms which manage collections with fields added by Javascript (see link to documentation above). But this second solution is harder to use because:
it doesn't check which fields exist, this is impractical when I have to submit a form with existing fields and a collection which relies on fields created dynamically with Javascript
it requires to add the form _token manually
My question
Is it possible to use the syntax from the first way to define the existing fields then add new dynamically created fields with the second syntax?
In other words, I would like to have something like this:
$form = $crawler->selectButton('submit')->form();
// set some values for the existing fields
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';
// submit the form with additional data
$crawler = $client->submit($form, array('name' => 'Fabien'));
But I get this error:
Unreachable field "name"
And $form->get('name')->setData('Fabien'); triggers the same error.
This example is not perfect because the form has no collection, but it's enough to show you my problem.
I'm looking for a way to avoid this validation when I add some fields to the existing form.
This can be done by calling slightly modified code from the submit() method:
// Get the form.
$form = $crawler->filter('button')->form();
// Merge existing values with new values.
$values = array_merge_recursive(
$form->getPhpValues(),
array(
// New values.
'FORM_NAME' => array(
'COLLECTION_NAME' => array(
array(
'FIELD_NAME_1' => 'a',
'FIELD_NAME_2' => '1',
)
)
)
)
);
// Submit the form with the existing and new values.
$crawler = $this->client->request($form->getMethod(), $form->getUri(), $values,
$form->getPhpFiles());
The array with the news values in this example correspond to a form where you have a fields with these names:
<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_1]" />
<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_2]" />
The number (index) of the fields is irrelevant, PHP will merge the arrays and submit the data, Symfony will transform this data in the corresponding fields.

Use current user id - symfony 2

I use the FOS User bundle and LdapBundle for my users to connect to the website.
I created a form, and I want to keep a track on who added an entry. So I want to save to the database the user that added/modified that thing.
What is the best way to do this ? Since it's going to be a form, my first thought was to create an hidden field on my FormType with the current user id, but I think it's safe.
Any suggestion would be appreciated.
Thanks !
I dont know ldapBundle but when i want to save for example a photo i do in my controller
$user=$this->security_context->getToken()->getUser();
$form = $this->createForm(new PhotoType(), $photo )
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$photo->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($photo);
$em->flush();
....
Its a basic code, you also have to check if the user exist beofre doing the persistance : if($user) ...
I would suggest against the hidden field as it could be easily manipulated.
The better way would be to inject SecurityContext into your form and bind the logged in user to that object via POST_SUBMIT event.

How to create a unique form using multiple entities fields in symfony2

I want to create a form using some fields from multiple entities. I have all the distinct entites needed already created and i am not using form classes. I need to know how to do to render a form and handle its data so i can save them to the correct tables in my database.
Here is a part of my controller in charge of doing that
public function createPublicSpaceAction() {
//My entities
$Room = new Room();
$GuestList = new GuestList();
$Guest = new Guest();
//I need to know what to do from here
return $this -> render('AcmeUserBundle:Default:Forms/createPublicSpace.html.twig', array());
}
I kept trying to find a solution and i came up with the idea that one form needs one entity. So maybe the solution would be to merge those entities in one so i can build the form easily. I would then have to persist data to corresponding tables. But i can't think of how to merge entities.
I figured out a temporary solution. For those who want to know, I manually created an entity that looks like a merge of all the entity I need. This new entity has no link with Doctrine therefore it cannot create a table. Its goal is simply to allow me to build up a form and be able to manipulate data through that form. I then assign all data submitted to corresponding entities fields and persist them to the database.
Once again i know this is not the best solution. But for some reasons I won't tell, it is for me at this moment. I hope this can help some that are in the same situation than me and do not hesitate to post links that could help or better ways to do that.
It is highly recommended to use form classes http://symfony.com/doc/current/book/forms.html#creating-form-classes
They are designed to save time and make a lot of things just easier.
However to answer your question consider the following. Your action needs to handel a post request. So catch the request object with the post data:
use Symfony\Component\HttpFoundation\Request;
public function createPublicSpaceAction(Request $request)
Then get a form builder intance and create the form:
$builder = $this->createFormBuilder();
$builder->add('floor', 'text', array(
'label' => 'Room floor',
'data' => $room->getFloor()
));
add as much form fields as you need. There are several built-in field types: http://symfony.com/doc/current/book/forms.html#built-in-field-types
Create the form:
$form = $builder->getForm();
Pass the form to your template:
return $this -> render('AcmeUserBundle:Default:Forms/
createPublicSpace.html.twig', array(
'roomForm' = $form
));
To get posted data within your action:
if ('POST' == $request->getMethod()) {
$data = $request->request->get("form");
}
And in your template you can render the form by yourself or let twig do the job:
{{ form_widget(form.floor)}}
So this are the most importend things to mention. However you should go through http://symfony.com/doc/current/book/forms.html They actually tell you everything I wrote down.
Good luck ;)

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

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