Optional ZF2 route restrictions in child routes

I had a problem with an optional restriction in the route, which is not optional in it for children. My routing structure is as follows:

'profile' => [ 'type' => 'segment', 'options' => [ 'route' => '/profile[/:id]', 'constraints' => ['id' => '[0-9]*'], 'defaults' => [ 'controller' => 'User\Controller\User', 'action' => 'profile' ] ], 'may_terminate' => true, 'child_routes' => [ 'sessions' => [ 'type' => 'literal', 'options' => [ 'route' => '/sessions', 'defaults' => ['action' => 'sessions'] ] ] ] ] 

Which, in my opinion, should give me the following routes:

  • /profile - works
  • /profile/123 - works
  • /profile/sessions - does not work
  • /profile/123/sessions - works

When I use route 3 in the URL view helper, I get the following error:

 $this->url('profile/sessions'); 

Zend\Mvc\Router\Exception\InvalidArgumentException : Missing id parameter

I initially had [0-9]+ as my restriction, but making it optional ( * ) did not seem to help. Has anyone experienced this thing before?

+6
source share
2 answers

I had the same problem once, the only solution I found was to create a separate route (in your case for / profile / sessions) as an optional parameter for the base route, it seems to become mandatory when accessing the children's route.

+3
source

Add it to the parent route.

 'profile' => [ 'type' => 'segment', 'options' => [ // ↓ 'route' => '/profile[/:id][/:action]', 'constraints' => [ 'id' => '[0-9]*', 'action' => '[a-zA-Z][a-zA-Z0-9_-]*' ], 'defaults' => [ 'controller' => 'User\Controller\User', 'action' => 'profile', ], ], ] 

This will make id and / or action optional. At least theoretically, this should make all the routes you listed possible, some problems with this.

+8
source

Source: https://habr.com/ru/post/926866/


All Articles