CakePHP3 routing: pass static variable to controller action - cakephp

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!

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()

Related

CakePHP 3 routing with parameters

I'm trying to create SEO friendly routing. I have a website with hotels and hotel rooms. I want to create a route progression that routes to different controllers/actions.
I want my urls to look like www.hotelwebsite.com/language/hotel-name/room-name
Here are the three routes I need:
If the url has a language parameter + 2 parameters:
$routes->connect('/:language/:hotelname/:room/', ['controller' => 'rooms', 'action' => 'viewRoom']);
where
public function viewRoom($hotel_slug, $room_slug)
in which
:hotelname == $hotel_slug and :room == $room_slug
If the url has a language parameter + 1 parameter:
$routes->connect('/:language/:hotelname/', ['controller' => 'hotels', 'action' => 'viewHotel']);
where
public function viewHotel($hotel_slug)
in which
:hotelname == $hotel_slug
Otherwise use my standard route
$routes->connect('/:language/:controller/:action/*');
Is this even remotely possible?
Surely that's possible, the example routes are almost ready to go, you just need to define which elements should be passed as function arguments, and you most probably have to limit what :hotelname and/or :room matches, as otherwise the router will not be able to differentiate between:
/:language/:hotelname/:room
and:
/:language/:controller/:action
and the first route would always win.
Passing as arguments can be configured via the pass option, like:
$routes->connect(
'/:language/:hotelname/:room',
[
'controller' => 'rooms',
'action' => 'viewRoom'
],
[
'pass' => ['hotelname', 'room']
]
);
$routes->connect(
'/:language/:hotelname',
[
'controller' => 'rooms',
'action' => 'viewHotel'
],
[
'pass' => ['hotelname']
]
);
Restricting what an elment matches can be done via regular expressions like:
$routes->connect(
'/:language/:hotelname/:room',
[
'controller' => 'rooms',
'action' => 'viewRoom'
],
[
'pass' => ['hotelname', 'room'],
'hotelname' => '(?:name1|name2|name3)',
'room' => '[0-9]+'
]
);
If you cannot restrict the elements that way because they are dynamic and/or there are too many, then you'll have to try a custom route class that for example matches against the database, check for example Mapping slugs from database in routing.
See also
API > \Cake\Routing\RouteBuilder::connect()
Cookbook > Routing > Route Elements
Cookbook > Routing > Passing Parameters to Action

want to remove action name from url CakePHP

i am working on a Cakephp 2.x.. i want to remove the action or controller name from url ... for example i am facing a problem is like that
i have a function name index on my Messages controller in which all the mobile numbers are displaying
the url is
www.myweb.com/Messages
now in my controller there is a second function whose name is messages in which i am getting the messages against the mobile number
so now my url becomes after clicking the number is
www.myweb.com/Messages/messages/823214
now i want to remove the action name messages because it looks weired...
want to have a url like this
www.myweb.com/Messages/823214
When connecting routes using Route elements you may want to have routed elements be passed arguments instead. By using the 3rd argument of Router::connect() you can define which route elements should also be made available as passed arguments:
// SomeController.php
public function messages($phoneNumber = null) {
// some code here...
}
// routes.php
Router::connect(
'/messages/:id', // E.g. /messages/number
array('controller' => 'messages', 'action' => 'messages'),
array(
// order matters since this will simply map ":id"
'id' => '[0-9]+'
)
);
and you can also refer link above given by me, hope it will work for you.
let me know if i can help you more.
REST Routing
The example in the question looks similar to REST routing, a built in feature which would map:
GET /recipes/123 RecipesController::view(123)
To enable rest routing just use Router::mapResources('controllername');
Individual route
If you want only to write a route for the one case in the question
it's necessary to use a star route:
Router::connect('/messages/*',
array(
'controller' => 'messages',
'action' => 'messages'
)
);
Usage:
echo Router::url(array(
'controller' => 'messages',
'action' => 'messages',
823214
));
// /messages/823214
This has drawbacks because it's not possible with this kind of route to validate what comes after /messages/. To avoid that requires using route parameters.
Router::connect('/messages/:id',
array(
'controller' => 'messages',
'action' => 'messages'
),
array(
'id' => '\d+',
)
);
Usage:
echo Router::url(array(
'controller' => 'messages',
'action' => 'messages',
'id' => 823214 // <- different usage
));
// /messages/823214
in config/routes.php
$routes->connect('/NAME-YOU-WANT/:id',
['controller' => 'CONTROLLER-NAME','action'=>'ACTIOn-NAME'])->setPass(['id'])->setPatterns(['id' => '[0-9]+']
);
You can use Cake-PHP's Routing Features. Check out this page.

Routing with named parameters

I have a URL that contains named parameters, which I want to map to a more user friendly URL.
Take, for example, the following URL:
/videos/index/sort:published/direction:desc
I want to map this to a more friendly URL, like:
/videos/recent
I have tried setting it up in the Router, but it doesn't work.
Code samples from the Router:
Router::connect(
'/videos/recent/*',
array('controller' => 'videos', 'action' => 'index'),
array('sort' => 'published', 'direction' => 'desc'
));
Which doesn't work. And the following also doesn't work:
Router::connect(
'/videos/recent/*',
array('controller' => 'videos', 'action' => 'index', 'sort' => 'published', 'direction' => 'desc'));
Any ideas?
Use get args
The easiest way to have routes work is to avoid named arguments all together. With pagination thats easy to achieve using appropriate config:
class FoosController extends AppController {
public $components = array(
'Paginator' => array(
'paramType' => 'querystring'
)
);
}
In this way when you load /videos/recent you should find it includes urls of the form:
/videos/recent?page=2
/videos/recent?page=3
Instead of (due to route mismatching)
/videos/index/sort:published/direction:desc/page:2
/videos/index/sort:published/direction:desc/page:3
But if you really want to use named args
You'll need to update your route definition - there's no page in the route config:
Router::connect(
'/videos/recent/*',
array(
'controller' => 'videos',
'action' => 'index',
'sort' => 'published',
'direction' => 'desc'
)
);
As such, if there is a page named parameter (which there will be for all urls generated by the paginator helper), the route won't match. You should be able to fix that by adding page to the route definition:
Router::connect(
'/videos/recent/*',
array(
'controller' => 'videos',
'action' => 'index',
'sort' => 'published',
'direction' => 'desc',
'page' => 1
)
);
Though even if it works, you may find it to be fragile.
lets see on [Router::connect documentation](Routes are a way of connecting request urls to objects in your application)
Routes are a way of connecting request urls to objects in your application
So, it's map urls to objects and not url to url.
You have 2 options:
use Router::redirect
Something like that:
Router::redirect( '/videos/recent/*', '/videos/index/sort:published/direction:desc');
but seems that's not that you want exactly
use Router::connect
use normal Router::connect which will connect url to some action which make appropriate scope. Something like that:
Router::connect(
'/videos/recent/*',
array(
'controller' => 'videos',
'action' => 'recent'
)
);
and in VideosController
public function recent() {
$this->request->named['sort'] = 'published';
$this->request->named['direction'] = 'desc';
$this->index();
}
it works and I saw such usage, but not sure, that is will satisfy you too.
as for me, I like normal named cakephp parameters. If such scope (published and desc) is your default state, just code default state in index action. For over cases i think it's normal to use ordinary named parameters.

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

cakephp named parameters break REST based web service

I have a json REST based in the form of:
Router::mapResources('Test');
Which is equivalent to for the index method to:
Router::connect( '/Test',
array(
'controller' => 'ChannelSources',
'action' => 'index',
'[method]' => 'GET' ),
array();
I am trying to add support for named parameters this method.
but apparently its breaks the Router method as an index action is not part of the URL
i have tried using
Router::connectNamed(array('somenameparam'));
But it failed.
I would create a specific route so that you can pass in the right parameters, then you can pass your params into the route.
Have a look at, http://book.cakephp.org/2.0/en/development/routing.html#passing-parameters-to-action
Router::connect(
'/blog/:id-:slug', // E.g. /blog/3-CakePHP_Rocks
array('controller' => 'blog', 'action' => 'view'),
array(
// order matters since this will simply map ":id" to $articleId in your action
'pass' => array('id', 'slug'),
'id' => '[0-9]+'
)
);

Resources