Symfony, routing.yml is not working - php

I have a project in sympfony.
Im trying to add a new page, and i have done usual steps, but nothing seems to work.
I have added the following to src/ITWB/FrontBundle/Resources/config/routing.yml:
itwb_front_abc:
pattern: /abcCenter
defaults: { _controller: ITWBFrontBundle:Footer:abcCenter }
In my src/ITWB/FrontBundle/Controller/FooterController.php i have added this:
public function abcCenterAction() {
return $this->render('ITWBFrontBundle::test.html.twig');
}
But it's not working.
I have tried putting and "echo" inside the action, and it isnt displaying, so, the problem is in the routing, domain.com/abcCenter its not being recognized. I have also tried with other names and it's the same.
What can i do ?
Thanks

You forgot the indent the options. Indenting is a really important aspect of Yaml:
itwb_front_abc:
pattern: /abcCenter
defaults: { _controller: ITWBFrontBundle:Footer:abcCenter }

Take care of indent, like Wouter J says.
You can access abcCenter via domain.com/app_dev.php/abcCenter (not domain.com/abcCenter) if your website is running local, otherwise you have to clear cache:
php app/console cache:clear --env=prod --no-debug
How to deploy a Symfony2 application.

The first place I would look: in app/config/routing.yml, do you have a reference to your bundle's routing.yml?
The app/config/routing.yml file should contain a couple of lines something like this:
front_bundle:
resource: "#FrontBundle/Resources/config/routing.yml"
Of course maybe you've done this already as part of the "usual steps" you mention?

Related

Is it possible to construct a Symfony path using only parameters?

I would like to reduce the number of repetitive code and give a canonical URL in my Drupal 8 application. Since the routing system is built on Symfony, I included it in the title.
I am constructing paths under routes in my mymodule.routing.yml file. I want to match a specified number of different strings in the first argument, and a slug which can be any string in the second argument. It looks like this:
entity.my_entity.canonical:
path: '/{type}/{slug}'
defaults:
_controller: '\namespace\PostController::show'
requirements:
_permission: 'perm'
type: different|strings|that|can|match|
Now, when I try to access using for example /match/some-slug then it just says "Page not found".
If I something static to the path, for example path: '/j/{type}/{slug}', then it works as expected when I open /j/match/some-slug in the browser.
My boss doesn't like any unnecessary characters in the URL though, so I would like to achieve this by using two parameters, like shown in the first example.
As Yonel mentioned in the comments you can use debug:router to check all your routes. I don't see anything wrong with your code.
Try running bin/console router:match "/match/blaaa" and if you see some controller that isn't the one you want then you'll need to change the route. It shouldn't be the case though because you're getting a 404.
Here's my exact setup that works
routing.yml:
entity.my_entity.canonical:
path: '/{type}/{slug}'
defaults:
_controller: 'MyBundle:Something:foo'
requirements:
type: different|strings|that|can|match|
Inside MyBundle\SomethingController:
public function fooAction($id)
{
return new Response("bar");
}
Then going to http://localhost/match/fom shows the "bar" response.
I have read the documentation again (RTM), and found out that it is not possible in Drupal 8, while it is possible in Symfony.
Note that the first item of the path must not be dynamic.
Source: Structure of routes in Drupal 8

Need Assistance with Symfony 2.7 creating first page

I am trying to learn the Symfony framework and struggling with it. The instructions are not very helpful or assume I know a lot more than I know. I am just trying to create a single web page with proper route and controller. I have been googling to find answers and made some progress but no luck yet. Right now I just have the standard install of Symfony with just default bundles etc. I created a project called "gtest3" and chose PHP for it...
I am not sure where I put the new route in (what file) or maybe it needs to be put in more than one file?
I found the "routing.yml" file which seems that is where I need to put it...
here is what is in there right now:
gtest3:
resource: "#gtest3Bundle/Resources/config/routing.php"
prefix: /
app:
resource: "#AppBundle/Controller/"
type: annotation
I am guessing I need to add something to this and put the location/filename of the controller? I have tried doing this a few ways and just get errors.
There is also the "routing.php" file that is referenced in the above code. I am not sure if this is the "controller" or if it is an additional piece of the "route". Here is the code from that file:
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('gtest3_homepage', new Route('/hello/{name}', array(
'_controller' => 'gtest3Bundle:Default:index',
)));
return $collection;
I am not sure what if anything I would add here.
Finally - there is the "DefaultConroller.php" file I found as well which may also be the controller. I dont think I need to include the code of that file here.
So - all I am trying to do is create a route of maybe "/gman" and then have the controller just echo something on the page. Super basic stuff. And I cannot figure out how to get this going.
Can anyone help with this? Thanks so much...
You can define your routes in three ways, either by using yml files, xml files, or by using a php file. This is documented behaviour.
You are from the looks of your routing.yml trying to set up a php version. I would not recommend it, and instead use configuration over coding the routing.
The annotation example would look like:
Adding a controller:
namespace Gtest3Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class Gtest3Bundle extends Controller
{
/**
* #Route("/hello/{name}")
* #Template()
*/
public function indexAction($name)
{
return array('name' => $name);
}
}
And add in your app/config/routing.yml:
gtest3:
resource: "#Gtest3Rights/Controller/"
type: annotation
prefix: /what-ever-you-want
You can check what kind of routes you have defined by using:
./app/console router:debug
If it doesn't appear hear, you have something misconfigured.
Please be advised that your bundle names breaks the convention of how bundles should be named in the symfony2 context.
It is advised to use NamespaceProjectBundle. This also documented. If you are stuck, try generating a bundle via the ./app/console generate:bundle. This way you can create a whole symfony2 structure which should show the default page hello/foo page just fine.
If it doesn't seem to run at all, make sure you have registered your bundle at the in the app/AppKernel.php file in the registerBundles() method.
To configure routes you can use yml, php or xml file. You can specify it in app/config/config.yml
framework:
router:
resource: "%kernel.root_dir%/config/routing.yml"
It's where you can check which file is used now.
There are some manners to store the routes.
app:
resource: "#AppBundle/Controller/"
type: annotation
This is how you use routes by writing annotations above your actions (eg indexAction) inside your controller class. Read more.
Another common approach is to build one or more .yml files inside each Bundle.
in app/config/routing.yml you should write this:
app:
resource: "#AppBundle/Resources/config/routing.yml"
prefix: /
Then you need to create the file (and directories if necessary) src/AppBundle/Resources/config/routing.yml and add the following content:
app_homepage:
path: /
defaults: { _controller: AppBundle:Default:index }
It will then try to find the DefaultController and fires the indexAction in the AppBundle (src/AppBundle/Controller/DefaultController.php).
To debug your routes simply type in your console from your projects directory:
app/console router:debug

Unable to remove cached page in Symfony 2.6

I am experiencing a weird behaviour with Symfony 2.6
I have a page that lists my users and its routing is in routing.yml as follows:
nononsense_users_homepage:
path: /{page}/{query}
defaults: { _controller: NononsenseUserBundle:Users:index, page: 1, query: 'q'}
Even if I remove the cache the "hard way" by deleting the app/cache folder it does not matter what I do with the controller I always get the same web page!!
Of course I also used:
php app/console cache:clear
with equivalent results setting the env flag also.
If I replace my routing with, for example:
nononsense_users_homepage:
path: /{page}/{query}
defaults: { _controller: kkkkkkkkk, page: 1, query: 'q'}
The page keeps showing. But if I remove the page or query parts the corresponding twig complains.
I changed other actions and routes in the same bundle and I get the expected results when, for example, I replace a whole action by an exit() call...so it is not I am changing the wrong file :-)
I stopped and run several times the server from the console and I even change browsers and users (you have to be logged to access that page) and nothing changes, there is nothing I can do to get an error page!!!
Nevertheless the action has some DB calls to the UsersRepository and if I include an exit() there I get an empty page as expected.
Does anyone know what I am doing wrong.
If you changed the controller in your routing.yml file and the controller does not change, you are probably using a different route. In dev mode, can you check which route is matched and you will most likely see that a different route is matching causing the error.

How to import resources from a given controller directory structure in Symfony2

I'm working on an application that is growing rapidly which is causing more and more controllers over time and I'm always trying to maintain good practices for do not have as many lines per controller. Right now are almost 40 controllers in Controller directory and it's a bit complicated found one when need to add code or edit or something else so I'm thinking in order them inside subfolders under Controller directory as follow:
src\
AppBundle\
Controller\
Comunes\
CiudadController.php
DuplicadosCedulaController.php
...
RegistroUsuarios\
EmpresaController.php
NaturalController.php
...
RPNI\
CodigoArancelarioController.php
RPNIProductoPaso1Controller.php
...
BuscarEmpresaController.php
DistribuidorController.php
...
But that reorder is causing this error on my application:
FileLoaderLoadException: Cannot import resource
"/var/www/html/project.dev/src/AppBundle/Controller/" from
"/var/www/html/projectdev/app/config/routing.yml". (Class
AppBundle\Controller\EmpresaController does not exist)
Since apparently Symfony is not able to find the controller class when it's not on Controller directory. I've found this topic but is not clear to me what the problem is. I don't know if this is possible or not I read Controller Naming Pattern at Symfony docs but is not so helpful. Any advice around this? A workaround? Suggestions for a better project structure organization?
Note: I made only one bundle because has no sense more than one since the application will not works for separate bundles so following Syfmony Best Practices I come with only one bundle
Edit
This is weird and I don't know how all is working again, I've move all the controllers from Controller to subfolders inside that directory as my example above shows and didn't change nothing at all on routing.yml and Symfony keep getting controllers even if they are in subfolders: amazing!! Ahhh very important just remember CLEAR CACHE command, the most important Symfony command I believe, many of developers issues are cause of this, I forgot complete to clear it and test changes!!
Here is a working example:
routing:
st_mainsiteweb_admin_subsite_create_template:
path: /subsite/create-template
defaults:
_controller: STMainSiteWebBundle:Admin/SubSite:createTemplate
directory structure:
ST\
MainSiteWebBundle\
Controller\
Admin\
SubSiteController -> createTemplateAction
Is this are you looking for?
I do it 2h, now is ok, no routing, no other file.
Just change the namespace of
CiudadController.php
DuplicadosCedulaController.php
....
from AppBundle\Controller to AppBundle\Controller\Comunes
I never tried that so it's just a theoretical answer. If you want to have the controllers like this is perfectly fine, but then you should need to map them in the routing.
Controller\
Comunes\
CiudadController.php
DuplicadosCedulaController.php
Then will be matched in routing yaml:
comunes:
resource: "#yourBundle/Controller/Comunes"
type: annotation
And so on for every different directory. As far as I know they are automatically loaded from Controller/ directory, but if you place them on any other place you need to reference them in the routing.

Routing in Symfony2

How to setup default routing in Symfony2?
In Symfony1 it looked something like this:
homepage:
url: /
param: { module: default, action: index }
default_symfony:
url: /symfony/:action/...
param: { module: default }
default_index:
url: /:module
param: { action: index }
default:
url: /:module/:action/...
I was looking through the cookbook for an answer to this, and think I've found it here. By default, all route parameters have a hidden requirement that they match any character except the / character ([^/]+), but this behaviour can be overridden with the requirements keyword, by forcing it to match any character.
The following should create a default route that catches all others - and as such, should come last in your routing config, as any following routes will never match. To ensure it matches "/" as well, a default value for the url parameter is included.
default_route:
pattern: /{url}
defaults: { _controller: AcmeBundle:Default:index, url: "index" }
requirements:
url: ".+"
I don't think it's possible with the standard routing component.
Take a look to this bundle, it might help :
https://github.com/hidenorigoto/DefaultRouteBundle
// Symfony2 PR10
in routing.yml:
default:
pattern: /{_controller}
It enables you to use this kind of urls: http://localhost/MySuperBundle:MyController:myview
Symfony2 standard routing component does not support it, but this bundle fills the gap Symfony1 left:
https://github.com/LeaseWeb/LswDefaultRoutingBundle
It does what you expect. You can default route a bundle using this syntax:
FosUserBundle:
resource: "#FosUserBundle"
prefix: /
type: default
It scans your bundle and automatically adds routes to your router table that you can debug by executing:
app/console router:debug
Example of automatically added default routes:
[router] Current routes
Name Method Pattern
fos_user.user.login_check ANY /user/login_check.{_format}
fos_user.user.logout ANY /user/logout.{_format}
fos_user.user.login ANY /user/login.{_format}
...
You see that it also supports the automatic "format" selection by using a file extension (html, json or xml).
Here is an example: http://docs.symfony-reloaded.org/master/quick_tour/the_big_picture.html#routing
A route definition has only one mandatory parameter pattern and three optionals parameters defaults, requirements and options.
Here's a route from my own project:
video:
pattern: /watch/{id}/{slug}
defaults: { _controller: SiteBundle:Video:watch }
requirements: { id: "\d+", slug: "[\w-]+"
Alternatively, you can use #Route annotation directly in a controller file. see https://github.com/sensio/SensioFrameworkExtraBundle/blob/master/Resources/doc/annotations/routing.rst
As for the default routes, I think Symfony2 encourages explicit route mapping.
Create a default route is not a good way of programming. Why? Because for this reason was implemented Exception.
Symfony2 is built just to do right things in the right way.
If you want to redirect all "not found" routes you should use exception, like NotFound404 or something similar. You can even customise this page at your own.
One route is for one purpose. Always. Other think is bad.
You could create your own bundle that handled all requests and used URL parameters to construct a string to pass to the controller's forward method. But that's pretty crappy, I'd go with well defined routes, it keeps your URLs cleaner, and decouples the URL and controller names. If you rename a bundle or something, do you then have to refactor your URLs?
If you want to create a "catch all", your best bet would be to hook on the KernelEvents::EXCEPTION event. This event gets triggered whenever an Exception falls through to the HttpKernel, this includes the NotFoundHttpException thrown when the router cannot resolve a route to a Controller.
The effect would be similar to Symfony's stylized 404 page that gets rendered when you send the request through app_dev.php. Instead of returning a 404, you perform whatever logic you're looking to.
It depends... Some of mine look like this:
api_email:
resource: "#MApiBundle/Resources/config/routing_email.yml"
prefix: /
and some look like
api_images:
path: /images/{listingId}/{width}/{fileName}
defaults: { _controller: ApiBundle:Image:view, listingId: null, width: null, fileName: null }
methods: [GET]
requirements:
fileName: .+

Categories