Zend_Form Overriding the default decorators

I'm having trouble removing the standard set of decorators using Zend_Form.

I am trying to extend Zend_Form to implement a different decorator style.

class CRM_Form extends Zend_Form
{
 public function init()
 {  
  $this->setDisableLoadDefaultDecorators(true);

  $this->addDecorator('FormElements')
->addDecorator('Form');

  $this->setElementDecorators(array(
  'ViewHelper',
  'Label',
 'Errors',
   new Zend_Form_Decorator_HtmlTag(array('tag' => 'p'))
  ));
 }
}

When I try to use this class as follows:

$form = new CRM_Form();
$form->setAction('/')->setMethod('post'); 
$id = $form->createElement('text','id')->setLabel('ID:');
$form->addElement($id);

Old decorators are used (definition list), not my paragraph style.

If I add an Element () element to the init () method of the CRM_Form class, it uses the style I set.

How to force all elements created with this class to use my default style?

+3
source share
3 answers

Zend Form , . , "addAndDecorte":

public function addAndDecorate($element) 
{
   $this->addElement($element);

   // do your decorating stuff..
}
0

setElementDecorators init, , . Zend_Form:: createElement, :

  • , .
  • , .

..

// not tested
public function createElement($type, $name, $options = null)
{
  if ( !is_array($options) ) {
    $options = array();
  }
  if ( !isset($options['decorators']) ) {
    $options['decorators'] = array(
      'ViewHelper','Label','Errors',
      new Zend_Form_Decorator_HtmlTag(array('tag' => 'p'))
    );
    // I'd make this array a protected class member
  }

  return parent::createElement($type, $name, $options);
}
+1

, $form->addElement('type', 'name', array('options'=>'example'));, Zend_Form , setElementDecorators.

, $form->addElement(), .

You can easily override this function to set decorators on elements that are already created by doing something like this in your form:

public function addElement($element, $name = null, $options = null)
{
  if ($element instanceOf Zend_Form_Element) {
    $element->setDecorators($this->_elementDecortors);
  }
  return parent::addElement($element, $name, $options);
}
+1
source

Source: https://habr.com/ru/post/1724936/


All Articles