I would like to create custom form elements in ZF2, which requires FormElementManager. I am currently using Doctrine Hydrator in the form creation as shown in this tutorial. In this method, an ObjectManager object is created in the controller and passed to the new form when it is instantiated:
public function editAction()
{
// Get your ObjectManager from the ServiceManager
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
// Create the form and inject the ObjectManager
$form = new UpdateBlogPostForm($objectManager);
// …
the update form:
namespace Application\Form;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
class UpdateBlogPostForm extends Form
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('update-blog-post-form');
// The form will hydrate an object of type "BlogPost"
$this->setHydrator(new DoctrineHydrator($objectManager));
// Add the user fieldset, and set it as the base fieldset
$blogPostFieldset = new BlogPostFieldset($objectManager);
$blogPostFieldset->setUseAsBaseFieldset(true);
$this->add($blogPostFieldset);
// … add CSRF and submit elements …
// Optionally set your validation group here
}
}
the BlogPost fieldset:
namespace Application\Form;
use Application\Entity\BlogPost;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class BlogPostFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('blog-post');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new BlogPost());
// … add fieldset elements …
}
// … public function getInputFilterSpecification() …
}
Unfortunately, in order to use ZF2's FormElementManager, the ZF2 manual says, "The second catch is that you must not directly instantiate your form class, but rather get an instance of it through the Zend\Form\FormElementManager;" so I have to get the form like this:
public function editAction()
{
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get('\Application\Form\UpdateBlogPostForm');
Is there a way to pass the ObjectManager object $objectManager
to the form through FormElementManager
, or is there a way to create the object within the form so the hydrator and the fieldset can use it?