How to display Image Preview in Admin Form magento

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.

Note:- This article is based on Magento 1.x version. For displaying image preview in magento 2 version please refer the below link.

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

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.

After finishing this step we need to update the controller part for a minor bug fix. If you Save the Form for the second time without image. An empty array value will get inserted in the database, Which makes the previous image preview disappear.

The save function of the Adminhtml Controller of the custom module must be updated as shown in the below code.

Compatability: Magento 1.4,1.5

  1. shivam says:

    hey hi,
    If the images are stored in the folder in “codebase/media/images/xyz.png” then what should be done?

    • Ramesh says:

      Hi shivam sorry for the delayed response. You can check the magento code base of image field. By default the image gets stored in Media directory. you can try adding your additional path along with the filename to save in db.

Leave a Comment

Your email address will not be published. Required fields are marked *