0

I have brand attribute in Magento and want to import all it's options.

1

2 Answers 2

1

1.Create csv with brand and attribute values as shown below & keep your csv at M2root/pub/scripts/attribute-value.csv enter image description here

2.Create import-options-value.php at Magento 2 root directory and paste below code & execute script using command line

php import-options-value.php

<?php
    ini_set('display_errors', '1');
    ini_set('error_reporting', E_ALL);

    use Magento\Framework\App\Bootstrap;
    require '/app/bootstrap.php';

    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $entityType = 'catalog_product';
    $directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
    $path  =  $directory->getRoot().'/pub/scripts/';
    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
    $eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
    $eavSetup = $objectManager->get('\Magento\Eav\Setup\EavSetup');
    $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
    $stores = $storeManager->getStores();
    $storeArray[0] = "All Store Views";
    foreach ($stores  as $store) 
    {
       $storeArray[$store->getId()] = $store->getName();
    }

    $fname = 'attribute-value.csv';
    $optionsExists = array();
    $count = "";
    $file = fopen($path.$fname, "r");
    while (($data = fgetcsv($file, 100000, ",")) !== FALSE)
    {
        foreach((array)$data[0] as $attributeCode)
        {
            $option = array();
            $attribute = $eavConfig->getAttribute($entityType, $attributeCode);
            $option['attribute_id'] = $attribute->getAttributeId();
            $options = $attribute->getSource()->getAllOptions();

            foreach($options as $optionCheck) {
                $optionsExists[] = $optionCheck['label'];
            }
            if($data[1]) {
                foreach((array)$data[1] as $key => $value) {
                    $newOptions = array_diff((array)$data[1], $optionsExists );
                    if ($newOptions) {
                        $str = '"'.$value.'"';
                        $option['value'][$str][0]=str_replace('"','', $str);
                        foreach($storeArray as $storeKey => $store) 
                        {
                          $option['value'][$str][$storeKey] = str_replace('"','', $str);
                        }   
                        $count++;
                        echo 'Added value : '.$value.PHP_EOL;
                    }
                }
                $eavSetup->addAttributeOption($option);

            }
        }
    }
        fclose($file);

    echo "Attribute option values has been associated to brand attribute SUCCESSFULLY Total = ".$count;
1

Please, try the code below. It works on Magento 2.4.

/**
 * @var \Magento\Eav\Api\AttributeOptionManagementInterface
 */
protected $attributeOptionManagement;

/**
 * @var \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory
 */
protected $optionLabelFactory;

/**
 * @var \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory
 */
protected $optionFactory;

/**
 * Update constructor.
 *
 * @param \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement
 * @param \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory
 * @param \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory
 */
public function __construct(
    \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
    \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory,
    \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory
) {
    $this->attributeOptionManagement = $attributeOptionManagement;
    $this->optionLabelFactory = $optionLabelFactory;
    $this->optionFactory = $optionFactory;
}

/**
 * Create attribute option
 *
 * @param string $attributeCode
 *
 * @throws \Magento\Framework\Exception\InputException
 * @throws \Magento\Framework\Exception\StateException
 */
public function addOptions(string $attributeCode): void
{
    foreach ($this->labels as $label) {
        var_dump('add option ' . $label);
        /** @var OptionLabel $optionLabel */
        $optionLabel = $this->optionLabelFactory->create();
        $optionLabel->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
        $optionLabel->setLabel($label);

        $option = $this->optionFactory->create();
        $option->setLabel($label);
        $option->setStoreLabels([$optionLabel]);
        $option->setSortOrder(0);
        $option->setIsDefault(false);

        $this->attributeOptionManagement->add(
            \Magento\Catalog\Model\Product::ENTITY,
            $attributeCode,
            $option
        );
    }
}
1
  • 1
    stackexchange and clean magento code? Really? Whats happening with the world?
    – jekabs
    Aug 10, 2022 at 14:24

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.