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');
    }
}
Kowsigan Atsayam
  • 484
  • 4
  • 9
  • 28
  • Check this link https://magento.stackexchange.com/questions/269883/in-admin-form-after-edit-and-save-a-form-in-db-already-stored-image-save-as-bla @kowsigan – Divya Sekar Sep 04 '19 at 04:43
  • have you check a above link if you have any doubt comment me. – Divya Sekar Sep 04 '19 at 10:32
  • @divyasekar It worked great. Thank you so much, Divya. Are you from Madurai? Glad to see a person from TN here. I am from Coimbatore. – Kowsigan Atsayam Sep 06 '19 at 13:02
  • 1
    Yes i m from madurai if you have any query ping me @kowsigan – Divya Sekar Sep 06 '19 at 13:09
  • @divyasekar, Is it possible to have inline edit for an image in the grid? Look my question -> https://magento.stackexchange.com/questions/287171/how-to-have-inline-edit-for-image-in-magento-2-admin-grid – Kowsigan Atsayam Sep 06 '19 at 13:27
  • @divyasekar, Hi divya, can you answer this question? ->https://magento.stackexchange.com/questions/289470/invalid-form-key-please-refresh-the-page-while-creating-new-users-in-magento-2 – Kowsigan Atsayam Sep 12 '19 at 11:00

1 Answers1

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');
    }
}
Kowsigan Atsayam
  • 484
  • 4
  • 9
  • 28