Magento – Magento2: Adding custom attribute to category doesn’t show store specific value

category-attributecustom-attributesmagento2.2.6store-view

I have created a custom category attribute using the custom code from here, attribute created successfully and able to save the value.

But I want to save store specific value in this custom attribute, So can save different value for English store view and Arabic store view.

I also try another way to create the custom category attribute, but no one saves store specific value.

I also found this issue on GitHub and try the given solution but not one is work for me.

Best Answer

Add below code in category_form.xml

<fieldset name="general">
    <container>
        <field name="my_cat_desc" sortOrder="130" formElement="input">
            <settings>
                <dataType>varchar</dataType>
                <label translate="true">My Cat Description</label>
                <scopeLabel>[STORE VIEW]</scopeLabel>
            </settings>
        </field>
    </container>
</fieldset>

Mynamespace\Mymodule\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">
     <type name="Magento\Catalog\Model\Category\DataProvider">
        <plugin name="category_color_data_mapping" type="Mynamespace\Mymodule\Model\Category\DataProvider" sortOrder="1" disabled="false"/>
    </type>
</config>

Mynamespace\Mymodule\Plugin\Category\DataProvider.php

<?php
namespace Mynamespace\Mymodule\Plugin\Category;

class DataProvider extends \Magento\Catalog\Model\Category\DataProvider
{
    public function __construct(
        Config $eavConfig
    ) {
        $this->eavConfig = $eavConfig;
    }
    
    public function afterPrepareMeta(\Magento\Catalog\Model\Category\DataProvider $subject, $result)
    {
        $meta = $result;
        $meta = array_replace_recursive($meta, $this->prepareFieldsMeta(
            $this->getFieldsMap(),
            $subject->getAttributesMeta($this->eavConfig->getEntityType('catalog_category'))
        ));
        return $meta;

    }
    
    private function prepareFieldsMeta($fieldsMap, $fieldsMeta)
    {
        $result = [];
        foreach ($fieldsMap as $fieldSet => $fields) {
            foreach ($fields as $field) {
                if (isset($fieldsMeta[$field])) {
                    $result[$fieldSet]['children'][$field]['arguments']['data']['config'] = $fieldsMeta[$field];
                }
            }
        }
        return $result;
    }
    protected function getFieldsMap()
    {
        $fields = '';
        $fields['general'][] = 'my_cat_desc';

        return $fields;
    }
}
Related Topic