adding img tag in zend form

2019-04-23 20:50发布

问题:

I'm building a form with a class extending Zend_Form.How can I add an img tag inside the form?I also need to add a class to it and align attribute

This is the final result I want to achieve:

<span class="myElement"><img src="myPath" align="middle" class="myClass"/>
<input type="text"></span>

I didnt find much about Zend_Form_Element_Image's documentation

thanks

Luca

回答1:

Have in library/Application/Form/Element/Img.php

class Application_Form_Element_Img extends Zend_Form_Element_Xhtml
{
    public $helper = 'formImg';

    public function loadDefaultDecorators ()
    {
        parent::loadDefaultDecorators ();
        $this->removeDecorator ('Label');
        $this->removeDecorator ('HtmlTag');

        $this->addDecorator('HtmlTag', array (
        'tag'   => 'span',
        'class' => 'myElement',
        ));
    }
}

In application/view/helpers/FormImg.php

class Zend_View_Helper_FormImg extends Zend_View_Helper_FormElement
{
    public function formImg ($name, $value, $attribs = null)
    {
        $info = $this->_getInfo($name, $value, $attribs);

        $xHtml = '<img'
                . $this->_htmlAttribs ($attribs)
                . ' />';

        return $xHtml;
    }
}

In your form:

    $this->addElement ('img', 'myimage', array (
        'src'           => '/images/download.png',
        'align'         => 'right',
    ));

Note: paths are subject to change in your particular application.



回答2:

Actually, you don't need a custom element to do that. You can use HtmlTag decorator and use the openOnly option.

$form = new Zend_Form();

$form->addElement("text", "foo", array("decorators" => array(
    array(array("img" => "HtmlTag"), array(
        "tag" => "img",
        "openOnly" => true,
        "src" => "myPath",
        "align" => "middle",
        "class" => "myClass"
    )),
    array("ViewHelper"),
    array(array("span" => "HtmlTag"), array(
        "tag" => "span",
        "class" => "myElement"
    ))
)));

echo $form->foo;


回答3:

Hi you can create a custom element called "html"

class Zend_Form_Element_Html extends Zend_Form_Element_Xhtml
{
    public $helper = 'formHtml';
}

Now you can call it:

$yourForm->addElement(
            'html',
            'myElementId',
            array(
             'value'=>'<span class="myElement"><img src="myPath" align="middle"  class="myClass"/>
<input type="text"></span>'))

For more info you can check this link:
Zend Framework: Insert DIV and Image in my form