1

I'm new to Magento, i have a image field, when i upload image and edit it, like next time i want to remove the uploaded image, i checked the checkbox and hit the save button, but image do not delete, I WANT TO DELETE IMAGE WHEN CHECKBOX CHECKED.

Here is my image field:

        $fieldset->addField(
            'filename',
            'image',
            [
                'label' => __('File'),
                'title' => __('File'),
                'name' => 'filename',
                'required' => true,
                'disabled' => $isElementDisabled,
            ]
        );

\app\code\EC\Customimport\Controller\Adminhtml\Index\Save.php

<?php
namespace EC\Customimport\Controller\Adminhtml\Index;

use Magento\Backend\App\Action;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;

class Save extends \Magento\Backend\App\Action
{

    /**
     * @param Action\Context $context
     */
    protected $_fileUploaderFactory;

    public function __construct(
        Action\Context $context,
        // \Magento\Framework\File\UploaderFactory $uploaderFactory,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
        StoreManagerInterface $storeManager,
        \Magento\Framework\Filesystem $filesystem
        )
    {
        $this->_fileUploaderFactory = $fileUploaderFactory;
        $this->_storeManager = $storeManager;
        $this->_filesystem = $filesystem;
        parent::__construct($context);
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        $pathurl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'customimport/';
        $mediaDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
        $mediapath = $this->_mediaBaseDirectory = rtrim($mediaDir, '/');

        if(!empty($_FILES['filename']['name'])){
            $uploader = $this->_fileUploaderFactory->create(['fileId' => 'filename']);
            $uploader->setAllowedExtensions(['jpg','jpeg','gif','png','csv','xlsx']);
            $uploader->setAllowRenameFiles(true);
            $path = $mediapath . '/customimport/';
            $result = $uploader->save($path);
        }
        $currenttime = date('Y-m-d H:i:s');

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {
            $model = $this->_objectManager->create('EC\Customimport\Model\Customimport');

            $id = $this->getRequest()->getParam('customimport_id');
            if ($id) {
                $model->load($id);
            }

            // =============UPDATED CODE=============
            if(!empty($_FILES['filename']['name'])){
              $model->setData('filename', $_FILES['filename']['name']);
            }
            elseif(isset($data['filename']['delete'])){
                $model->setData('filename', null);
            }

            $model->setData('title', $data['title']);
            $model->setData('status', $data['status']);
            $model->setData('created_time', $currenttime);
            $model->setData('update_time', $currenttime);

            try {
                $model->save();
                $this->messageManager->addSuccess(__('Item detail has been saved.'));
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['customimport_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\RuntimeException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the entry.'));
            }

            $this->_getSession()->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['customimport_id' => $this->getRequest()->getParam('customimport_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
}

enter image description here

3
  • please attach your save.php file Commented May 8, 2019 at 12:32
  • Question Updated @RkRathod Commented May 8, 2019 at 12:37
  • check answer.... Commented May 8, 2019 at 12:42

1 Answer 1

1

Add This Condition in save.php file :-

Add This Code After if ($data) {

            if(!empty($_FILES['filename']['name'])){
              $model->setData('filename', $_FILES['filename']['name']);
            }
            elseif(isset($data['filename']['delete'])){
                $model->setData('filename', null);
            }
19
  • It's not working bro :( @Rk Rathod Commented May 8, 2019 at 12:42
  • in which position add this code ? Commented May 8, 2019 at 12:43
  • Check Updated Answer @Rk Rathod Commented May 8, 2019 at 12:44
  • check checkbox and show in print $data Commented May 8, 2019 at 12:46
  • and check any array generate like this "filename['delete']" Commented May 8, 2019 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.