Ildar
Ildar

Reputation: 796

How to pass arrays in ZF2 routes?

for example, I want to get this url string

/1/2/3/4

In view:

$this->url('routeName', array(
    'a' => array(1, 2, 3, 4)
));

In controller:

print_r($this->params()->fromRoute('a'));

Output is:

array(
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 4
);

Is it possible to create this route?

Upvotes: 1

Views: 497

Answers (2)

Code Lღver
Code Lღver

Reputation: 15593

Add the url routing in module.config.php file like this:

'routename' => array(
    'type'    => 'Zend\Mvc\Router\Http\Segment',
    'options' => array(
        'route'    => 'routename[/:val1][/:val2][/:val3][/:val4]',
        'defaults' => array(
            'controller' => 'controllername',
            'action'     => 'actionname'
        ),
        'constraints' => array(
            'val1' => '[0-9]+',
            'val2' => '[0-9]+',
            'val3' => '[0-9]+',
            'val4' => '[0-9]+'
        )
    )
)

And then add the number by following this:

$this->url('routename', array(
    'val1' => 1,
    'val2' => 2,
    'val3' => 3,
    'val4' => 4
));

And you can get all the parameter by :

print_r($this->params());

Upvotes: 1

Sam
Sam

Reputation: 16445

IF it would work at all, it'd be using the class Zend\Mvc\Router\Http\WildCard. Since I never got that one to be working the way i expected it to be though, i suggest you go the ZF2 way where you have full control over what you're doing ;) Parameters and configuration stuff should be named always! I suggest you create a simple route of type Zend\Mvc\Router\Http\Segment:

'routename' => array(
    'type'    => 'Zend\Mvc\Router\Http\Segment',
    'options' => array(
        'route'    => '/:val1/:val2/:val3/:val4',
        'defaults' => array(
            'controller' => 'controllername',
            'action'     => 'actionname'
        ),
        'constraints' => array(
            'val1' => '[0-9]+',
            'val2' => '[0-9]+',
            'val3' => '[0-9]+',
            'val4' => '[0-9]+'
        )
    )
)

If the requirements are different, obviously the route configuration would change. You'd need to set up the route like this:

$this->url('routename', array(
    'val1' => 1,
    'val2' => 2,
    'val3' => 3,
    'val4' => 4
));

Upvotes: 2

Related Questions