Anuj TBE
Anuj TBE

Reputation: 9826

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

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?

Upvotes: 1

Views: 390

Answers (3)

Alex Stallen
Alex Stallen

Reputation: 2252

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.

Upvotes: 0

Jacek B Budzynski
Jacek B Budzynski

Reputation: 1413

$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

Upvotes: 1

Warren Sergent
Warren Sergent

Reputation: 2597

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.

Upvotes: 1

Related Questions