How to send params in url query_string in Symfony?

江枫思渺然 提交于 2019-12-24 01:51:56

问题


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.


回答1:


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:

class Newcont extends Controller
{
    /**
     * @Route("/newcont/add/{id}", name="myroute", requirements={"id": "\d+"})
     */

Then in your Twig file, use the path helper that will generate the correct path for you:

<a href="{{ path('myroute', {'id': 7}) }}">New</a>

You can replace 7 by a variable of course.

<a href="{{ path('myroute', {'id': myTwigVar}) }}">New</a>

In your controller you can get the id parameter directly so you don't have to use the request service:

public function addAction(Request $request, $id) { 

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.



来源:https://stackoverflow.com/questions/43832163/how-to-send-params-in-url-query-string-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!