John Crest
John Crest

Reputation: 261

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;
    }

Upvotes: 0

Views: 610

Answers (2)

Bram Gerritsen
Bram Gerritsen

Reputation: 7238

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']);

Upvotes: 1

Shahadat Hossain Khan
Shahadat Hossain Khan

Reputation: 737

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.

Upvotes: 0

Related Questions