0

everyone.
I want to create an image uploader that uploads an image to the server from the admin app category view using the ImageUploader UI component, and stores its path in the database.
So far, I can get the module to upload the image, and store it on the server I can see the files in the pub/media/catalog/category directory, and the path is recorded in the database, but after the upload, the category view in the admin app is stuck with the spinner spinning, and the console outputs the following error:

file-uploader.js:79

TypeError: value.map is not a function. (In 'value.map(this.processFile, this)', 'value.map' is undefined)



Here is my complete source code:

Vendor/Module/Controller/Adminhtml/Category/Image/Upload.php

<?php

namespace Vendor\Module\Controller\Adminhtml\Category\Image;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;

class Upload extends \Magento\Backend\App\Action implements HttpPostActionInterface
{
    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('Magento_Catalog::categories');
    }

    public function execute()
    {
        $imageId = $this->_request->getParam('param_name', 'subcategory_image');

        try {
            $result = $this->imageUploader->saveFileToTmpDir($imageId);
        } catch (\Exception $e) {
            $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
        }
        return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
    }
}

Vendor/Module/etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="categorylist" frontName="categorylist">
            <module name="Vendor_Module" before="Magento_Backend" />
        </route>
    </router>
</config>

Vendor/Module/etc/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">
    <virtualType name="Vendor\Module\CategoryImageUpload" type="Magento\Catalog\Model\ImageUploader">
        <arguments>
            <argument name="baseTmpPath" xsi:type="string">catalog/tmp/category</argument>
            <argument name="basePath" xsi:type="string">catalog/category</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>
            <argument name="allowedMimeTypes" xsi:type="array">
                <item name="jpg" xsi:type="string">image/jpg</item>
                <item name="jpeg" xsi:type="string">image/jpeg</item>
                <item name="gif" xsi:type="string">image/gif</item>
                <item name="png" xsi:type="string">image/png</item>
            </argument>
        </arguments>
    </virtualType>
    <type name="Vendor\Module\Controller\Adminhtml\Category\Image\Upload">
        <arguments>
            <argument name="imageUploader" xsi:type="object">Magento\Catalog\CategoryImageUpload</argument>
        </arguments>
    </type>
</config>

Vendor/Module/Helper/Data.php

<?php

namespace Vendor\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $_storeManagerInterface;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
    ) {
        $this->_storeManagerInterface = $storeManagerInterface;
        parent::__construct($context);
    }

    public function getIconImageUrl($category)
    {
        $url = null;
        $image = $category->getData('subcategory_image');
        if ($image) {
            if (is_string($image)) {
                $url = $this->_storeManagerInterface->getStore()->getBaseUrl(
                    \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                ) . 'catalog/category/' . $image;
            } else {
                $url = false;
            }
        }
        return $url;
    }
}

Vendor/Module/Model/Category/DataProvider.php

<?php

namespace Vendor\Module\Model\Category;

class DataProvider extends \Magento\Catalog\Model\Category\DataProvider
{
    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $category = parent::getCurrentCategory();
        if ($category) {
            $categoryData = $category->getData();
            $categoryData = $this->addUseConfigSettings($categoryData);
            $categoryData = $this->filterFields($categoryData);
            $categoryData = $this->convertValues($category, $categoryData);

            $this->loadedData[$category->getId()] = $categoryData;
        }
        return $this->loadedData;
    }

    private function convertValues($category, $categoryData)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $media_url = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');

        if (isset($categoryData['subcategory_image'])) {
            unset($categoryData['subcategory_image']);
            $fileName2 = $category->getData('subcategory_image');
            $helper = $objectManager->get('Vendor\Module\Helper\Data');
            $categoryData['subcategory_image'][0]['name'] = $category->getData('subcategory_image');
            $categoryData['subcategory_image'][0]['url'] = $helper->getIconimageUrl($category);
            $categoryData['subcategory_image'][0]['size'] = @filesize($directory->getPath('media') . '/catalog/category/' . $fileName2);
        }
        return $categoryData;
    }

    protected function getFieldsMap()
    {
        $fields = parent::getFieldsMap();
        $fields['content'][] = 'subcategory_image';
        return $fields;
    }
}

Vendor/Module/Setup/InstallData.php

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Setup\CategorySetupFactory;

class InstallData implements InstallDataInterface
{
    private $categorySetupFactory;

    public function __construct(CategorySetupFactory $categorySetupFactory)
    {
        $this->categorySetupFactory = $categorySetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
        $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
        $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
        $categorySetup->removeAttribute(
            \Magento\Catalog\Model\Category::ENTITY,
            'subcategory_image'
        );
        $categorySetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY,
            'subcategory_image',
            [
                'backend'      => 'Magento\Catalog\Model\Category\Attribute\Backend\Image',
                'type'         => 'varchar',
                'input'        => 'image',
                'label'        => 'Image',
                'name'         => 'Image',
                'source'       => '',
                'visible'      => true,
                'required'     => false,
                'user_defined' => true,
                'group'        => 'Content',
                'global'       => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL
            ]
        );

        $setup->endSetup();
    }
}

Vendor/Module/view/adminhtml/ui_component/category_form.xml

<?xml version="1.0"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="content">
        <field name="subcategory_image" formElement="imageUploader" sortOrder="3">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
            <settings>
                <elementTmpl>ui/form/element/uploader/image</elementTmpl>
                <dataType>string</dataType>
                <notice translate="true">This image will be displayed as a category menu item in the parent category</notice>
                <label translate="true">Category Menu Image</label>
                <componentType>imageUploader</componentType>
                <visible>true</visible>
                <required>false</required>
            </settings>
            <formElements>
                <imageUploader>
                    <settings>
                        <required>false</required>
                        <allowedExtensions>jpg jpeg gif png</allowedExtensions>
                        <maxFileSize>4194304</maxFileSize>
                        <uploaderConfig>
                            <param xsi:type="url" name="url" path="categorylist/category_image/upload" />
                        </uploaderConfig>
                        <initialMediaGalleryOpenSubpath>catalog/category</initialMediaGalleryOpenSubpath>
                        <previewTmpl>Magento_Catalog/image-preview</previewTmpl>
                        <openDialogTitle>Media Gallery</openDialogTitle>
                    </settings>
                </imageUploader>
            </formElements>
        </field>
    </fieldset>
</form>

Any suggestions on how I might fix this?
Thank you in advance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.