CakePHP 3 : link to any action in PagesController opens same action - cakephp

I have to link to different actions in PagesController.
I have created many static pages and for that I have defined an action like
public function contact(){
}
now when I access www.mysite.com/pages/contact instead of opening contact.ctp it opens the default display action.
The routes.php file contains
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
How can I access the static pages or other actions of PagesController?

$routes->connect('/pages/:action/*', ['controller' => 'Pages']);
Now you can call to diferent actions. e.g.
www.mysite.com/pages/contact
www.mysite.com/pages/about
www.mysite.com/pages/someaction

The default routing for the PagesController is to direct everything to the display action.
In order to add additional actions, you would need to route these specifically.
$routes->connect('/pages/contact', ['controller' => 'Pages', 'action' => 'contact']);
Or, alternatively, if you do not want everything to go through the display action, remove the specific line in routes.php that directs everything there. CakePHP would auto-route anything beginning with /pages/ to the PagesController, and anything after the slash to it's appropriate action.

If you make the view file src/Template/Pages/contact.ctp you can access it using the URL http://example.com/pages/contact
No need to change anythin in routes.php they are fine. No need to create a method in your PagesController, this is a simple and optional controller for serving up static content.

Related

CakePHP 3 - Rename controller in routes.php

What would be the correct way to reroute all actions from fakeController to controller1 using Cake's routing engine?
I'd like to reroute actions index and any other actions and also parameters.
app/fake/ => app/controller1/
app/fake/action1 => app/controller1/action1
app/fake/action2/any/params => app/controller1/action2/any/params
Is it possible with just one line of code?
Why I am doing this? - because in CakePHP 3 the routes are case-sensitive. I'd like to keep my controllers names UpperCase, but it results in paths like app/Users/login, if I write users it says usersController not found. If there is a way around this, I wouldn't need all this rerouting.
The default route is case-sensitive, yes, however by default there should be fallbacks defined using the InflectedRoute class, which behave as known from 2.x, ie it will inflect users to Users (as of 3.1.0 the default is DashedRoute, which inflects too).
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L73
If you want this to be the default behavior (note that this is relatively slow) for all routes, then simply set this to be the default via Router::defaultRouteClass()
Router::defaultRouteClass('InflectedRoute');
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L42
or in order to restrict it to a specific scope, use the fallbacks() method.
$routes->fallbacks('InflectedRoute');
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L73
Alternatively you could create appropriate routes for all your controllers, similar to as shown in your apps routes.php file:
Router::scope('/', function (\Cake\Routing\RouteBuilder $routes) {
// ...
$routes->connect('/users', ['controller' => 'Users', 'action' => 'index']);
$routes->connect('/users/:action/*', ['controller' => 'Users']);
$routes->connect('/foos', ['controller' => 'Foos', 'action' => 'index']);
$routes->connect('/foos/:action/*', ['controller' => 'Users']);
// and so on...
});
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L60-L62
See Cookbook > Routing for more information about routing.

How to access plugin in cakephp

I am new in cakephp, I want to call the plugin via the URL. Here is URL of
http://testproject.local/PluginName/ControllerName/ActionName
When I Run this URL at that time I found "Missing Controller" error.
Missing Controller
Error: <ControllerName>Controller could not be found.
Error: Create the class <ControllerName>Controller below in file: `app/Controller/<ControllerName>Controller.php`
It's showing me
`Exception Attributes: array ( 'class' => 'PracticeFusionController', 'plugin' => NULL, )`
Here is my routes.php
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/Pages/*', array('controller' => 'pages', 'action' => 'display'));
Router::connect('/gods/:action/*', array('plugin' => 'nova', 'controller' => 'gods'));
Router::connect('/gods', array('plugin' => 'nova', 'controller' => 'gods'));
Router::parseExtensions('json', 'xml');
Router::mapResources('events');
Router::connect('/<pluginName>', array('plugin' => '<pluginName>', 'controller' => '<ControllerName>'));
You can only load/open Plugin routes if you actually loaded the plugin in your project's bootstrap. You don't need to include a plugin route in your core app's routes.php. If you want to add plugin specific routes, you can load the plugin specific routes file, using the routes option. Note that by default all /plugin/controller/action routes are already routed properly, you don't need a separate routes file for that.
So, in your core app's app/Config/bootstrap.php, add:
CakePlugin::load('YourPlugin', array('routes' = true));
The routes from your plugin's Config/routes.php will then be loaded and can be used.
More details on this can also be found in the documentation.
If above solutions does not works, please load plugin like CakePlugin::load('YourPlugin', array('routes' => true)); Please note array passed is : array('routes' => true)

Cakephp route and prefix

I have a problem with Routes in CakePHP. Let me explain.
I'm using authentication through the Auth component. I have a routing prefix called account.
When I want to edit a user, I'm calling the users controller which gives me a URL like:
/account/users/edit/5
What I want is to have a URL like:
/account/edit/5
So I changed my router like this:
Router::connect('/:prefix/edit/:id',
array('controller' => 'users', 'action' => 'edit'),
array('pass' => array('id'), 'id' => '[0-9]+')
);
which worked when I try to access /account/edit/5
My problem is located in my view. How can I access this route using the Html->link helper?
So far, I'm just doing it like this:
'/'.$this->Session->read('Auth.User.role').'/edit/'.$this->Session->read('Auth.User.id')
But it's not really clean in my opinion. I want to use the helper.
Thanks a lot for your help
Using a prefix "account" would mean needing an action like "account_edit" in your controller. That's probably not what you want. Also why put the "id" in url when it's already there in the session? Why not just use url "/account" for all users and get the id (and role if required) from session in the action?
Router::connect('/account',
array('controller' => 'users', 'action' => 'edit')
);
This would be the clean way to generate required url:
$this->Html->link('Account', array(
'controller' => 'users',
'action' => 'edit'
));
// Will return url "/account"
In general always use array form to specify url to benefit from reverse routing.
everything is just fine except router. it should be
Router::connect('/account/*',
array('controller' => 'users', 'action' => 'edit')
);
and creating anchor link in various way using Helper you can CHECK HERE

Adding a controller function for the "home" view in CakePHP

When visiting a default CakePHP site, it takes you to "home.ctp" page.
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
I want to add a few elements there (like blog posts), so I thought I could just add this to the PagesController() class:
public function home() {
$this->set('blogposts', $this->Blogpost->find('all'));
}
But that does not work.
So: what is the correct way to add something like this on the home page (or any other page for that matter)
The preferred option is to create a custom route for the home page but you can also override the PagesController's display function
Option 1: (Preferred Method)
Router::connect('/', array('controller' => 'mycontroller', 'action' => 'myaction'));
Option 2
Router::connect('/', array('controller' => 'pages', 'action' => 'home'));
Option 3:
class PagesController {
function display()
{
// default controller code here
// your custom code here
}
}
The final option is using requestAction in your view, but it isn't recommended as it has a huge performance drawback
Option 4: (Not recommended)
$newsitems = $this->requestAction(array('controller' => 'newsitems', 'action' => 'getlatestnews', 'limit' => 10));
In fact, the action is display, home is a parameter. So your main method in the Controller Pages must call display, not home. After that, create display.ctp view.
Reference:
Routing
To actually answer the original question:
$this->loadModel('Blogpost');
Ideally the model should be called
$this->loadModel('BlogPost');

Cakephp, Route old google search results to new home page

I have created a new website for a company and I would like all the previous search engine results to be redirected. Since there were quite a few pages and most of them where using an id I would like to use something generic instead of re-routing all the old pages.
My first thought was to do that:
Router::connect('/*', array('controller' => 'pages', 'action' => 'display', 'home'));
And put that at the very end of the routes.php file [since it is prioritized] so that all requests not validating with previous route actions would return true with this one and redirect to homepage.
However this does not work.
When I use a different path on the Router it redirects successfully. For example if I give it:
Router::connect('/*', array('controller' => 'projects', 'action' => 'browser'));
it works fine. The problem arises when the controller used is pages, action display etc.
I'm pasting my routes.php file [since it is small] hoping that someone could give me a hint:
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
Router::connect('/company/*', array('controller' => 'articles', 'action' => 'view'));
Router::connect('/contact/*', array('controller' => 'contacts', 'action' => 'view'));
Router::connect('/lang/*', array('controller' => 'p28n', 'action' => 'change'));
Router::connect('/eng/*', array('controller' => 'p28n', 'action' => 'shuntRequest', 'lang' => 'eng'));
Router::connect('/gre/*', array('controller' => 'p28n', 'action' => 'shuntRequest', 'lang' => 'gre'));
Router::parseExtensions('xml');
Instead of trying to handle everything within the cakePHP route file, I would recommend that you use the .htaccess file to 301 redirect pages as necessary.
What you have above will not transfer the rankings over because as far as i can see there is no 301 redirect being outputted in any of the routes.php based solutions you proposed.
The bigger problem is that a Route doesn't redirect, it connects URLs with responses. In other words, it makes sure that your now invalid URLs still yield a valid page. Which is exactly the opposite of what you want to achieve.
You want to tell visitors that a URL that used to be valid isn't anymore. You do this by issuing appropriate HTTP response codes, 301 Moved Permanently in this case. Without doing this the URLs will still appear valid to search engines and they won't update their index.
You'd either have to connect all the invalid URLs via Routes to some controller action that'll issue a $this->redirect('...', 301) or you could use some .htaccess rules to redirect. Which one to use depends on the complexity of the redirect, but you'll probably be able to use simple .htaccess mod_rewrite rules.
There are enough examples on SO: https://stackoverflow.com/search?q=htaccess+301+redirect

Resources