简体   繁体   中英

zf2 - getting controller plugins in form/controller factory

Is it possible to access controller plugins from a form/controller factory (any factory implementing FactoryInterface)?

I have a form factory that i want to set the form action depending on the request parameter, but need to access the url from the route defined in config.

So whereas in a controller i would use the url controller plugin:

$form->setAttribute('action', $this->url()->fromRoute('appointment.add', array('clientId' => $clientId)));

...how can i access this in a factory? eg something like:

class MyFormFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface  $serviceLocator){
        $serviceManager = $serviceLocator->getServiceLocator();
        //...snip...
        $form = new AddAppointmentForm($client);
        $serviceManager->get('ControllerPluginManager');
        $url =  $controllerPluginManager->get('Url');
        die($url->fromRoute('appointment.add', ['clientId' => $clientId]));
        return $form;
    }

It would not be good practice to use controller plugins in a non controller context. To assemble an URL with the ZF2 router you could just use the router which is also available in the ServiceManager .

$router = $serviceManager->get('HttpRouter');
$url = $router->assemble(['clientId' => $clientId], ['name' => 'appointment.add']);

You can create instance of \\Zend\\Mvc\\Controller\\PluginManager in your factory and can easily get url or whatever plugin you want. Just a little problem, you can't set your controller in you plugin manager. So, controller dependent plugin will NOT work properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM