Zend Framework Element Form Image Edit Upload

I wanted to show an image uploader (using Zend_Form_Element_File) but when the user was editing the image (replacing it) it showed the current image in the form.

For some reason ZF devs won’t let you change the view helper for a Zend_Form_Element_File, so subclassing it and changing the view helper don’t work. There is a half baked example of this here (extend zend form file element), note that he is extending Zend_Form_Element, not Zend_Form_Element_File because (I assume) of the bug reported here (Zend_Form_Element_File doesn’t make use of $helper member) BOO!

So anyway, in the end I just did this:

<?php

class Boo_Form_Element_ImageUpload extends Zend_Form_Element_File {
public $options;

public function __construct($image_name, $attributes, $image_path) {
$this->options = $image_path;

parent::__construct($image_name, $attributes);

//
// By default the description is rendered last, but we want to use
// it to show the <img> when the user is editing it, so we rearrange
// the order in which the things are rendered
//
$this->clearDecorators();
$this
->addDecorator(‘Description’, array(‘tag’ => ‘div’, ‘class’ => ‘description image-preview’, ‘escape’ => false))
->addDecorator(‘File’)
->addDecorator(‘Errors’)
->addDecorator(‘HtmlTag’, array(‘tag’ => ‘dd’))
->addDecorator(‘Label’, array(‘tag’ => ‘dt’));

if ($image_path)
$this->setDescription(‘Current image:<br><img src=”‘.$image_path.'”>’);
}
}
and you can add it to a form just like a normal form element:
$file = new Boo_Form_Element_ImageUpload(‘file’, array(), ‘http://my-site.local/images/placeholder.jpg’);
$file->setOptions(array(
‘required’ => true,
‘label’ => ‘Upload a picture’
))
->setDestination(realpath(APPLICATION_PATH . self::DIR_TMP))
->addValidators(array(
array(‘Count’, true, 1),
array(‘Extension’, true, array(‘jpg,jpeg,gif,png’)),
array(‘Size’, true, self::MAX_FILE_SIZE)
));

$this->addElement($file);
Hope that helps someone else ๐Ÿ™‚