Using custom form elements with the AnnotationBuilder in Zend Framework 2

Just a quick little tip – Since ZF 2.2 we now have the FormElementManager service available which make is nice as easy to register new custom form elements and fieldsets in your ZF2 application (see Creating Custom Elements). However I quickly discovered that it wasn’t possible to use custom elements easily in my forms if the form was created using the annotation builder.

According to the ZF2 manual the annotation builder is used like so:

The problem here is that the AnnotationBuilder instance has no knowledge of the FormElementManager to find the custom elements. It has no FormFactory set so it creates it’s own internal instance which isn’t aware of the FormElementManager.

The solution I have found to this is to set the FormFactory of the AnnotationBuilder like so:

Now if the User class is annotated with custom form elements it will all work nicely.

That’s my solution, let me know if you have a better one.

Leave a Reply

Your email address will not be published. Required fields are marked *