dimanche 12 avril 2015

Zend Framework 2: Creating forms from configuration - how to fix ServiceNotCreatedException

I want to create a form in Zend Framework 2 from configuration, similar as described in the docs. So instead of doing this in the form class for every element:



// [...]

$this->add(array(
'name' => 'fname',
'type' => 'text',
));

// [...]v


I want to do it like this:



// [...]

$form = $factory->createForm(array(
'elements' => array(
array(
'spec' => array(
'name' => 'fname',
'type' => 'text',
),
),
),
));

// [...]


Since I am new to the framework, I am still a bit unsure as where things go & what is the correct way to do things, but I think I am on a good track – I just need to get things working to understand them more.


Currently my code results in an exception which leaves me a bit puzzled, although I understand it somehow:



An exception was raised while creating "MyForm"; no instance returned


Besides my confusion, I already have an idea where my code might go wrong.


The form class looks pretty simple because the actual elements won't be injected here:



namespace My\Form;

use Zend\Form\Form;

class MyForm extends Form
{
public function __construct()
{
parent::__construct();

$this->setAttribute('method', 'post');
$this->setAttribute('action', '/some-action');
}
}


The configuration for the form elements looks like this:



namespace My\Form;

use Zend\Form\Factory;

class MyFormFactory extends Factory
{
public function __construct()
{
$factory = new Factory();

$form = $factory->createForm(array(
'elements' => array(
array(
'spec' => array(
'name' => 'fname',
'type' => 'text',
),
),
),
));

return $form;
}
}


To wire the two together, I have this service manager configuration in the module's module.config.php:



'service_manager' => array(
'factories' => array(
'MyForm' => function ($servicemanager) {
$form = new \My\Form\MyForm();
$factory = $servicemanager->get('MyFormFactory');
$form->add($factory);
return $form;
},
'MyFormFactory' => function ($servicemanager) {
$factory = new \My\Form\MyFormFactory();
return $factory;
},
),
),


And last but not least, the controller:



namespace My\Controller;


use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class MyController extends AbstractActionController
{
public function indexAction()
{
$form = $this->getServiceLocator()->get('MyForm');

return new ViewModel(array(
'form' => $form,
));
}
}


As already said, the only thing that happens is the exception which is actually pretty clear: The MyForm class does not return an instance. To fix this, I already tried to return something, but that did not do anything.


What needs to be changed to get the form created? Is my approach any good or am I on the wrong track?


Aucun commentaire:

Enregistrer un commentaire