Latest: Genstatic, my first sip of coffee

Content with Style

Web Technique

Custom Zend Form Image Upload Element

by Pascal Opitz on June 29 2009, 23:59

It really is time to post something, isn't it? Here is a quick way to have an image preview inside of a form based on Zend Form.

Assumptions

I am using the auto include mechanism for this one, utilizing the PEAR naming convention, and all my files will sit underneath a Shared folder within the library folder.

A custom form Element

This is sitting under Shared/Form/Element/Image.php


<?php
class Shared_Form_Element_Image extends Zend_Form_Element 
{
  public $helper = "imageUpload";
  public $options;
  
  public function __construct($image_name, $attributes, $data_item) {
    $this->options = $data_item;
    parent::__construct($image_name, $attributes);
  }
}

As you can see, the form Element itself doesn't contain much code, but it does overwrite the property 'helper'. Which bings us to the next file:

A custom view helper

In our example, this sits under Shared/Views/Helpers/ImageUpload.php


<?php
class Shared_View_Helper_ImageUpload extends Zend_View_Helper_FormFile {

  public function imageUpload($name, $value, $attribs, $options) {
    $str = parent::formFile($name, $attribs = null);

    if(!empty($options[$name])) {
      $str .= $this->getImagePreview($name, $options[$name]);
    } else {
      $str .= $this->getEmptyPreview();
    }
    
    return $str;
  }

  private function getImagePreview($name, $path) {
    $img = ($this->view->doctype()->isXhtml())
       ? '&lt;img src="/'.$path.'" alt="'.$name.'" />'
       : '&lt;img src="/'.$path.'" alt="'.$name.'">';
    
    return '&lt;p class="preview">'.$img.'&lt;/p>';
  }
  
  private function getEmptyPreview() {
    return '&lt;p class="preview">No image uploaded.&lt;/p>';
  }
}

Pretty straight forward, I am just subclassing the FormFile helper that Zend brings us. However, you might want to create a different helper all together, if you need to use much more customized markup than I do.

Invocation

The form itself will no contain the image path as element, therefore we need to inject it into the form data inside the Controller, then invoke the Form with that data:


$data['image'] = $image_path;
$form = new My_From($data);

Inside our Form, all we need to do now is to add a new element using our custom ImageUpload element:


$preview = new Shared_Form_Element_Image('image', null, $options);
$preview->addValidator('Count', false, 1);
$preview->addValidator('Extension', false, 'jpg,png,gif');
$preview->setLabel('My Image');
$fields[] = $preview;

Comments

  • Thanks your post was very helpful to me.

    But as you extends Zend_Form_Element and not Zend_Form_Element_File, I can't receive the file ( $form->image->receive() ).

    If I extend Zend_Form_Element_File,the file is well uploaded, but the custom helper doesn;t work anymore :(

    by bablukid on March 17 2010, 22:58 - #


Comments for this article are closed.