PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] CakePHP3 routing: pass static variable to controller action

 February 05, 2022     cakephp, cakephp-3.0, internationalization, routing     No comments   

Issue

I trying to pass "language" param from CakePHP3 route, to the action, so I can set the language for those pages.

$routes->connect('/es/hola', ['controller' => 'StaticPages', 'action' => 'welcome']);
$routes->connect('/en/hello', ['controller' => 'StaticPages', 'action' => 'welcome']);

The only way I can make it work is using a dynamic parameter like this:

$routes->connect('/:lang/hola', ['controller' => 'StaticPages', 'action' => 'welcome'], ['pass' => ['lang']]);

But the problem is this route will be match:

/en/hola
/es/hello
...
/fr/hello

I think it should be another best way to do this in CakePHP3, but I can't find this.

Thanks!


Solution

If you don't want it to be dynamic, then you need to pass it in the defaults, ie alongside the controller and action:

$routes->connect(
    '/es/hola',
    [
        'controller' => 'StaticPages',
        'action' => 'welcome',
        'lang' => 'es'
    ]
);

In the controller the parameter will be available via the request object:

$lang = $this->request->getParam('lang'); // param('lang') before CakePHP 3.4

If you want it to be passed as an argument to the controller action, you can still define it to be passed via the pass option.

See also

  • Cookbook > Routing > Connecting Routes
  • API > \Cake\Routing\RouteBuilder::connect()


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing