Symfony2 route in annotations with optional parameters - symfony

i created a route with optional parameter in controller like this:
/**
* League action
*
* #Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null})
* #Route("/association/{assoc}/{league}/{game}")
* #Template()
*
* #param $assoc
* #param $league
* #param $game
* #return array
*/
public function leagueAction($assoc, $league, $game)
but if i try to create a link with this named route, the optional parameter is ommitted:
{{ path('league', {'assoc': association.short, 'league': league.id, 'game': g.id}) }}
resulting link is
/association/BVNR/7
What am i missing?

In the following definitions,
* #Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null})
* #Route("/association/{assoc}/{league}/{game}")
two routes are related to your action, the first one (named "league" which doesn't have any default parameter and a second unnamed one (as you didn't add name attribute) which also doesn't have any default parameter.
How to fix ...
Add a name to your second route and call it as it contains "game" parameter.
Move the default value of "game" parameter to your second route (As it the only one to have a game parameter.
(You don't really need to define two routes, take a look at the "How to improve ..." part of my answer).
Try this ...
* #Route("/association/{assoc}/{league}/{game}", name="league_game", requirements={"league" = "\d+"}, defaults={"game" = null})
While you should call "league_game" instead of "league",
{{ path('league_game', {'assoc': association.short, 'league': league.id, 'game': g.id}) }}
How to improve ...
Make sure you really need to define two routes, because I would suggest keeping only one route.
As there's a default value for "game"in the following definition,
#Route("/association/{assoc}/{league}/{game}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null}
It then covers both versions, with and without "game".

Related

symfony2 set request parameter to custom annotation

I want use request parameter in my annotation in Symfony2
I want set $id (it is parameter from request) to MyAnnotation, as it described below
/**
* #MyAnnotation($id)
* #Route('something/{id}')
*
*/
When I set $id in this way, I have an error. How to pass this parameter to annotation?
Other way is:
/**
* #MyAnnotation("id")
* #Route('something/{id}')
*
*/
And I can get value of "id" parameter in annotation class, in constructor:
public function __construct($options)
{
// get key
$key = $options['value'];
// get value of key
$id = $request->get($key);
}
But I dont know its possible to set $id in annotation and dont write code in constructor.

How to document a controller in symfony?

I'm trying to document my project. I want to document my controller. Before my Action I have:
/**
* Description: xxx
* #param parameters of my function Action
* #return views of the action
*/
The return value here will show:
Why?
Thanks
EDIT:
A standard controller:
public function myControllerAction(Request $request) {
return $this->render('AppBundle:Default:index.html.twig');
}
The reason is that the first word after #return is considered the type of the returned data according to the official phpDocumentor docs:
#return datatype description
#return datatype1|datatype2 description
The #return annotation expects the data type as a first argument, before the description. In your case you've specified the data type as views which hasn't been included with a use statement, so PHP assumes it belongs to the current namespace and you get \AppBundle\Controllers\views. The return type of a controller must be a Symfony\Component\HttpFoundation\Response. So you want:
#return \Symfony\Component\HttpFoundation\Response description
or if you already have a use statement for Response:
#return Response description
In some cases you might want to be more specific if you are always returning a specific subclass of response, like:
BinaryFileResponse
JsonResponse
RedirectResponse
StreamedResponse

how to pass variable from twig path to the same controller?

In template i need to pass variable to controller when clicked link
{{ variable }}
click
.
How to do this?
/**
* #Route("/test", defaults={"variable" = 1}, name="test")
* #Method("GET")
* #Template()
*/
public function testAction($variable)
{
return array('variable'=>$variable);
}
You will say i need placeholder in #Route /test/{variable}, then how to first time visit url test?
edit: this is silly question. I had some cache problem while testing this issue. The answear is obvious.
You need to define your #Route annotation like you mention:
/**
* #Route("/test/{variable}", defaults={"variable" = 0}, name="test")
* #Method("GET")
* #Template()
*/
public function testAction($variable)
{
return array('variable'=>$variable);
}
Thanks to defaults option you can access your route with or without variable:
With:
click
This will generate url /test/2 and your $variable will equal 2
Without:
click
This will generate url /test and your $variable will equal 0 (a value set in defaults option)
I had to do something similar, and #Tomasz, your answer helped me a lot. I my case I needed two variables.
Using the above example as a reference:
* #Route("/test/{variable}/{var2}",
* defaults={"variable" = 0, "var2" = 0},
* name="test")
* #Method("GET")
* #Template()
*/
public function testAction($variable, $var2)
{
return array('variable'=>$variable, 'var2 => $var2);
}
Then in twig you can use:
click
which generates URL /test/2/3
In my case, I was using something more fancy, like an Entity:
<td><a href="{{ path('submitPetHasProgram',
{'prog':stu.getTcProgram.getProgramId,
'student':stu.getStuId}) }}">Select</a></td>
Hopefully this will help someone out in the future who is struggling for a solution to this type of problem.

how to set the routing translation based on annotation?

All the routing of my website is realized based on the annotations. Now, I want to translate my routing. To realize that, I tried to use the bundle JMSI18nRoutingBundle.
Nevetheless, the documentation does not give any example how to specify the route for each locale.
This is an action with its routing, how to translate it?
/**
* #Route("/welcome", name="welcome")
* #Template()
*/
public function welcomeAction() {
return array();
}
Thanks,
Question after being edited
/**
* #Route("/welcome", name="welcome", defaults={"_locale" = "en"})
* #Route("/bienvenue", name="welcome", defaults={"_locale" = "fr"})
* #Route("/willkommen", name="welcome", defaults={"_locale" = "de"})
* #Template()
*/
public function welcomeAction() {
return array();
}
Now, what is happening with this new annotations:
the selected route is always the last one which is /willkommen (if you change the order the routes, the selected route is still the last one)
the _locale is set the the locale of the last route which 'de' according to the annotation above.
So, any proposal?
Thanks...
I found the solution. You just have to set run the following command
php app/console translation:extract fr --bundle=MinnTestBundle
--enable-extractor=jms_i18n_routing --output-format=yml
Then, minn/TestBundle/Ressources/translations/routes.fr.yml file will be generated. Customize you route translations & that is it!
Hope it will help others...
You can add multiple route annotations.
/**
* #Route("/welcome", name="welcome", defaults={"_locale" = "en"})
* #Route("/bienvenue", name="welcome", defaults={"_locale" = "fr"})
* #Template()
*/

copy object Inheritance Mapping doctrine2

i have the following entity:
/**
* #ORM\Table(name="event")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="eventtype", type="integer")
* #ORM\DiscriminatorMap({1 = "eventClub", 2 = "eventLive", 3 = "eventBar", 4 = "eventGeneric" })
*/
class P1event extends AbstractEntity {
/**
*
* #var List[] $lists
*
* #ORM\OneToMany(targetEntity="List", mappedBy="fkevent", cascade={"persist", "merge"})"
*/
private $lists;
A user should have the possibility to change the eventtype via a form. By changing the evetntype, i must create a new Object becaus of my table inheritance (doctrine doc).
I have no idea how i can change the lists of the copied event to the new event inside one transaction. Has anybody an idea how to handle it correctly? Thank you very much.
In a similar situation, I just passed GET parameter type, then in the controller created an object of the desired type and transferred it to the form. If I understand your question correctly.
After created a new event object, call
$eventY->setLists($eventX->getLists());
doen't work ?

Resources