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
The above code not creating the options, please someone help me on that how can we create a attribute with options. Thanks!!