Mohammad Faisal
Mohammad Faisal

Reputation: 5959

delete uploaded image in custom module

UPDATE
I'm updating the question as I solved one of the problem in this question. The original question is below the line.

I'm now able to see the preview of the image as the problem was with the below code

$fieldset->addField('banner', 'image', array(
    'label' => Mage::helper('designer')->__('Banner'),
    'required' => false,
    'name' => 'banner',
));

where instead of image, file was written for the type of field. But now the problem is, I'm unable to delete the previous image. I do check the delete image checkbox but the file still remains there. Why its not deleting?


I'd created a module with module creator and able to save images. But when the next time I do want to edit the record it does not show the preview of the uploaded image or the delete checkbox.

screen shot Do I need to write additional code in my adminhtml tab form?

Upvotes: 0

Views: 3490

Answers (2)

ARVIND KARKAR
ARVIND KARKAR

Reputation: 282

Below code write in your save action of your controller

  if (isset($data['image']['delete'])) {
       Mage::helper('your_helper')->deleteImageFile($data['image']['value']);
  }
  $image = Mage::helper('your_helper')->uploadBannerImage();
  if ($image || (isset($data['image']['delete']) && $data['image']['delete'])) {
       $data['image'] = $image;
  } else {
       unset($data['image']);
  }

Write below code in your helper

    public function deleteImageFile($image) {
    if (!$image) {
        return;
    }
    try {
        $img_path = Mage::getBaseDir('media'). "/" . $image;
        if (!file_exists($img_path)) {
            return;
        }
        unlink($img_path);
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

Replace your_helper to your actual helper class

Upvotes: 0

MagePal Extensions
MagePal Extensions

Reputation: 17656

In your saveAction of you controller you need to check if the delete image checkbox is checked.

Eg.

if (isset($_FILES['checkcsv']['name']) && $_FILES['checkcsv']['name'] != '') {
    try {
        ...
        $uploader->save($path, $logoName);

        save path to database

    } catch (Exception $e) {

    }
}
else if((isset($data['banner']['delete']) && $data['banner']['delete'] == 1)){

    //can also delete file from fs
    unlink(Mage::getBaseDir('media') . DS . $data['banner']['value']);

    //set path to null and save to database
    $data['banner'] = '';


}

Upvotes: 1

Related Questions