Links as buttons in Zend Framework form

In my current project I have to use link tags instead input elements for my form buttons. To do this I needed to create new form element, new helper and add helper path to my bootstrap file.

First I created element class file Irm_Form_Element_HrefButton, this class extends Zend_Form_Element_Submit, because I would all I need is just change helper class name to hrefButton. So my element class file:

<?php
class Irm_Form_Element_HrefButton extends Zend_Form_Element_Submit
{
	public $helper = 'hrefButton';
}

To create helper I copied submit button helper class and changed some code:


<?php

class Irm_View_Helper_HrefButton extends Zend_View_Helper_FormElement
{
    public function hrefButton($name, $value = null, $attribs = null)
    {
        $info = $this->_getInfo($name, $value, $attribs);
        extract($info); // name, value, attribs, options, listsep, disable

        // XHTML or HTML end tag?
        $endTag = ' />';
        if (($this->view instanceof Zend_View_Abstract) && !$this->view->doctype()->isXhtml()) {
            $endTag= '>';
        }

        // Render the button.
        $xhtml = '<input type="hidden"'
               . ' name="' . $this->view->escape($name) . '"'
               . ' value="' . $this->view->escape($value) . '"'
               . $endTag;

		$xhtml = $xhtml . '<a href="#"'
			. ' id="' . $this->view->escape($id) . '"'
			. $this->_htmlAttribs($attribs)
			.' ><span>'.$this->view->escape($value).'</span></a>';

        return $xhtml;
    }
}

Somewhere in bootstrap file in view initialization function add helper path like this:

// ... bootstrap class
protected function _initView ()
{
	// .... init view
	$view->addHelperPath(APPLICATION_PATH . '/../library/Irm/View/Helper','Irm_View_Helper');
	return $view;
}

Now you can use your new form element in your form class file, to make link submit your form you can set onclick event with setAttrib() method like this:

//... form class file
$element = new Irm_Form_Element_HrefButton('submit');
$element->setLabel('Submit')
	->setAttrib('onclick', "document.getElementById('my-form').submit();return false;");
$this->addElement($element);
//... form class file
0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

One Response to Links as buttons in Zend Framework form

  1. ali says:

    the black background in the code snippet is an extremely bad idea!!
    it is agonizing to read!

Leave a Reply

Your email address will not be published. Required fields are marked *