Adding custom attributes in Zend Framework 2 using the Zend Form

304 views Asked by At

What I want to achieve is to add custom attributes to the form, which are:

'validType' => 'remote[\'/catalogos/acl/compruebarecurso\',\'nombre\']', 
'invalidmessage' => 'Al parecer el nombre ya existe'.

The problem lies in the view, since it does not generate the correct HTML

class RecursosForm extends Form 
    { 
        // TODO - Insert your code here 

        /** 
         */ 
        public function __construct($name = null){ 
            parent::__construct($name); 

            $this->add(array( 
                    'name' => 'nombre', 
                    'type' => 'Zend\Form\Element\Text', 
                    'attributes' => array( 
                            'class' => 'easyui-validatebox', 
                            'validType' => 'remote[\'/catalogos/acl/compruebarecurso\',\'nombre\']', 
                            'invalidmessage' => 'Al parecer el nombre ya existe' 
                    ), 
                    'options' => array( 
                            'label' => 'Recurso:', 
                            'label_attributes' => array('class'  => 'fitem'), 

                    ) 
            )); 
        } 
    }  
1

There are 1 answers

0
AlexP On

The view helper isn't producing incorrect HTML but is actually preventing it. The attributes you have added would result in invalid HTML so ZF2 removes them.

You can override this by extending the abstract form view helper and defining your own $validAttributes, although it still would result in incorrect HTML.

You should consider using the HTML 5 custom data attribute (attributes with the prefix data-*) as these are valid and will not be filtered out by the standard form view helpers.

'attributes' => [ 
    'class'                => 'easyui-validatebox', 
    'data-valid-type'      => 'remote[\'/catalogos/acl/compruebarecurso\',\'nombre\']', 
    'data-invalid-message' => 'Al parecer el nombre ya existe' 
],