DEV Community

loading...

Adding a custom attribute to a category doesn't show store specific value

Anuradha Fernando
PHP/Magento Cloud developer.
Updated on ・2 min read

When adding a custom attribute to a category in the admin, Store Scope will not show even though we set the Store View in the setup script.
Vendor/Module/Setup/Patch/Data/AddViewModeCategoryAttribute.php

$eavSetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY,
            'attribute_code',
            [
                'type' => 'text',
                'label' => 'ATTRIBUTE LABLE',
                'input' => 'select',
                'sort_order' => 333,
                'source' => 'Vendor\Module\Model\Category\Attribute\Source\NAME',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => 'grid',
                'group' => 'General Information',
                'backend' => ''
            ]
        );
Enter fullscreen mode Exit fullscreen mode

Expected result

  1. Should see [Store View] label under the attribute label.
  2. Should be able to see different values per scope level (global, website, store)

Actual result

  1. Can't see the [Store View] label under the attribute label.
  2. Can't see different values per scope level (global, website, store)
  3. Can see different values in the database

This is a Magento2 bug and not yet fixed in 2.3

As a fix, please use the below code.

Add below code into your module's di.xml

<preference for="Magento\Catalog\Model\Category\DataProvider" type="Vendor\Module\Model\Category\DataProvider" />
Enter fullscreen mode Exit fullscreen mode

In order to add the 'Use Default Value' checkbox for custom attributes, we need to override DataProvider.php. There is a function called 'getFieldsMap'. So after modifying the 'getFieldsMap' function 'DataProvider' class will be as follows.

Vendor/Module/Model/Category/DataProvider.php

namespace Vendor\Module\Model\Category;

use Magento\Catalog\Model\Category\DataProvider as CategoryDataProvider;

class DataProvider extends CategoryDataProvider
{
    protected function getFieldsMap() {
        $parentFieldMap = parent::getFieldsMap();       

        array_push($parentFieldMap['general'], 'attribute_code');
        return $parentFieldMap;
    }
}
Enter fullscreen mode Exit fullscreen mode

replace the 'attribute_code' with the actual attribute code
'general' => section in admin panel form, where attribute is displayed

Run the setup upgrade command and clear the cache. You will be able to set store specific values for custom attributes.

cheers!!

Discussion (0)