OK, this is a newbie question, but I can't find the answer anywhere. In a controller in Symfony2, I want to access the POST value from one of my forms. In the controller I have:
public function indexAction()
{
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form = $this->get('form.factory')->create(new ContactType());
$form->bindRequest($request);
if ($form->isValid()) {
$name_value = $request->request->get('name');
Unfortunately $name_value
isn't returning anything. What am I doing wrong? Thanks!
I think that in order to get the request data, bound and validated by the form object, you must use :
$form->getClientData();
The form post values are stored under the name of the form in the request. For example, if you've overridden the getName()
method of ContactType() to return "contact", you would do this:
$postData = $request->request->get('contact');
$name_value = $postData['name'];
If you're still having trouble, try doing a var_dump()
on $request->request->all()
to see all the post values.
Symfony doc to get request data
Finally, the raw data sent with the request body can be accessed using getContent():
$content = $request->getContent();
what worked for me was using this:
$data = $request->request->all();
$name = $data['form']['name'];
There is one trick with ParameterBag::get()
method. You can set $deep
parameter to true
and access the required deep nested value without extra variable:
$request->request->get('form[some][deep][data]', null, true);
Also you have possibility to set a default value (2nd parameter of get()
method), it can avoid redundant isset($form['some']['deep']['data'])
call.
If you are newbie, welcome to Symfony2, an open-source project so if you want to learn a lot, you can open the source !
From "Form.php" :
getData() getNormData() getViewData()
You can find more details in this file.
The field data can be accessed in a controller with: Listing 12-34
$form->get('dueDate')->getData();
In addition, the data of an unmapped field can also be modified directly: Listing 12-35
$form->get('dueDate')->setData(new \DateTime());
page 164 symfony2 book(generated on October 9, 2013)
I access the ticketNumber parameter for my multipart post request in the following way.
$data = $request->request->all();
$ticketNumber = $data["ticketNumber"];
Source: Stackoverflow.com