I want to send parameters in query_string URL from Twig page and get it in the controller.
for example: index.html.twig
<a href="/newcont/add/{{ id }}">New</a>
and controller
:
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class Newcont extends Controller
{
/**
* @Route("/newcont/add/{id}", requirements={"id": "\d+"})
*/
public function addAction(Request $request){
$params = $request->request->all();
//$id = $request->query->get();
var_dump($params);
die;
}
}
I want to have an url with a variable in twig that is sent to the controller action.
Never hard code the routes! Use the routing helpers in your templates. First give a name to your route, in this case I have named it "myroute", of course you should use something more meaningful:
Then in your Twig file, use the
path
helper that will generate the correct path for you:You can replace 7 by a variable of course.
In your controller you can get the
id
parameter directly so you don't have to use the request service:You can do this because you have explicitly named this parameter in your route and it is mandatory, so in all cases it will be defined. It makes the code much cleaner and easy to read. It also allow to remove useless code.
Note that is this case you don't want to modify the query string, you modify the path. The query string is what is after the path like
?foo=bar
.