Skip to content

admin grid form image was not upload with proper path in database

im trying to upload image from admin grid form,image was uploaded but not in proper path,

here is my code,

app/code/Magelearn/Customform/view/adminhtml/ui_component/mladmincustomform_customform_form.xml

<field name="image">
<argument name="data" xsi:type="array">
    <item name="config" xsi:type="array">
        <item name="dataType" xsi:type="string">string</item>
        <item name="source" xsi:type="string">image</item>
        <item name="label" xsi:type="string" translate="true">Image</item>
        <item name="visible" xsi:type="boolean">true</item>
        <item name="formElement" xsi:type="string">fileUploader</item>
        <item name="previewTmpl" xsi:type="string">Magelearn_Customform/image-preview</item>
        <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
        <item name="required" xsi:type="boolean">false</item>
        <item name="uploaderConfig" xsi:type="array">
            <item name="url" xsi:type="url" path="mladmincustomform/customform_fileUploader/save"/>
        </item>
    </item>
</argument>

di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="MagelearnCustomformApiCustomformRepositoryInterface" type="MagelearnCustomformModelCustomformRepository"/>
    <preference for="MagelearnCustomformApiDataCustomformInterface" type="MagelearnCustomformModelDataCustomform"/>
    <preference for="MagelearnCustomformApiDataCustomformSearchResultsInterface" type="MagentoFrameworkApiSearchResults"/>

    <!-- <preference for="MagelearnCustomformCustomformImageUpload" type="MagelearnCustomformModelImageUploader" /> -->

    <virtualType name="MagelearnCustomformModelResourceModelCustomformGridCollection" type="MagentoFrameworkViewElementUiComponentDataProviderSearchResult">
        <arguments>
            <argument name="mainTable" xsi:type="string">magelearn_customform</argument>
            <argument name="resourceModel" xsi:type="string">MagelearnCustomformModelResourceModelCustomformCollection</argument>
        </arguments>
    </virtualType>
    <type name="MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="magelearn_customform_listing_data_source" xsi:type="string">MagelearnCustomformModelResourceModelCustomformGridCollection</item>
            </argument>
        </arguments>
    </type>
    <virtualType name="MagelearnCustomformCustomformImageUpload" type="MagelearnCustomformModelImageUploader">
        <arguments>
                <argument name="baseTmpPath" xsi:type="string">magelearn/customform/tmp</argument>
                <argument name="basePath" xsi:type="string">magelearn/customform</argument>
                <argument name="allowedExtensions" xsi:type="array">
                    <item name="jpg" xsi:type="string">jpg</item>
                    <item name="jpeg" xsi:type="string">jpeg</item>
                    <item name="gif" xsi:type="string">gif</item>
                    <item name="png" xsi:type="string">png</item>
                </argument>
        </arguments>
    </virtualType>
    <type name="MagelearnCustomformControllerAdminhtmlCustomformFileUploaderSave">
        <arguments>
                <argument name="imageUploader" xsi:type="object">MagelearnCustomformCustomformImageUpload</argument>
        </arguments>
    </type>
</config>

Magelearn/Customform/Controller/Adminhtml/Customform/FileUploader/Save.php

<?php

namespace MagelearnCustomformControllerAdminhtmlCustomformFileUploader;
use MagentoFrameworkControllerResultFactory;
class Save extends MagentoBackendAppAction {

    /**
     * Image uploader
     *
     * @var IgorludgeroBrandlistModelImageUploader
     */
    protected $imageUploader;

    /**
     * @param MagentoBackendAppActionContext $context
     * @param IgorludgeroBrandlistModelImageUploader $imageUploader
     */
    public function __construct(
        MagentoBackendAppActionContext $context,
        MagelearnCustomformModelImageUploader $imageUploader
    ) {
        parent::__construct($context);
        $this->imageUploader = $imageUploader;
    }

    /**
     * Check admin permissions for this controller
     *
     * @return boolean
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Magelearn_Customform::Customform');
    }

    public function execute()
    {
        try {
            $result = $this->imageUploader->saveFileToTmpDir('image');

            $result['cookie'] = [
                'name' => $this->_getSession()->getName(),
                'value' => $this->_getSession()->getSessionId(),
                'lifetime' => $this->_getSession()->getCookieLifetime(),
                'path' => $this->_getSession()->getCookiePath(),
                'domain' => $this->_getSession()->getCookieDomain(),
            ];
        } catch (Exception $e) {
            $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
        }
        return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
    }

}

DataProvider.php

<?php
declare(strict_types=1);

namespace MagelearnCustomformModelCustomform;

use MagelearnCustomformModelResourceModelCustomformCollectionFactory;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppFilesystemDirectoryList;

class DataProvider extends MagentoUiDataProviderAbstractDataProvider
{

    protected $loadedData;
    protected $collection;
    protected $filesystem;
    protected $dataPersistor;
    /**
     * Store manager
     *
     * @var MagentoStoreModelStoreManagerInterface
     */
    protected $storeManager;

    /**
     * Constructor
     *
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param CollectionFactory $collectionFactory
     * @param DataPersistorInterface $dataPersistor
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $collectionFactory,
        DataPersistorInterface $dataPersistor,
        MagentoStoreModelStoreManagerInterface $storeManager,
        Filesystem $filesystem,
        array $meta = [],
        array $data = []
    ) {
        $this->collection = $collectionFactory->create();
        $this->dataPersistor = $dataPersistor;
        $this->filesystem = $filesystem;
        $this->storeManager = $storeManager;
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    }

    /**
     * Get data
     *
     * @return array
     */
    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
        $destinationPath = $mediaDirectory->getAbsolutePath('magelearn/customform');
        $items = $this->collection->getItems();
        foreach ($items as $model) {
            $itemData = $model->getData();
            if ($model->getImage()) {
            $imageName = $itemData['image']; // Your database field 
            //unset($itemData['image']);
            $itemData['image'] = array(
                array(
                    'name'  =>  $imageName,
                    'url'   =>  $this->storeManager
                ->getStore()
                ->getBaseUrl(
                    MagentoFrameworkUrlInterface::URL_TYPE_MEDIA
                ).'magelearn/customform'.$itemData['image'] // Should return a URL to view the image. For example, http://domain.com/pub/media/../../imagename.jpeg
                )
            );
            }
            $this->loadedData[$model->getId()] = $itemData;
        }
        $data = $this->dataPersistor->get('mladmincustomform');
        
        if (!empty($data)) {
            $model = $this->collection->getNewEmptyItem();
            $model->setData($data);
            $this->loadedData[$model->getId()] = $model->getData();
            $this->dataPersistor->clear('mladmincustomform');
        }
        
        return $this->loadedData;
    }
    
}

Magelearn/Customform/Controller/Adminhtml/Customform/Save.php

<?php
declare(strict_types=1);

namespace MagelearnCustomformControllerAdminhtmlCustomform;

use MagentoFrameworkExceptionLocalizedException;

class Save extends MagentoBackendAppAction
{

    protected $dataPersistor;

    /**
     * @param MagentoBackendAppActionContext $context
     * @param MagentoFrameworkAppRequestDataPersistorInterface $dataPersistor
     */
    public function __construct(
        MagentoBackendAppActionContext $context,
        MagentoFrameworkAppRequestDataPersistorInterface $dataPersistor
    ) {
        $this->dataPersistor = $dataPersistor;
        parent::__construct($context);
    }

    /**
     * Save action
     *
     * @return MagentoFrameworkControllerResultInterface
     */
    //protected $imageUploader;
    public function execute()
    {
        /** @var MagentoBackendModelViewResultRedirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();
        //echo "<pre>"; print_r($data['image']); die();
        if ($data) {
            $id = $this->getRequest()->getParam('id');            
            
            $model = $this->_objectManager->create(MagelearnCustomformModelCustomform::class)->load($id);

            if (!$model->getId() && $id) {
                $this->messageManager->addErrorMessage(__('This Customform no longer exists.'));
                return $resultRedirect->setPath('*/*/');
            }
            
            echo "<pre>"; print_r($data);
            echo "<pre>"; print_r($data['image'][0]['name']); die();

            if (isset($data['image'][0]['name']) && isset($data['image'][0]['tmp_name'])) {
                $data['image'] = $data['image'][0]['name'];
                
                /*$this->imageUploader = MagentoFrameworkAppObjectManager::getInstance()->get(
                'MagelearnCustomformCustomformImageUpload');*/
                
                /*$imageUploader = $this->_objectManager->get(MagelearnCustomformCustomformImageUpload::class);
                $imageUploader->moveFileFromTmp($data['image']);*/

                $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                $imageUploader = $objectManager->get(MagelearnCustomformCustomformImageUpload::class);                
                $imageUploader->moveFileFromTmp($data['image']);

                //$this->imageUploader = $this->_objectManager->get(MagelearnCustomformCustomformImageUpload::class);
                //$this->imageUploader->setBasePath('magelearn/customform');

                //$this->imageUploader->moveFileFromTmp($data['image']);
            } elseif (isset($data['image'][0]['name']) && !isset($data['image'][0]['tmp_name'])) {
                $data['image'] = $data['image'][0]['name'];
            } else {
                $data['image'] = null;
            }
            $model->setData($data);
        
            try {
                $model->save();
                $this->messageManager->addSuccessMessage(__('You saved the Customform.'));
                $this->dataPersistor->clear('mladmincustomform');
        
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['id' => $model->getId()]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the Customform.'));
            }
        
            $this->dataPersistor->set('mladmincustomform', $data);
            return $resultRedirect->setPath('*/*/edit', ['id' => $this->getRequest()->getParam('id')]);
        }        
        return $resultRedirect->setPath('*/*/');
    }
}

in database its save path image like

“m/a/magento-vs-shopify_1.jpg”,

but need to save like

“magelearn/customform/m/a/magento-vs-shopify_1.jpg”

not saved this path.
please hele me with this.