How to send params in url query_string in Symfony?

2019-07-20 13:10发布

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条回答
淡お忘
2楼-- · 2019-07-20 13:53

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.

查看更多
登录 后发表回答