0

Below is my code to display custom field in catalog category form.

category_form.xml file

<?xml version="1.0" encoding="UTF-8"?>
<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="thumbnail" sortOrder="40" formElement="imageUploader">
            <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>
                <label translate="true">Category Image Icon</label>
                <visible>true</visible>
                <required>false</required>
            </settings>
            <formElements>
                <imageUploader>
                    <settings>
                        <required>false</required>
                        <uploaderConfig>
                            <param xsi:type="url" name="url" path="categorylist/category_thumbnailimage/upload"/>
                        </uploaderConfig>
                        <previewTmpl>Magento_Catalog/image-preview</previewTmpl>
                        <openDialogTitle>Media Gallery</openDialogTitle>
                        <initialMediaGalleryOpenSubpath>catalog/category</initialMediaGalleryOpenSubpath>
                        <allowedExtensions>jpg jpeg gif png</allowedExtensions>
                        <maxFileSize>2194304</maxFileSize>
                    </settings>
                </imageUploader>
            </formElements>
        </field>

        <!-- <field name="thumbnail">
            <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">category</item>
                    <item name="label" xsi:type="string" translate="true">Category Icon Image</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="formElement" xsi:type="string">fileUploader</item>
                    <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                    <item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
                    <item name="required" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="number">30</item>
                    <item name="uploaderConfig" xsi:type="array">
                        <item name="url" xsi:type="url" path="categorylist/category_thumbnailimage/upload"/>
                    </item>
                </item>
            </argument>
        </field> -->
    </fieldset>
</form>

It will save image in Temp folder. Now I want to get that image in phtml file.

In controller file i am already added follow code.

<?php
namespace Vendor\Module\Controller\Adminhtml\Category\Thumbnailimage;

use Magento\Framework\Controller\ResultFactory;

/**
 * Class Upload
 */
class Upload extends \Magento\Backend\App\Action {
    protected $baseTmpPath;
    protected $imageUploader;
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Catalog\Model\ImageUploader $imageUploader
    ) {
        $this->imageUploader = $imageUploader;
        parent::__construct($context);

    }
    public function execute() {

        try {
            $result = $this->imageUploader->saveFileToTmpDir('thumbnail');
            $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);
    }
}

In Setup folder I added InstallData.php

<?php
namespace Vendor\Module\Setup;

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

class InstallData implements InstallDataInterface {
    public function __construct(CategorySetupFactory $categorySetupFactory) {
        $this->categorySetupFactory = $categorySetupFactory;
    }
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
        $installer = $setup;
        $installer->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, 'image_icon');
        $categorySetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY, 'thumbnail', [
                'type' => 'varchar',
                'label' => 'Image Icon',
                'input' => 'image',
                'backend' => 'Magento\Catalog\Model\Category\Attribute\Backend\Image',
                'required' => false,
                'sort_order' => 5,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'General Information',
            ]
        );
        $installer->endSetup();
    }
}

Now, I want to display custom image icon url.

How to get?

0

You need to define Dataprovider for Image

<?php

    namespace VendorName\CategoryBanner\Model\Category;


    use Magento\Catalog\Model\CategoryFactory;
    use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
    use Magento\Eav\Model\Config;
    use Magento\Store\Model\StoreManagerInterface;
    use Magento\Ui\DataProvider\EavValidationRules;
    use Magento\Framework\App\ObjectManager;
    use Magento\Catalog\Model\Category\FileInfo;

    class DataProvider extends \Magento\Catalog\Model\Category\DataProvider
    {
        private $fileInfo;
        protected $_dir;

        public function __construct($name, $primaryFieldName, $requestFieldName, EavValidationRules $eavValidationRules, CategoryCollectionFactory $categoryCollectionFactory, StoreManagerInterface $storeManager, \Magento\Framework\Registry $registry, Config $eavConfig, \Magento\Framework\App\RequestInterface $request, CategoryFactory $categoryFactory,\Magento\Framework\Filesystem\DirectoryList $dir, array $meta = [], array $data = [])
        {
            parent::__construct($name, $primaryFieldName, $requestFieldName, $eavValidationRules, $categoryCollectionFactory, $storeManager, $registry, $eavConfig, $request, $categoryFactory, $meta, $data);
            $this->_dir = $dir;
        }
        private function createImagesDir()
        {
            if ( ! file_exists($this->_dir->getPath('media').'/catalog/category/Banner')) {
                mkdir($this->_dir->getPath('media').'/catalog/category/Banner','0775', true);
            }
        }
        public function getData()
        {
            $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
            $eavModel = $objectManager->create('Magento\Catalog\Model\ResourceModel\Eav\Attribute');
            $attr = $eavModel->load(134);
            $attributeCode = $eavModel->getAttributeCode();
            $this->createImagesDir();
            $data = parent::getData();
            $category = $this->getCurrentCategory();
            if ($category) {
                $categoryData = $category->getData();
                $categoryData = $this->addUseConfigSettings($categoryData);
                $categoryData = $this->filterFields($categoryData);

                $this->loadedData[$category->getId()] = $categoryData;
            }
            $mime = $this->getFileInfo()->getMimeType('/Banner/'.$category->getData('category_banner'));
            $stat = $this->getFileInfo()->getStat('/Banner/'.$category->getData('category_banner'));
            if (isset($data[$category->getId()]['category_banner'])) {
                unset($data[$category->getId()]['category_banner']);

                //create getCategoryThumbUrl in helper file
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $helper     = $objectManager->get('\Shineretrofits\CategoryBanner\Helper\Data');

                $data[$category->getId()]['category_banner'][0]['name'] = $category->getData('category_banner');
                $data[$category->getId()]['category_banner'][0]['url']  = $helper->getCategoryThumbUrl($category);
                $data[$category->getId()]['category_banner'][0]['size'] = isset($stat) ? $stat['size'] : 0;
                $data[$category->getId()]['category_banner'][0]['type'] = $mime;
            }

            return $data;
        }

        protected function getFieldsMap()
        {
            $fields = parent::getFieldsMap();
            $fields['general'][] = 'category_banner'; // NEW FIELD

            return $fields;
        }
        private function getFileInfo()
        {
            if ($this->fileInfo === null) {
                $this->fileInfo = ObjectManager::getInstance()->get(FileInfo::class);
            }
            return $this->fileInfo;
        }
    }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.