Magento 2 – How to Preview Uploaded Image in Form When Editing

image-uploadmagento-2.1

When I try to upload the image, it was successfully uploading the image as well as save the image name into the database but when I click on edit, it will show me the below error message in my console:

Uncaught TypeError: value.map is not a function - file-uploader.js:69

enter image description here

Below is my code ui_component XML file

<field name="brand_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">Branddetails</item>
                <item name="label" xsi:type="string" translate="true">Brand Image</item>
                <item name="visible" xsi:type="boolean">true</item>
                <item name="formElement" xsi:type="string">fileUploader</item>
                <item name="previewTmpl" xsi:type="string">[Namespace_Module]/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="[Module]/[controller-folder]/upload"/>
                </item>
            </item>
        </argument>
    </field>

Upload.php in my controller folder

<?php
namespace [Namespace]\[Module]\Controller\Adminhtml\[controller-folder];
use Magento\Framework\Controller\ResultFactory;
class Upload extends \Magento\Backend\App\Action
{
protected $imageUploader;

public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Catalog\Model\ImageUploader $imageUploader
) {     
    parent::__construct($context);
    $this->imageUploader = $imageUploader;
}

protected function _isAllowed()
{
    return $this->_authorization->isAllowed('[Namespace_Module]::[entity]');
}

public function execute()
{
    try {
        $result = $this->imageUploader->saveFileToTmpDir('brand_image');
        //echo '<pre>';print_r($result);die;
        $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 in Model

<?php 
namespace [Namespace]\[Module]\Model\Branddetails;
use Magento\Ui\DataProvider\AbstractDataProvider;
use Magento\Ui\DataProvider\Modifier\ModifierInterface;
use Magento\Ui\DataProvider\Modifier\PoolInterface;
use [Namespace]\[Module]\Model\ResourceModel\[entity]\CollectionFactory;
class DataProvider extends AbstractDataProvider {
protected $_loadedData;

public function __construct(
    $name,
    $primaryFieldName,
    $requestFieldName,
    CollectionFactory $CollectionFactory,
    array $meta = [],
    array $data = []
) {
    $this->collection = $CollectionFactory->create();
    parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
}

public function getData()
{
    if (isset($this->_loadedData)) {
        return $this->_loadedData;
    }
    $items = $this->collection->getItems();

    foreach ($items as $brand) {            
        $this->_loadedData[$brand->getEntityId()] = $brand->getData();
    }
    //echo '<pre>';print_r($this->_loadedData);die;
    return $this->_loadedData;
}
}

Please help me to solve this error.
Thanks in advance.

Best Answer

Ya finally I got the answer, I just modify the function in the DataProvider.php and it will solve the problem.

DataProvider.php

public function getData()
{      
    if (isset($this->_loadedData)) {
        return $this->_loadedData;
    }
    $items = $this->collection->getItems();

    foreach ($items as $brand) {            
        $brandData = $brand->getData();
        $brand_img = $brandData['brand_image'];
        unset($brandData['brand_image']);
        $brandData['brand_image'][0]['name'] = $brand_img;
        $brandData['brand_image'][0]['url'] = $brand_img_url;           
        $this->_loadedData[$brand->getEntityId()] = $brandData;     
    }

    return $this->_loadedData;
}

enter image description here

Related Topic