Magento 2 create category attribute using upgradeData

create category custom layout in Magento 2

Today we discuss about the Magento 2 create category attribute using upgradeData using the script.

We are creating a select box category attribute using the below steps.

  1. Increase the module version from 1.0.0 to 1.0.1 in module.xml file
    Path: app/code/Custom/CategoryAttribute/etc/module.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Custom_CategoryAttribute" setup_version="1.0.1">
		<sequence>
			<module name="Magento_Catalog"/>
		</sequence>
	</module>
</config>
  1. Create UpgradeData.php file in the setup folder.
    Path: app/code/Custom/CategoryAttribute/Setup/UpgradeData.php
<?php
/**
 * Copyright © 234556 All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Custom\CategoryAttribute\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

class UpgradeData implements UpgradeDataInterface
{

    private $eavSetupFactory;

    /**
     * Constructor
     *
     * @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function upgrade(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        if (version_compare($context->getVersion(), "1.0.1", "<")) {
            $setup->getConnection()->startSetup();
            /** @var EavSetup $eavSetup */

            $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
            $eavSetup->addAttribute(
                \Magento\Catalog\Model\Category::ENTITY,
                'blog_type',
                [
                    'type' => 'int',
                    'label' => 'Select Blog Type',
                    'input' => 'select',
                    'sort_order' => 335,
                    'source' => 'Custom\CategoryAttribute\Model\Source\Blogtype',
                    'global' => ScopedAttributeInterface::SCOPE_STORE,
                    'visible' => true,
                    'required' => false,
                    'user_defined' => false,
                    'default' => null,
                    'group' => 'General Information',
                    'backend' => ''
                ]
            );

            $setup->getConnection()->endSetup();
        }
    }
}

‘source’ => ‘Custom\CategoryAttribute\Model\Source\Blogtype’,

3. Create a Source file to return the option for the drop-down
Path: app/Custom/CategoryAttribute/Base/Model/Source/Blogtype.php

<?php

namespace Custom\CategoryAttribute\Model\Source;

use Magefan\Blog\Model\ResourceModel\Category\CollectionFactory;

class Blogtype extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    
    protected $_categoryFactory;

    /**
     * Construct
     *
     * @param CollectionFactory $categoryFactory
     */
    public function __construct(CollectionFactory $categoryFactory)
    {
        $this->_categoryFactory = $categoryFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function getAllOptions()
    {
        $options    = array();
        $collection = $this->_categoryFactory->create();
        $options[]  = [
               'value' => '',
               'label' => 'Select blog type'
           ];
        foreach($collection as $block){            
            if($block->getData('is_active')){
                $options[] = [
                   'value' => $block->getData('category_id'),
                   'label' => $block->getData('title')
               ];
            }           
        } 

        /*
        print_r($options); // print array
        Array
		(
		    [0] => Array
		        (
		            [value] => 
		            [label] => Select blog type
		        )

		    [1] => Array
		        (
		            [value] => 1
		            [label] => Blog Category1
		        )

		    [2] => Array
		        (
		            [value] => 2
		            [label] => Blog Category2
		        )

		) */
        return $options;     
    }
}

Note: We are using the Magefan blog category collection

  1. Create category_form.xml file to displace attributes in the category.
    Path: app/code/Custom/CategoryAttribute/view/adminhtml/ui_component/category_form.xml
<?xml version="1.0" ?>
<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="blog_type">
			<argument name="data" xsi:type="array">
				<item name="options" xsi:type="object">Custom\CategoryAttribute\Model\Source\Blogtype</item>
				<item name="config" xsi:type="array">
					<item name="required" xsi:type="boolean">false</item>
					<item name="validation" xsi:type="array">
						<item name="required-entry" xsi:type="boolean">false</item>
					</item>
					<item name="sortOrder" xsi:type="number">335</item>
					<item name="dataType" xsi:type="string">string</item>
					<item name="formElement" xsi:type="string">select</item>
					<item name="label" xsi:type="string" translate="true">Select Blog Type</item>
				</item>
			</argument>
		</field>
	</fieldset>
</form>

Run commands:
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento c:f

Get the attribute value in the file of the current category

<?php 
    $catalogHelperData = $this->helper('Magento\Catalog\Helper\Data');
    $categoryObject = $catalogHelperData->getCategory();
    $blog_type = $categoryObject->getBlogType();
    var_dump($blog_type); 
?>

Like us on Facebook and Linkedin for more updates.

Create Category Custom Layout In Magento 2

Magento 2 create category attribute using upgradeData

Back To Top