How to render some html in Zend form?

1.8k views Asked by At

In my form i need this:

<li class  ="af_title"><div>Contact form</div></li>

I understand that if I need for example a text field - then I'd just create Zend_Form_Element_Text and wrap HtmlTag decorator around it - right?

questions:

1) how would I generate div form element so I can wrap decorator around it?

2) mmm. - how would I set content of said element to be "Contact form"?

Thanks:)

1

There are 1 answers

0
Marcin On BEST ANSWER

To wrap your Contact form around div which is inside <li class ="af_title"> you can do as follows:

$yourForm = new YourForm();
$yourForm->addDecorator(array('div' => 'HtmlTag'), array('tag' => 'div'));
$yourForm->addDecorator(array('li' => 'HtmlTag'), array('tag' => 'li', 'class' => 'af_title'));

EDIT:

I see that you speak of div form element. Such element does not exist, but you could easily create it. For this you need two things: new form element (i.e. div element) and a form view helper that would take care of generation of the html. I allowed myself to prepare simple examples of these two elements to show what I mean:

Div.php in APPLICATION_PATH . /forms/Element:

class My_Form_Element_Div extends Zend_Form_Element {
     /**
     * Default form view helper to use for rendering
     * @var string
     */
    public $helper = 'formDiv';

    public function __construct($spec, $options = null) {
        parent::__construct($spec, $options);
        $this->removeDecorator('label');
        $this->removeDecorator('htmlTag');

    }

}

FormDiv.php in APPLICATION_PATH . /views/helpers:

class My_View_Helper_FormDiv extends Zend_View_Helper_FormElement {


    public function formDiv($name, $value = null, $attribs = null) {  

        $class = '';

        if (isset($attribs['class'])) {
             $class = 'class = "'. $attribs['class'] .'"';
        }

        return "<li $class><div>$value</div></li>";
    }

}

Having this, you can just add the div form element to any form element in their init() method as follows:

    $div = new My_Form_Element_Div('mydiv');
    $div->setValue('Contact form')->setAttrib('class', 'af_title');
    $this->addElement($div);