How to route to a specific method in cakePHP?

1.3k views Asked by At

my route:

Router::connect('/', array('controller' => 'users', 'action' => 'homepage'));

Router::connect('/admin', array('controller' => 'users', 'action' => 'dashboard', 'admin' => true));

my Controller

class BrandsController extends AppController {

/**
 * Components
 *
 * @var array
 */
public $components = array('Paginator', 'Session', 'Flash');


var $paginate = array('limit' => 100);

/**
 * admin_index method
 *
 * @return void
 */
public function admin_index()
{      
  index method      
}
 public function admin_searches() 
{
     searches method
}     

My link

<?php echo Router::url(array('controller' => 'brands', 'action' => 'searches')); ?>

I have a admin_searches.ctp file which has hello world text as well.

Problem is: When i have a href link as,

<a href="<?php echo Router::url(array('controller' => 'brands','action' => 'admin_index')); ?>">Brands List</a> 

it works fine and displays the index page. Now when i want to display a search page "admin_searches,ctp" it wont. How may I route in the link or amend route file so that when i call the above link it invokes search method in my controller class

2

There are 2 answers

0
mario On BEST ANSWER

This is a authentication issue. Everytime i try to create a new file eg: admin_search and a controller method called admin_search it echoes "you are not permitted to acess this location." Therefore, to overcome this issue i had to include authentication of a method in beforeFilter();

public function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow('admin_searches');
    }
13
Jason Joslin On

Assuming your admin_searches action is in your BrandsController you should print links in the view like this:

<?= $this->Html->link('admin searches',['controller' => 'brands', 'action'=>'admin_searches']); ?>

It will write the <a> tags for you as well. You are probably going to have to sub out the controller and action names, i just guessed. But it is the way to use the HTML helper to generate links

Rewriting url to map to your action

Its pretty straight forward in the documentation. in your routes.php file add something like:

Router::connect(
    '/brands/searches',
    array('controller' => 'brands', 'action' => 'admin_searches')
);

now /brands/searches will go to the admin_searches action in your brands controller

https://book.cakephp.org/2.0/en/development/routing.html#connecting-routes

UPDATE

you have told me the link generated is /magnus_backend/admin/brands/searches There is a couple of ways to route to it. I would probably look at rewriting the base url but this should work

Router::connect(
    '/magnus_backend/admin/brands/searches',
    array('controller' => 'brands', 'action' => 'admin_searches')
);