Search code examples
phprouteszend-frameworkzend-route

Routes and URL Params - ZendFramework


I'm having an issue with zendframework routes and params.

I have language selector in my view page:

 <div class="language-chooser">
    <?
    $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
    unset($params['module']);
    unset($params['controller']);
    unset($params['action']);
    ?>
    <a href="<?= $this->url(array_merge($params, array('lang' => 'pt'))); ?>"><img src="<?= $this->baseUrl('/images/flags/br.png'); ?>" alt="" /></a>
    <a href="<?= $this->url(array_merge($params, array('lang' => 'en'))); ?>"><img src="<?= $this->baseUrl('/images/flags/us.png'); ?>" alt="" /> </a>
</div>

It works fine without routes. Accessing localhost/app/contact, I get the link correctly Ex.: localhost/app/contact/index/lang/en

But if I add a route

protected function _initRotas() {
    $router = Zend_Controller_Front::getInstance()->getRouter();
    $route = new Zend_Controller_Router_Route(
                    '/contact',
                    array(
                        'module' => 'default',
                        'controller' => 'contact',
                        'action' => 'index'
                    )
    );
    $router->addRoute('contact', $route);
}

I get the link without the lang param. Ex.: localhost/app/contact/

How could i solve this issue?

Thanks


Solution

  • The first example is based on the default route, which looks like :module/:controller/:action/* Notice the * at the end of the route; it defines that the url can contain additional key/value pairs.

    To make your contact route work, you could either use

    $route = new Zend_Controller_Router_Route(
        '/contact/:lang',
        array(
            'module' => 'default',
            'controller' => 'contact',
            'action' => 'index'
        )
    );
    

    this will make the url look like /contact/pt. Or you can use:

    $route = new Zend_Controller_Router_Route(
        '/contact/*',
        array(
            'module' => 'default',
            'controller' => 'contact',
            'action' => 'index'
        )
    );
    

    Which will result in /contact/index/lang/pt