phpparametersdefaultzend-routezend-framework3

Not getting default route parameter in ZF3


In ZF3 I want to get default parameter from route. I'm getting parameters in this way in controller:

$params = $this->params()->fromRoute('crud');

My urls looks like this:

1: somedomain/admin/color/add
2: somedomain/admin/color

In 1) I'm getting add in my $params variable.
In 2) I'm getting null but I'm expecting default (in this case view)

I think this is problem with bad router configuration.

'admin' => [
            'type' => Segment::class,
            'options' => [
                'route' => '/admin/:action',
                'defaults' => [
                    'controller' => Controller\AdminController::class,
                    'action' => 'index',
                ],
            ],
            'may_terminate' => true,
            'child_routes' => [
                'color' => [
                    'type' => Segment::class,
                    'options' => [
                        'route' => '/:crud',
                        'constraints' => [
                            'crud' => 'add|edit|delete|view',
                        ],
                        'defaults' => [
                            'controller' => Controller\AdminController::class,
                            'crud' => 'view',
                        ],
                    ],
                ],
            ],
            ],

Solution

  • In your route definition, you didn't says the router that your crud parameter is optionnal. So when you call somedomain/admin/color, it is the route /admin/:action which is selected.

    To specify a optional parameter, use the bracket notation (assuming you use the same action):

    'admin' => [
        'type' => Segment::class,
        'options' => [
            'route' => '/admin/:action[/:crud]',
            'defaults' => [
                'controller' => Controller\AdminController::class,
                'action' => 'index',
                'crud' => 'view',
            ],
            'constraints' => [
                'crud' => 'add|edit|delete|view',
            ],
        ],
    ],