Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get->Request in Symfony2

Tags:

post

php

symfony

I have a very simple question, How can I get the POST values from get->Request();

public function emptytrashAction(){
    $request = $this->getRequest();
    $portfolio_id = $_POST["test"];
}

I dont want to use the $_POST variable and the form I submit just contain this hidden field test. The form is,

 <form name="empt_trash" action="{{ path('MunichInnovationGroupPatentBundle_portfolio_emptytrash') }}" method="post" >
    <input type="hidden" name="test" value={{ selected_portfolio.id }}>
    <input class="button3 tooltip" name = "submit" type="submit" value="Empty"></a>
 </form>

How can I get the value of the hidden field without using $_POST?

Edit

If a method use both GET and POST requests, For the Post request I check in my code like this

            if ($request->getMethod() == 'POST')

but it is not the symfony2 way then what is the proper way to check for the POST request?

like image 755
Zoha Ali Khan Avatar asked Dec 15 '22 22:12

Zoha Ali Khan


2 Answers

As simple as :

$request  = $this->getRequest();
$postData = $request->request->get('test');

Note: This solution is only valid for Symfony <2.4 version. For 2.4 is deprecated and removed for 3.0.

The new code for obtain the request should be:

$request = $this->container->get('request_stack')->getCurrentRequest();
$postData = $request->request->get('test');
like image 119
j0k Avatar answered Dec 30 '22 12:12

j0k


$this->getRequest() is a deprecated method since symfony 2.4 and it will be removed in the version 3.0, so the best way to get the current request is through the following code:

//src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
...

/*
 * ...
 * @deprecated Deprecated since version 2.4, to be removed in 3.0. Ask
 *             Symfony to inject the Request object into your controller
 *             method instead by type hinting it in the method's signature.
 */
public function getRequest()
{
    return $this->container->get('request_stack')->getCurrentRequest();
}

Introduced by the following evolution,

[FrameworkBundle] use the new request_stack service to get the Request object in the base Controller class.

like image 22
sami boussacsou Avatar answered Dec 30 '22 13:12

sami boussacsou