2

I am creating a product attribute with option using Magento 2.3 Data patch.

Used below code.

<?php
declare(strict_types=1);

namespace Vendor\Module\Setup\Patch\Data;

use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class AddFeatureAttribute implements DataPatchInterface
{

private $moduleDataSetup;
private $eavSetupFactory;
public $_storeManager;
private $logger;
protected $_dir;
public function __construct(
    ModuleDataSetupInterface $moduleDataSetup,
    EavSetupFactory $eavSetupFactory,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\Filesystem\DirectoryList $dir
) {
    $this->moduleDataSetup = $moduleDataSetup;
    $this->eavSetupFactory = $eavSetupFactory;
    $this->_storeManager = $storeManager;
    $this->logger = $logger;  
    $this->_dir = $dir;
}

/**
 * {@inheritdoc}
 */
public function apply()
{
    /** @var EavSetup $eavSetup */
    $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

    $fileName = 'attributes.csv';
    $pubPath = $this->_dir->getPath('pub');
    $attributeFile = $pubPath.'/'.$fileName;
    $arrResult = array();
    if(($handle = fopen($attributeFile, 'r')) !== FALSE) {
        $row = 1;
        while(($data = fgetcsv($handle, 1000000, ',')) !== FALSE) {
            $col_count = count($data);
            $arrResult[] = $data;               
            $row++;
        }
        fclose($handle);
    } 
    $i = 0;
    foreach ($arrResult as $line) {
        if($i > 0){
            $attributeCode = $line[0];                    
            $attributeName = $line[1];
            $inputType = strtolower($line[2]);
            $options = $line[3];
          $type = 'int';
      $eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
           $attributeCode,
           [
             'type' => $type,
             'group' => 'General',
             'backend' => '',
             'frontend' => '',
             'label' => $attributeName,
             'input' => $inputType,
             'class' => '',
             'source' => '',
             'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
             'visible' => true,
             'required' => false,
             'user_defined' => true,
             'searchable' => false,
             'filterable' => true,
             "filterable_in_search" => '1',
             'comparable' => false,
             'visible_on_front' => true,
             'used_in_product_listing' => true,
             'unique' => false,                 
             'option' => [
                'values' => $options,
               ],
             'system' => 1                    
             ]
           );
       }
     $i++;
   }

  }

public static function getDependencies()
 {
    return [];
 }

 /**
 * {@inheritdoc}
 */
 public function getAliases()
  {
     return [];
  }
}

The sample csv file is like below

enter image description here

The above code not creating the options, please someone help me on that how can we create a attribute with options. Thanks!!

3 Answers 3

3

you can try following way..

Here my attribute is Color

Vendor/Module/Setup/Patch/Data/AddColorProductAttribute.php

<?php


namespace Vendor\Module\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchRevertableInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

/**
 * Class AddColorProductAttribute
 *
 * @package Vendor\Module\Setup\Patch\Data
 */
class AddColorProductAttribute implements DataPatchInterface, PatchRevertableInterface
{

    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;
    /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Constructor
     *
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $this->moduleDataSetup->getConnection()->startSetup();
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'color',
            [
                'type' => 'int',
                'label' => 'color',
                'input' => 'select',
                'source' => \Vendor\Module\Model\Product\Attribute\Source\Color::class,
                'frontend' => '',
                'required' => true,
                'backend' => '',
                'sort_order' => '30',
                'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
                'default' => null,
                'visible' => true,
                'user_defined' => true,
                'searchable' => true,
                'filterable' => true,
                'comparable' => true,
                'visible_on_front' => true,
                'unique' => false,
                'apply_to' => 'simple,grouped,bundle,configurable,virtual',
                'group' => 'General',
                'used_in_product_listing' => true,
                'is_used_in_grid' => true,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => false,
                'option' => ''
            ]
        );

        $this->moduleDataSetup->getConnection()->endSetup();
    }

    public function revert()
    {
        $this->moduleDataSetup->getConnection()->startSetup();
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY, 'color');

        $this->moduleDataSetup->getConnection()->endSetup();
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [
        
        ];
    }
}

Vendor/Module/Model/Product/Attribute/Source/Color.php

<?php


namespace Vendor\Module\Model\Product\Attribute\Source;

/**
 * Class Color
 *
 * @package Vendor\Module\Model\Product\Attribute\Source
 */
class Color extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{

    /**
     * getAllOptions
     *
     * @return array
     */
    public function getAllOptions()
    {
        $this->_options = [
        
        ];
        return $this->_options;
    }

    /**
     * @return array
     */
    public function getFlatColumns()
    {
        $attributeCode = $this->getAttribute()->getAttributeCode();
        return [
        $attributeCode => [
        'unsigned' => false,
        'default' => null,
        'extra' => null,
        'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
        'length' => 255,
        'nullable' => true,
        'comment' => $attributeCode . ' column',
        ],
        ];
    }

    /**
     * @return array
     */
    public function getFlatIndexes()
    {
        $indexes = [];
        
        $index = 'IDX_' . strtoupper($this->getAttribute()->getAttributeCode());
        $indexes[$index] = ['type' => 'index', 'fields' => [$this->getAttribute()->getAttributeCode()]];
        
        return $indexes;
    }

    /**
     * @param int $store
     * @return \Magento\Framework\DB\Select|null
     */
    public function getFlatUpdateSelect($store)
    {
        return $this->eavAttrEntity->create()->getFlatUpdateSelect($this->getAttribute(), $store);
    }
}
3
  • Thank you for the answer, but how can we import from csv and create the options. as like in the question. Commented Mar 21, 2020 at 7:27
  • @jafarpinjar you need to logic add in model class file Commented Mar 21, 2020 at 8:28
  • Yea I have logic used in my patch file, can you help as in that please Commented Mar 22, 2020 at 7:00
0
<?php

declare(strict_types=1);
namespace Moazzam\CustomProductAttribute\Setup\Patch\Data;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Zend_Validate_Exception;

/**
 * Add custom select attribute
 *
 * Class ProductAttribute
 */
class ProductAttribute implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private ModuleDataSetupInterface $_moduleDataSetup;

    /**
     * @var EavSetupFactory
     */
    private EavSetupFactory $_eavSetupFactory;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->_moduleDataSetup = $moduleDataSetup;
        $this->_eavSetupFactory = $eavSetupFactory;
    }

    /**
     * Apply the patch
     *
     * @return void
     * @throws LocalizedException
     * @throws Zend_Validate_Exception
     */
    public function apply()
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->_eavSetupFactory->create(['setup' => $this->_moduleDataSetup]);

        $eavSetup->addAttribute(\Magento\Catalog\Model\Product::ENTITY, 'clothing_materials', [
            'group' => 'Product Details',
            'type' => 'int',
            'backend' => '',
            'frontend' => '',
            'sort_order' => 210,
            'label' => 'Clothing Materials',
            'input' => 'select',
            'class' => '',
            'source' => 'Moazzam\CustomProductAttribute\Model\Source\Customdropdown',
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            'visible' => true,
            'required' => false,
            'user_defined' => false,
            'default' => '',
            'searchable' => false,
            'filterable' => false,
            'comparable' => false,
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'apply_to' => ''
        ]);
    }

    /**
     * Get Dependencies
     *
     * @return array|string[]
     */
    public static function getDependencies(): array
    {
        return [];
    }

    /**
     * Get alisas
     *
     * @return array|string[]
     */
    public function getAliases(): array
    {
        return [];
    }
}
0
<?php

declare(strict_types=1);
namespace Moazzam\CustomProductAttribute\Model\Source;

use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;

/**
 * Make the option for custom dropdown source model
 *
 * Class Customdropdown
 * @package Moazzam\CustomProductAttribute\Model\Source
 */
class Customdropdown extends AbstractSource
{
    /**
     * Make the option for source model
     *
     * @return array|array[]|null
     */
    public function getAllOptions(): ?array
    {
        if ($this->_options === null) {
            $this->_options = [
                ['label' => __('--Select--'), 'value' => ''],
                ['label' => __('Cotton'), 'value' => 1],
                ['label' => __('Wool'), 'value' => 2],
                ['label' => __('Linen'), 'value' => 3],
                ['label' => __('Viscose'), 'value' => 4]
            ];
        }
        return $this->_options;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.