0

enter image description here

The image is already saved in the uploaded image. But when editing the form it shows No file Chosen. How can I fetch the previously save the image?

Here is the save.php code:

    <?php

namespace Webkul\Grid\Controller\Adminhtml\Grid;

use Magento\Framework\App\Filesystem\DirectoryList;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var \AdminGrid\Grid\Model\GridFactory
     */
    var $gridFactory;
    protected $_mediaDirectory;
    protected $_fileUploaderFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \AdminGrid\Grid\Model\GridFactory $gridFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Webkul\Grid\Model\GridFactory $gridFactory,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
    ) {
        parent::__construct($context);
        $this->gridFactory = $gridFactory;
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
        $this->_fileUploaderFactory = $fileUploaderFactory;
    }

    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();

        try{

            $target = $this->_mediaDirectory->getAbsolutePath('mycustomfolder/');

            $targetOne = "mycustomfolder/";
            /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
            $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
            /** Allowed extension types */
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);
            /** rename file name if already exists */
            $uploader->setAllowRenameFiles(true);
            /** upload file in folder "mycustomfolder" */
            $result = $uploader->save($target);

        }
        catch (Exception $e) 
        {
            $this->messageManager->addError($e->getMessage());
        }


        $data = $this->getRequest()->getPostValue();

        $data['image'] = $targetOne.$result['file'];

        if (!$data) {
            $this->_redirect('grid/grid/addrow');
            return;
        }
        try {
            $rowData = $this->gridFactory->create();
            $rowData->setData($data);
            if (isset($data['id'])) {
                $rowData->setEntityId($data['id']);
            }
            $rowData->save();
            $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
        } catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
        }
        $this->_redirect('grid/grid/index');


    }

    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Webkul_Grid::save');
    }
}
6

1 Answer 1

1

I solved it by adding additional code in save.php.

Save.php

<?php

namespace Webkul\Grid\Controller\Adminhtml\Grid;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem;
use Webkul\Grid\Model\GridFactory;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var \AdminGrid\Grid\Model\GridFactory
     */
    var $gridFactory;
    protected $_mediaDirectory;
    protected $_fileUploaderFactory;
    protected $adapterFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \AdminGrid\Grid\Model\GridFactory $gridFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Webkul\Grid\Model\GridFactory $gridFactory,
        \Magento\Framework\Filesystem $filesystem,
        AdapterFactory $adapterFactory,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
        \Magento\Framework\Filesystem\Driver\File $file
    ) {
        parent::__construct($context);
        $this->gridFactory = $gridFactory;
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
        $this->_fileUploaderFactory = $fileUploaderFactory;
        $this->adapterFactory = $adapterFactory;
        $this->_file = $file;
    }

    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        if ($this->getRequest()->getPostValue()) {
        try {
            $model = $this->_objectManager->create('Webkul\Grid\Model\Grid');
            $data = $this->getRequest()->getPostValue();
            if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
        try{

            $target = $this->_mediaDirectory->getAbsolutePath('mycustomfolder/');

            $targetOne = "mycustomfolder/";
            /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
            $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
            /** Allowed extension types */
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);

            $imageAdapter = $this->adapterFactory->create();
            $uploader->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
            /** rename file name if already exists */
            $uploader->setAllowRenameFiles(true);
            /** upload file in folder "mycustomfolder" */
            $result = $uploader->save($target);

            if (!$result) {
                throw new LocalizedException(
                    __('File cannot be saved to path: $1', $target)
                );
            }

            $data['image'] = $targetOne.$result['file'];

        }
            catch (\Exception $e) {
            }
        }

        if(isset($data['image']['delete']) && $data['image']['delete'] == 1) {
                    $_mediaDirectory = $this->filesystem->getDirectoryRead($this->directoryList::MEDIA)->getAbsolutePath();
                    $file = $data['image']['value'];
                    $imgPath = $_mediaDirectory.$file;
                    if ($this->_file->isExists($imgPath))  {
                        $this->_file->deleteFile($imgPath);
                    }
                    $data['image'] = NULL;
                }
                if (isset($data['image']['value'])){
                    $data['image'] = $data['image']['value'];
                }
                $inputFilter = new \Zend_Filter_Input(
                    [],
                    [],
                    $data
                );
                $data = $inputFilter->getUnescaped();
                $id = $this->getRequest()->getParam('id');
                if ($id) {
                    $model->load($id);
                    if ($id != $model->getId()) {
                        throw new \Magento\Framework\Exception\LocalizedException(__('The wrong item is specified.'));
                    }
                }
                $model->setData($data);
                $session = $this->_objectManager->get('Magento\Backend\Model\Session');
                $session->setPageData($model->getData());
                $model->save();
                $this->messageManager->addSuccess(__('You saved the item.'));
                $session->setPageData(false);
                if ($this->getRequest()->getParam('back')) {
                    $this->_redirect('grid/*/editrow', ['id' => $model->getId()]);
                    return;
                }
                $this->_redirect('grid/*/');
                return;
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
                $id = (int)$this->getRequest()->getParam('id');
                if (!empty($id)) {
                    $this->_redirect('grid/*/editrow', ['id' => $id]);
                } else {
                    $this->_redirect('grid/*/index');
                }
                return;
            } catch (\Exception $e) {
                $this->messageManager->addError(
                    __('Something went wrong while saving the item data. Please review the error log.')
                );
                $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
                $this->_objectManager->get('Magento\Backend\Model\Session')->setPageData($data);
                $this->_redirect('grid/*/editrow', ['id' => $this->getRequest()->getParam('id')]);
                return;
            }
        }
        $this->_redirect('grid/*/');
    }



    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Webkul_Grid::save');
    }
}

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.