2
votes

I am working on cakephp project. I have removed index.php from URL using .htaccess file and now I want to remove view name from URL & add some other two varying parameter. Suppose I choose country & city then these two parameter should appear in URL on selecting them.

The problem I am facing is as cakephp takes

www.example.com/Controllername/viewname

But my requirement is like this

www.example.com/Controllername/param1/param2

If I pass this way It looks for param1 as controller and param2 as view.

Initially should be like:

www.example.com/Controllername/
2

2 Answers

2
votes

In your APP/routes.php:

// www.example/com/Controllername
Router::connect('/Controllername', 
    array('controller'=>'Controllername', 'action'=>'index'));

// www.example.com/Controllername/param1/param2
Router::connect('/Controllername/:param1/:param2',
    array('controller'=>'Controllername', 'action'=>'index'), 
    array('pass' => array('param1', 'param2')));

and your controller:

// set to null/a value to prevent missing parameter errors
public function index($param1=null, $param2=null) {
   //echo $param1 . ' and ' . $param2;
}

When generating links:

array('controller'=>'Controllername', 'action'=>'index', 'param1'=>'foo', 'param2'=>'bar');

Order matters. Change paramX to anything you want i.e. country and town

note this does not cover: controllername/param1 - both must be present in this example.

There are other ways to achieve this.

0
votes

I think you should first make sure that mod-rewrite module is enabled. You shouldn't have had to remove index.php from the url using .htaccess if mod_rewrite were enabled. Check how to enable it in the manual of your webserver and the default .htaccess of cakephp should be able to handle the rest of the routing for you.

After you have enable rewrite module, you can modify the routes as pointed out by @Ross in the previous answer in you APP/routes.php:

// www.example/com/Controllername
Router::connect('/Controllername', 
array('controller'=>'Controllername', 'action'=>'index'));

// www.example.com/Controllername/param1/param2
Router::connect('/Controllername/:param1/:param2',
array('controller'=>'Controllername', 'action'=>'index'), 
array('pass' => array('param1', 'param2')));