Symfony2: No route found for "GET /lucky/controller/" - symfony

I'm trying to get started with Symfony2 and I'm getting stuck on the "create your first page" tutorial : http://symfony.com/doc/current/book/page_creation.html
I created the controller file (copy-pasted from tutorial) as E:\Web\project\src\AppBundle\Controller\LuckyController.php :
<?php
// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class LuckyController
{
/**
* #Route("/lucky/number")
*/
public function numberAction()
{
$number = rand(0, 100);
return new Response(
'<html><body>Lucky number: '.$number.'</body></html>'
);
}
}
I didn't make any change to any other file.
When I go to the URL 127.0.0.1/project/web/app_dev.php/lucky/controller (127.0.0.1 is the virtual host for E:\Web) I keep getting the error "No route found for "GET /lucky/controller"".
404 Not Found - NotFoundHttpException
1 linked Exception:
[2/2] NotFoundHttpException: No route found for "GET /lucky/controller/"
[1/2] ResourceNotFoundException:
If I remove the "/web" from the URL, 127.0.0.1/project/app_dev.php/lucky/controller, I get a 404 error.
I'm pretty sure the error comes from the folder structure since the files are unmodified. Similar issue was reported here but none of these suggestions solved my error.

Just figured out that the URL should be 127.0.0.1/project/web/app_dev.php/lucky/number (and not controller). Problem solved.

Be careful, your route is /lucky/number not /lucky/controller.
So, you have to try with 127.0.0.1/project/web/app_dev.php/lucky/number

Related

App\\Entity\\Project object not found by the #ParamConverter annotation

Bit of an obscure one this. I'm reading that Symfony get's muddled when dealing with more than one route of a similar pattern. Here goes, this is what I've tried thus far:-
For starters, I hit the endpoint: https://127.0.0.1:8000/api/contracts/12345/new which returns the 404 error in full:-
{type: "https://tools.ietf.org/html/rfc2616#section-10", title: "An error occurred", status: 404,…}
class
:
"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException"
detail
:
"App\\Entity\\Project object not found by the #ParamConverter annotation."
status
:
404
title
:
"An error occurred"
trace
:
[{namespace: "", short_class: "", class: "", type: "", function: "",…},…]
type
:
"https://tools.ietf.org/html/rfc2616#section-10"
Here's a snapshot of my URL patterns:-
docker-compose exec app bin/console debug:router
new_contract POST ANY ANY /api/contracts/{id}/new
api_edit_project POST ANY ANY /api/contracts/{id}/edit
They're very similar but I'm using the new endpoint from above. Here's the controller:-
/**
* #Route("/api")
*/
class ContractController extends BaseApiController
{
/**
* #Post ("/contracts/{id}/new", name="new_contract")
*/
public function postNewContractAction(){
// -- we don't hit this method at all
}
/**
* #Post ("/contracts/{id}/edit", name="api_edit_project")
*/
public function postEditContractAction(){}
}
Further to this, I've tried moving the controller methods around in terms of ordering, but this has no effect.
Any ideas?
As statet in the Symfony Documentation, receiving a 404 Error, when trying to fetch an object by it's id automatically using the paramConverter magic, this usually means there is no data for that id.
If no Post object is found, a 404 Response is generated;
I suspect there is no Project with id=12345.
Why are you asking for an {id} in the /new route, actually? To my understanding you would not have an ID in that case, yet.
I always try to set the parameters at last position in routes, as it may avoid route collisions.

Symfony\Component\HttpKernel\Exception\ NotFoundHttpException

I am following the openclassrooms tutorial on symfony. I am now currently at the chapter "Les controleurs avec Symfony".
I try to open http://localhost/Symfony/web/app_dev.php and get this error
NotFoundHttpException
I suspect the error to come from AdvertController.php.
But I compared it with the given code at the tutorial. And it is exactly the same. I tried then to delete the cache but it does not function. I will open another question for that.
Here is the AdvertController.php code:
<?php
//src/Neo/PlatformBundle/Controller/AdvertController.php
namespace Neo\PlatformBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
//use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class AdvertController extends Controller
{
public function indexAction()
{
$url= $this->get('router')->generate(
'neo_platform_view', //first argument : path name
array('id' => 5)
);
return new Response("The url of the announcement is:".$url);
}
public function viewAction($id)
{
return new Response("Desplay of the announcment with id:".$id);
}
public function viewSlugAction($slug, $year, $_format)
{
return new Response(
"We could desplay the announcment conrresponding the the slug
'".$slug."', created in ".$year." and with the format ".$_format."."
);
}
}
?>
If you would like me to post other parts of code, please let me know.
I have no idea, where to look at.
Thank you very much!
You can try to dump your routes with the command php bin/console debug:router or app/console for symfony <3.0 to see if there is a route your your desired path.
If you have the prefix /platform, your paths inside your controller are now /platform/path instead of /path.
You need a default route for your root path.
The message error is very explicit, there are not routes for "/". Try to verify your routing.yml

Symfony Routing "_locale" parameter not accepted

I have a problem with the symfony routing.
For an multilanguage projekt I render a Twig template via a job queue for mailing. In this template is a link to a route that requires the "_locale" parameter with "de" or "en" for example. I use the function "{{ url('route', {'_locale': 'de'}) }}" to generate the url.
By rendering the template, I got the following error message:
[Twig_Error_Runtime]
An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("_locale") to generate a URL for route "Route".") in "TemplatePath" at line 5.
Whats my mistake?
Thanks for help
When you are generating URL route, via CLI, the Symfony kernel is missing a HTTP Request, and a Routing->RequestContext.
Thats why, the URL generator cannot find _locale parameter.
To fix it, you must manually create a RequestContext, so, in your command:
$this->getContainer()->get('router')
->setContext(
(new RequestContext())
->setParameter('_locale', 'fr')
);
class BaseCommand extends ContainerAwareCommand
{
protected function getLocale()
{
return $this->getContainer()->get('translator')->getLocale();
}
protected function render($view, $data)
{
return $this->getContainer()->get('templating')->render($view, $data);
}
}
in command
class SomeCommand extends BaseCommand
{
...
$this->render($view, array_merge($data, ['_locale' => $this->getLocale()])
}
in view
{{url('any', {param: 'foo'}|merge(_locale is defined ? {'_locale': _locale } : {}))}}
It's necro time :)
I'm just guessing here, but there's a couple things you can try.
Can you set the locale in your command?
Set the locale for the translator bundle:
$this->getContainer()->get('translator')->setLocale('de');
Set the locale for this session:
$this->getContainer()->get('session')->setLocale('de);
Internationalized routing for Symfony 4.1 and higher
If this applies to you, try this:
url('route.de', {'_locale': 'de'}) }}"
Does your route have 'de' and 'en' set as a requirement?
/**
* Matches /route
* #Route(
* "/route/{_locale}",
* requirements={
* '_locale': 'en|de'
* },
* name="route"
* )
*/
It's an old question but this might help someone out.

Symfony 2 redirect route

I have the following route that works via a get:
CanopyAbcBundle_crud_success:
pattern: /crud/success/
defaults: { _controller: CanopyAbcBundle:Crud:success }
requirements:
_method: GET
Where Canopy is the namespace, the bundle is AbcBundle, controller Crud, action is success.
The following fails:
return $this->redirect($this->generateUrl('crud_success'));
Unable to generate a URL for the named route "crud_success" as such route does not exist.
500 Internal Server Error - RouteNotFoundException
How can I redirect with generateUrl()?
Clear your cache using php app/console cache:clear
return $this->redirect($this->generateUrl('CanopyAbcBundle_crud_success'));
If parameters are required pass like this:
return $this->redirect($this->generateUrl('CanopyAbcBundle_crud_success', array('param1' => $param1)), 301);
The first line of your YAML is the route name that should be used with the router component. You're trying to generate a URL for the wrong route name, yours is CanopyAbcBundle_crud_success, not crud_success.
Also, generateUrl() method does what it says: it generates a URL from route name and parameters (it they are passed). To return a 403 redirect response, you could either use $this->redirect($this->generateUrl('CanopyAbcBundle_crud_success')) which is built into the Controller base class, or you could return an instance of Symfony\Component\HttpFoundation\RedirectResponse like this:
public function yourAction()
{
return new RedirectResponse($this->generateUrl('CanopyAbcBundle_crud_success'));
}

Symfony2 template configuration from routing.yml

When dealing with the Sylius e-commerce bundles I have found what seems to be a way of configurig the template for a route, that I didn't know:
I have tested in a fresh Symfony RC 2.2.0 with vendors installation.
This would be in the routing.yml
_welcome:
pattern: /
defaults:
_controller: AcmeDemoBundle:Welcome:index
_template: AcmeDemoBundle:Welcome:index # added by me
this generates an error:
FatalErrorException: Error: Call to a member function getTemplate() on
a non-object in
.... \vendor\sensio\framework-extra-bundle\Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener.php
line 62
now, in TemplateListener, what we have is:
if (!$configuration = $request->attributes->get('_template')) {
return;
}
if (!$configuration->getTemplate()) {
$guesser = $this->container->get('sensio_framework_extra.view.guesser');
$configuration->setTemplate($guesser->guessTemplateName($controller, $request, $configuration->getEngine()));
}
$configuration is a String, actually the template I put in routing.yml (AcmeDemoBundle:Welcome:index). Checked by adding a var_dump and also inspecting ParameterBag -> get method which is what $request->attributes is.
So. Why TemplateListener is expecting an object? What am I missing? Am I missconfiguring in routing.yml?
This parameter is not available in Symfony itself.
Feature is provided by SyliusResourceBundle and available only in Sylius controllers.
And apparently _template request attribute conflicts with SensioFrameworkExtraBundle, which uses same name to store object.
We have to move those parameters one config node deeper, to avoid such problems in future.
You can keep an eye on the https://github.com/Sylius/SyliusResourceBundle repository, fix should arrive today.

Resources