phpzend-frameworkzend-framework2routerzend-router

Inject default value in ZF2 Router


I currently have a Segment route looking like this: /shop/:shopId/ where shopId has no default value.

Whenever the route is matched a code in Module.php is triggered, that would do some preparation according to the shopId and save it in the session for example.

My question is, if it is possible, at that point, to set the default value for the route to that shopId? The final goal is to be able to assemble URLs without specifying the shopId each time from this moment on.

I remember in ZF1 this behavior was by default, where matched params from the Request were reused when assembling the URL and you had to explicitly specify you wanted them removed. Now I need the same functionality, but configured on a Module.php level, rather than having to rewrite every single assemble() call.


Solution

  • Option one: from your indexAction

    $id = $routeMatch->getParam('id', false);
    if (!$id)
       $id = 1; // id was not supplied set default one note this can be added as constant or from db .... 
    

    Option two: set route in module.config.php

    'product-view' => array(
                    'type'    => 'Literal',
                    'options' => array(
                        'route'    => '/product/view',
                        'defaults' => array(
                            'controller'    => 'product-view-controller',
                            'action'        => 'index',
                        ),
                    ),
                    'may_terminate' => true,
                    'child_routes' => array(
                        'default' => array(
                            'type'    => 'Segment',
                            'options' => array(
                                'route'    => '[/:cat][/]',
                                'constraints' => array(
                                    'cat'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                                ),
                                'defaults' => array(
                                ),
                            ),
                        ),
                    ),
                ),
    

    in you controller:

    public function indexAction()
        {
            // get category param
            $categoryParam = $this->params()->fromRoute('cat');
            // if !cat then get random category 
            $categoryParam = ($categoryParam) ? $categoryParam : $this->categories[array_rand($this->categories)];
            $shortList = $this->listingsTable->getListingsByCategory($categoryParam);
            return new ViewModel(array(
                'shortList' => $shortList,
                'categoryParam' => $categoryParam
            ));
        }