ZF2 - Generating Url from route

2020-07-06 07:28发布

问题:

I can't figure out to generate Url from everywhere i want to, in zend 2

I get action and controller so i try this:

$this->url('myControllerName', array('action' => 'myActionName'));

But this return an object, i just want the full URL string of this route

Somebody can help me to find the proper way?

EDIT : according to Stoyan, maybe i made a mistake on my route. here is the part of my module.config

'router' => array (
                'routes' => array (
                        'indexqvm' => array (
                                'type' => 'segment',
                                'options' => array (
                                        'route' => '/Indexqvm[/:action][/:id_event]',
                                    'constraints' => array (
                                            'action' => '[a-zA-Z][a-zA-Z0-9_-]+',
                                            'id_event' => '[0-9]+'
                                    ),
                                    'defaults' => array (
                                            'controller' => 'Qvm\Controller\Indexqvm',
                                            'action' => 'index' 
                                    ) 
                            ) 
                    ),

And my call :

echo $this->url('indexqvm', array('action' => 'list-index'));

the error : Catchable fatal error: Object of class Zend\Mvc\Controller\Plugin\Url could not be converted to string

回答1:

Use the echo before calling $this->url(...) (see bellow) and this will display the whole URL.

<?php echo $this->url('route-name', $urlParams, $urlOptions); ?>

Note that the first paramter of url() is the name of the route as specified in your [module]/config/module.config.php file.

See this for more information about ZF2's URL view helper.

EDIT in response to the question edit:

The above section is related to using the URL view helper.

If you want a URL in the controller then you need the URL controller plugin.

<?php $url = $this->url()->fromRoute('route-name', $params, $options); ?>

This is the reference to the ZF2 manual for this controller plugin.

Hope this helps :)

Stoyan



回答2:

You can use this in the .phtml file

echo $this->url('HelloWorld/default', array('controller'=>'Index', 'action'=>'registration'));

Where HelloWorld/default is the routing and the remaining is the controller and its action and also you can send the others parameter adding just in array as key and value pair.