Custom Element Factory

zend-form

#1

I can`t access to CustomElementFactory
What am I doing wrong?

### Entity
namespace Application;
...
use Zend\Form\Annotation;
...
class SomeEntity
{
...
/**
 * @Annotation\Type("Application\Form\Element\CustomElement")
 */
public $custom;
...
}

### module.config.php
...
'form_elements' => [
    'factories' => [
        \Application\Form\Element\CustomElement::class => function () {
            throw new \Exception('It works? No!');
        },
    ],
],
...

### IndexController 
function indexAction()
{
...
    $class = $this->params()->fromQuery('entity');
    $b = new AnnotationBuilder($this->getObjectManager());
    $form = $b->createForm($class);
...
}

### CustomElement
namespace Application\Form\Element;

use Zend\Form\Element;

class CustomElement extends Element
{
}

#2

I do not use annotations, but I think there is no @Form\Type!

Please look at the documentation for the correct annotations: https://docs.zendframework.com/zend-form/quick-start/#using-annotations
There you can find an example for the type annotation:

/**
 * @Annotation\Type("Zend\Form\Element\Email")
 * @Annotation\Options({"label":"Your email address:"})
 */
public $email;

#3

This does not change the question

use Zend\Form\Annotation as Form; (Fixed)

Thank you for your comment


#4

The annotation is wrong, not the namespace!


#5

I showed only part of the code.
There is no Fatal error.


#6

Replace:

@Form\Type("Application\Form\Element\CustomElement")

with:

@Annotation\Type("Application\Form\Element\CustomElement")


#7

Nothing changed. Problem still exists
CustomElement is also defined


#8

The problem is that the Form Factory does not determine the Element Factory

var_dump($form->getFormFactory())

### ouput
...
["\Application\Form\Element\CustomElement"] => object(Zend\Form\ElementFactory)#471 (1) {
        ["creationOptions":"Zend\Form\ElementFactory":private] => NULL
      }
...

But I expected call Exception(‘It works? No!’)

Because I want to use the following code for my purposes

'form_elements' => [
    'factories' => [
        \Application\Form\Element\CustomElement::class => \Application\Form\Element\CustomElementFactory::class,
    ],
],

#9

Fetch the annotation-builder from the service-manager:

$builder = $container->get(Zend\Form\Annotation\AnnotationBuilder::class);

…and all is included.


#10

Yes, it works. Thanks a lot!

But, I’m using Doctrine Entity, so I need to use

$builder = $container->get(DoctrineORMModule\Form\Annotation\AnnotationBuilder::class);

This does not work


#11

Sorry, this is not a ZF component. Please look at module for the correct name to retrieve the builder:


#12

http://devblog.x2k.co.uk/using-custom-form-elements-with-the-annotationbuilder-in-zend-framework-2/


#13

@kkg
This article describes the usage without Doctrine, but within a ZF application it is much simple the pull the annotation-builder from the service-manager.