Reputation: 28853
I have a simple user system using CakePHP and you view profiles like so /users/view/11
where 11 would be the ID. What I want to do is change it so it uses the username instead so you'd get a url like /users/view/cameron
.
I know I could change this in the controller and also in the view for the action links BUT I was wondering if it was possible to change it in the routing so it would change it all automatically or would I still need to change the methods in the controller etc?
Examples would be great. Thanks
CODE BASED ON BELOW ANSWER:
function view ( $username = null )
{
$this->layout = 'page';
$this->set('users', $this->User->findByUsername($username));
$this->set('title_for_layout', $this->User->field('firstname') . ' ' . $this->User->field('lastname'));
}
but title doesn't work?
Upvotes: 0
Views: 140
Reputation: 333
Routing doesn't work that way, so you have to manually edit the links in every view. Or you could just use the passed id to search for the User record.
The $this->User->field function works without parameters if $this->User->id is set. You might want to do something like this:
function view ( $username = null )
{
$this->layout = 'page';
$users = $this->User->findByUsername($username);
if(sizeof($users))
{
$this->set('users', $users);
$this->set('title_for_layout', $users[0]['User']['firstname'] . ' ' . $users[0]['User']['lastname']);
}
else
{
$this->Session->setFlash('Invalid username');
}
}
Hope this helps.
Upvotes: 0
Reputation: 2126
You unfortunately cannot create a routing rule that will automatically do this. You should change your view() function to accept a username as a parameter, and then perform a find by username. ie:
function view($username = null) {
$this->set('user', $this->User->findByUsername($username));
}
Upvotes: 2