How can I in ZF2 create custom form element with custom validator? I want to create custom category picker that uses jQuery and content of this element should be rendered from phtml script. In ZF1 it was quite easy but in ZF2 I don’t know from where to start.
Share
A form element must implement a
Zend\Form\ElementInterface. A default class is theZend\Form\Elementwhich you can use as a base form:CUSTOM VALIDATOR
You can let the element directly assign a custom validator. Then you must implement the
Zend\InputFilter\InputProviderInterface:CUSTOM RENDERING
At this moment it is a bit complex how Zend Framework handles the rendering of custom form element types. Usually, it just returns plain
<input type="text">elements.There is one option, then you have to override the
Zend\Form\View\Helper\FormElementhelper. It is registered asformelementand you must override this view helper in your custom module:Furthermore, every form element in Zend Framework 2 is rendered by a view helper. So you create a view helper for your own element, which will render the element’s content.
Then you have to create your own form element helper (
MyModule\Form\View\Helper\FormElement):As a last step, create your view helper to render this specific form element:
If you want to render a .phtml file for example for this form element, load it inside this helper:
It will render a
my-module/form-element/foo.phtmland in this script you will have a variable$elementwhich contains your specific form element.