Search code examples
imageformszend-frameworkhref

Zend forms: How to surround an image-element with a hyperlink?


How do I surround an image element inside a Zend form with an HTML <a href>-Tag? I specifically don't want a JS onClick()-Event as it seems not to work properly in my case (see question Zend: Redirect from form without validation).

This is how I add the image element inside the form, right now the hyperlink is displayed as Text "Link" right next to the image:

    $this->addElement('image', 'btnBack', array (
        'name' => 'btnBack',
        'id'   => 'btnBack',
        'label' => '',
        'title' => 'Go back',
        'alt' => 'Go back',
        'src' => '/img/undo.png'
    ));
    $this->getElement('btnBack')
            ->setDescription('<a href="/admin/groupoverview">Link</a>')
            ->setDecorators(array(
                'ViewHelper',
                array('Description', array('escape' => false, 'tag' => false)),
                array('HtmlTag', array('tag' => 'dd')),
                array('Label', array('tag' => 'dt')),
                'Errors',
              ));

Solution

  • This sounds like a bad idea. From the look of your other question, all you want is an image 'button' that goes to a specific URL. You shouldn't try and do this with an image input, since this is a type of submit button, and so clicking it will submit the form. If you're trying to override this with javascript or wrap the whole thing with a HTML link you're trying to solve the wrong problem.

    The easiest approach is probably to use a button input. You can then style it with CSS to make it look like an image, and add your javascript onclick action to make it do what you want. Since input type="button" elements don't do anything onclick by default, you shouldn't have any of the problems you had before.

    $this->addElement('button', 'btnBack', array(
        'id'   => 'btnBack',
        'label' => 'Go back',
        'onclick' => "window.location='/admin/groupoverview'"
    ));
    

    then in your stylesheet (replace the width and height with the correct image dimensions):

    #btnBack {
        background-image: url(/img/undo.png);
        width: 123px;
        height: 123px;
        border: 0;
        text-indent: -1000px;
        cursor: pointer;
    }
    

    the text-indent shifts the text label out of view. If you absolutely don't want these rules in your stylesheet you could put them inline on the form element by passing a style attribute instead.