Magento 2.1 – How to Create Category Attribute Thumbnail

magento-2.1magento2

create category attribute thumbnail.
i create require file as per new magento 2.1
This is my category_form.xml

<?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">
            <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">Thumbnail 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="catalog/category_image/upload"/>
                    </item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

when i upload image i show following error

{error: "The file was not uploaded.", errorcode: 666}
error: "The file was not uploaded."
errorcode: 666

i am not sure this is magento 2.1 bug ya something wrong in my code ?

Best Answer

Your code seems good. but you missed one minor mistake here.

as per above category_form.xml code you created new field <field name="thumbnail">.
So newly created element name will be thumbnail here.

but you are using core module controller to perform upload operation.

<item name="uploaderConfig" xsi:type="array">
    <item name="url" xsi:type="url" path="catalog/category_image/upload"/>
</item>

and in this controller core code has been paasing image field name for image element. i.e.

$result = $this->imageUploader->saveFileToTmpDir('image');

so difference is here. You should be pass your custom field name i.e. thumbnail

Solution

  1. Create your own controller class in your custom module. e.g. app/code/namespace/modulename/Controller/Adminhtml/Category/Image/Upload.php
  2. Copy whole code from above class and paste into your class.
  3. replace fieldname 'image' with thumbnail

    $result = $this->imageUploader->saveFileToTmpDir('thumbnail');

Please you can get complete solution here Marius answer completely.