Magento 1.9 – Show Thumbnail Image and Delete Image in Custom Module Admin Form

admin-paneladminformmagento-1.9varien-file-uploader

I'm trying to display thumbnail image in my custom admin module edit form like this
enter image description here
Right now I'm using this addfield.

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

I looked at lib/Varien/Data/Form/Element/Image.php and found this code which uses images url there.

public function getElementHtml()
    {
        $html = '';

        if ((string)$this->getValue()) {
            $url = $this->_getUrl();

            if( !preg_match("/^http\:\/\/|https\:\/\//", $url) ) {
                $url = Mage::getBaseUrl('media') . $url;
            }

But I'm not storing images in media folder for this module. I'm uploading images from the controller in ram_images folder.

 $path = Mage::getBaseDir('media') . DS .'ram_images' ;
   $uploader->save($path, $_FILES['main_image']['name'] );

Also, i could not change URL from Image.php file as it will affect other system modules. is there any workaround here. Please suggest a solution.

And I also want to delete image using checkbox provided below upload button.

Thanks.

Best Answer

Add the code in your controller file

public function saveAction() 
{
    ...

    if (!empty( $_FILES['main_image']['name'] )) 
    {
        $data['main_image'] =  $_FILES['main_image']['name'] ;
    } 
    else 
    {
        if (isset($data['main_image']['delete']) && $data['main_image']['delete'] == 1) 
        {
            if ($data['main_image']['value'] != '')
                $this->removeFile($data['main_image']['value']);
            $data['main_image'] = '';
        }
        else 
        {
            unset($data['main_image']);
        }
    }

    ...
}
public function removeFile($file) 
{
        $_helper = Mage::helper('ram');
        $file = $_helper->updateDirSepereator($file);
        $directory = Mage::getBaseDir('media') . DS .'ram_images' ;
        $io = new Varien_Io_File();
        $result = $io->rmdir($directory, true);
}

Create below function in Helper Class

 public function updateDirSepereator($path) 
    {
        return str_replace('\\', DS, $path);
    }
Related Topic