Question

i was trying to add new routes to my Zend Framework 1 application. But it seems to understand my 2 params as one. How can i fix that?

$route = new Zend_Controller_Router_Route(':name-:type', array('controller' => 'tour', 'action' => 'index'));
$route = $routeLang->chain($route);
$router->addRoute('tour', $route);
Was it helpful?

Solution

Let me rephrase your question again so others can get it quickly:

How to pass 'name' and 'type' parameters all together connected by dash ('-'), so if going to url: 'tour/index/sampleName-sampleType', Zend can recognize name is 'sampleName', type is 'sampleType'?

You need: Zend_Controller_Router_Route_Regex()

If you want url to match: 'www.example.com/sampleName-sampleType'

protected function _initRoutes ()
{
    $this->bootstrap('frontController');
    $front = $this->getResource('frontController');
    $router = $front->getRouter();
    
    $route = new Zend_Controller_Router_Route_Regex('(.+)-(.+)', array('controller' => 'tour', 'action' => 'index'), array(1 => 'name', 2=>'type'), '%s-%s');
    $router->addRoute('tour', $route);
}

Or if you want to match: 'www.example.com/sampleName-tour-sampleType'

protected function _initRoutes ()
{
    $this->bootstrap('frontController');
    $front = $this->getResource('frontController');
    $router = $front->getRouter();
    
    $route = new Zend_Controller_Router_Route_Regex('(.+)-tour-(.+)', array('controller' => 'tour', 'action' => 'index'), array(1 => 'name', 2=>'type'), '%s-tour-%s');
    $router->addRoute('tour', $route);
}

Print it out in controller 'tour', action 'index':

echo '<br>Name is: ' . $this->getParam('name') . '<br>Type is: ' . $this->getParam('type');

Then go to url: '/tour/sampleName-sampleType', you will see the result:

Name is: sampleName

Type is: sampleType

A little sugar:

Actually your route is correctly set, however by default the routing pattern is: '/tour/index/name/sampleName/type/sampleType', your dash ('-') only worked as a separator for parameters, as in Zend does not recognize it as a connection string.

The following code is the complete code to add such a route to your Zend project for those who might need it.

In Bootstrap.php

protected function _initRoutes ()
{    
    $this->bootstrap('frontController');
    $front = $this->getResource('frontController');
    $router = $front->getRouter();

    $route = new Zend_Controller_Router_Route(':name/:type', array('controller' => 'tour', 'action' => 'index'));
    $router->addRoute('tour', $route);
}

Print it out in controller:

echo '<br>Name is: ' . $this->getParam('name') . '<br>Type is: ' . $this->getParam('type');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top