Magento Themes and Magento Extensions

How to display Image Preview in Admin Form magento

Share

Magento allows us to create custom form in admin panel by creating our own custom module. We can create almost any field in the admin form by creating a class that extends the base class Mage_Adminhtml_Block_Widget_Form. The _prepareForm method allows to define our form elements.
Sometimes we may need to upload a file in the adminform, the default file field doesn’t provide the image preview when we upload an image file. For this purpose we need to use image field type as shown in the below snippet

$fieldset->addField('filename', 'image', array(
'label' => Mage::helper('customform')->__('Image'),
'required' => false,
'name' => 'filename',
));

In the above code addField method adds a new field to the adminform. The first argument to addField method call specifies your form fieldname (In this case i written simply as filename). The Second argument is the input type (In this case it is image). Third argument specifies the properties such as name of the input field, label for the input field etc.

The code snippet below shows the sample form with a few fields like title, image, status, content. Once the image is uploaded and save and continue button is clicked the image preview and delete checkbox will appear in the screen.

protected function _prepareForm() {
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('customform_form', array('legend' => Mage::helper('customform')->__('Item information')));
$fieldset->addField('title', 'text', array(
'label' => Mage::helper('customform')->__('Title'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
));
$fieldset->addField('filename', 'image', array(
'label' => Mage::helper('customform')->__('Image'),
'required' => false,
'name' => 'filename',
));
$fieldset->addField('status', 'select', array(
'label' => Mage::helper('customform')->__('Status'),
'name' => 'status',
'values' => array(
array(
'value' => 1,
'label' => Mage::helper('customform')->__('Enabled'),
),
array(
'value' => 2,
'label' => Mage::helper('customform')->__('Disabled'),
),
),
));
$fieldset->addField('content', 'editor', array(
'name' => 'content',
'label' => Mage::helper('customform')->__('Content'),
'title' => Mage::helper('customform')->__('Content'),
'style' => 'width:700px; height:500px;',
'wysiwyg' => false,
'required' => true,
));
return parent::_prepareForm();
}

Leave a Reply

You must be logged in to post a comment.