Làm sao thêm Magento 2 category attribute

Step #1: Create the Attribute

The following is a full example of an install script that creates a category attribute. If you already have a category attribute, it is not necessary.

namespace Namespace\Module\Setup;

use Magento\Framework\Setup\{

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;

class InstallData implements InstallDataInterface
private $eavSetupFactory;

public function __construct(EavSetupFactory $eavSetupFactory) {
$this->eavSetupFactory = $eavSetupFactory;

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(\Magento\Catalog\Model\Category::ENTITY, 'attribute_id', [
'type' => 'int',
'label' => 'Your Category Attribute Name',
'input' => 'boolean',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
'visible' => true,
'default' => '0',
'required' => false,
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
'group' => 'Display Settings',

Step #2: Display the Attribute

The category UI Component is rendered with configuration from the category_form.xml file. All files with that name are merged together. As a result, you can add a field by creating a category_form.xml file in the view/adminhtml/ui_component directory in your module.

Here is a full example of adding a field under the “Display Settings” group. It is important to note that attribute_id should match the ID of the attribute that you created in the install script.

boolean checkbox Your Category Attribute Name toggle 1 0 0

Category: Magento