In my Controller I have 2 Actions with annotations:
/**
* Lists all Mains entities.
*
* @Route("/{lang}/{main_name}", defaults={"lang" = "de"})
* @Method("GET")
* @Template()
*/
public function mainAction($lang,$main_name)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('MyWebsiteBundle:Main')->findOneBy(array('name'=>$main_name));
echo $entity->getContent();
die;
}
/**
* Lists all Branches.
*
* @Route("/{lang}/{branch}/b{id}", defaults={"lang" = "de"})
* @Method("GET")
* @Template()
*/
public function branchAction($lang,$id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('MyWebsiteBundle:Branch')->find($id);
echo $entity->getMain()." > ".$entity->getName()."<br><br>";
echo $entity->getContent();
die;
}
When I call the mainAction Link without "lang" for example: "localhost/contact" instead of "localhost/en/contact" It works, th site "contact" is been called.
But when I call the branchAction like "localhost/products/b2" instead of "localhost/en/products/b2" I get an error because I think its been called the mainAction.
Is it possible what I want to do? THANKS FOR YOUR SUPPORT!!
It sounds like a simplified version of your requirements are:
/[az]{2}/
, then rewrite the URL, prepending /de/
to the original path. /[az]{2}/
, then handle it normally. If that's the case, then making this your first controller action would likely work:
/**
* @Route("/{path}", name = "rewrite", requirements = { "path" = "[a-zA-Z]{3,}" })
*/
public function rewriteAction($path) {
$defaultLanguage = "de";
return $this->redirect("$defaultLanguage/$path");
}
This uses the requirements
field to instruct Symfony to only use this route if the path begins with 3 letters (ie more than 2 letters).
There's a few nuances you'll need to handle (removing extra slashes, handling one-character paths like /a/
, handling paths with digits like /t5
, etc.), but I think this might be a good start.
You could also handle this on the server level, for example by using Apache URL redirects.
Finally, please don't echo $content;
and die;
in your controller methods. That defeats the purpose of having an MVC framework. Rather, you should use return new Response($content);
. This way, if Symfony has any post-processing to do after the controller method is called, it can do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.