Latest: Happy New Year 2010

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

Don't miss the opportunity to leave the first comment.

Leave your comment

Comments are moderated.
Tags allowed: a, strong, em, code, ul, ol, li, q, blockquote, br, p

Advertisement
Advertisement