当前位置: 动力学知识库 > 问答 > 编程问答 >

symfony2 - Whats wrong with symfony 2 route with parameter & name

问题描述:

I have a symfony 2 route like:

/**

* @Route("/thing/add/{id}", name="addThing")

*/

function addThing(Request $req) {

when I access /thing/add/1, symfony 2 complains:

The "addThing" route has some missing mandatory parameters ("id").

But in the profiler, I see under "request attributes", "id" = 1. But theres nothing in GET (or POST). Whats the problem?

UPDATE

If I remove name="addThing" it works ... but how do I access that route for my form action?

网友答案:

I will just complete the answer provided by @scube.

First of all, you should not pass the Request object directly in the action function of your controller. The reason is that arguments in those kind of functions (functions used as action in a controller) are used solely for the purpose of mapping part of the url into arguments. For example, if I have an annotation like @Route(/blog/{year}/{month}/{day), then, for arguments to being populated, you need an action function like this one:

public function blogViewAction($year, $month, $day) {
    // ...
}

This way, $year will be populated by the year argument from the url, $month by month and $day by day. The name of the variable in the url must match the name of your argument.

If you want to use the request object and you are in a controller, you request it from the dependency injection container like this:

$request = $this->get('request');

This is the way to define action in controller. Your definition of your route should look like this, same as @scube said:

/**
 * @Route("/thing/add/{id}", name="addThing")
 */
public function addThing($id) {
    // ...
}

Check that your route is registered in Symfony2 by running php app/console router:debug. This will print every routes known by the framework in your project. Check that the name addThing is there and the url mapping is good.

Finally, even if scope modifiers are not mandatory (public, protected, private) because public is the default, it is a good convention to always specify one.

Hope this helps.

Regards,
Matt

网友答案:

First: why the error message mention "addNote" and not "addThing"? Second: In order to use the id value in your url you need to define your function like this:

function addThing($id) { ... }
分享给朋友:
您可能感兴趣的文章:
随机阅读: