3

Need way to add options to already created Color attribute.

7

4 Answers 4

4

Please follow below steps

1.Create csv with color and attribute values as shown below
& keep your csv at M2root/scripts/colorvalues.csv

enter image description here

  1. Create colors.php at Magento 2 root directory and paste below code & execute script using command line

php colors.php

 <?php

    ini_set('display_errors', '1');
    ini_set('error_reporting', E_ALL);

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

    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $entityType = 'catalog_product';
    $directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
    $path  =  $directory->getRoot().'/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 = 'colorvalues.csv';

    $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();
        if($data[1])
        {
        foreach((array)$data[1] as $key => $value)
        {
            $str = '"'.$value.'"';
            $option['value'][$str][0]=str_replace('"','', $str);
            foreach($storeArray as $storeKey => $store) 
            {
              $option['value'][$str][$storeKey] = str_replace('"','', $str);
            }   

        }

        $eavSetup->addAttributeOption($option);


        }
        }
    }
        fclose($file);

    echo "Attribute option values has been associated to brand attribute SUCCESSFULLY";
  1. do Re index from command line php bin/magento indexer:reindex

Imp Note: Please try in your default magento2 in local system first and test properly.

Please let me know still facing any issue?

2
  • ok i try and let you know
    – Sourav
    Commented Mar 26, 2019 at 7:05
  • Can confirm that this still works in 2.4.4. Thanks so much. All scripts now need to go into /pub so I had to change the references. You don't know how much time you've just saved me! Commented May 17, 2023 at 16:14
1

Simple and easy to the understandable script here.

<?php

use Magento\Framework\App\Bootstrap;

require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');

attributeValue::addValuesforAttribute('colorAttribute');

class attributeValue{

    public static function addValuesforAttribute($attributeCode)
    {
       $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
       $fileCsv = $objectManager->get('Magento\Framework\File\Csv');
       $attributeFactory = $objectManager->create('Magento\Eav\Setup\EavSetupFactory');
       $eavFactory = $objectManager->get('\Magento\Eav\Model\Entity\AttributeFactory');
        $option = array();
        $eavFactory = $eavFactory->create()->load($attributeCode,"attribute_code");
        $option['attribute_id'] = $eavFactory->getAttributeId();
        $values = "attributeValue.csv";
        $csvData = $fileCsv->getData($values);
        foreach ($csvData as $row => $data) {
                $color = $data[0];
                $option['value'][$color][] =  $color;
    }
        $eavSetup = $attributeFactory->create();
        $eavSetup->addAttributeOption($option);
        echo " \n Options are ";
        print_r($option);
        echo " Succesfull add Options for Attribute ".$attributeCode;
    }
}

CSV color name formate is enter image description here

1
  • Thanks this helped me :)
    – Mujahidh
    Commented Sep 14, 2022 at 7:37
0

Add Attributte Option Like This :-

public function __construct(
         \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
         \Magento\Store\Model\StoreManagerInterface $storeManager,
         \Magento\Eav\Model\Entity\AttributeFactory $eavAttribute
   ){
     $this->_eavAttribute = $eavAttribute;
     $this->_storeManager = $storeManager;
     $this->_eavSetupFactory = $eavSetupFactory;
   }

public function yourFunction()
{
           $attributeId = $this->_eavAttribute->create()->load('color','attribute_code');
           $option = [enter_option_here];
           $allStores = $this->_storeManager->getStores();
           $option['attribute_id'] = $attributeId->getAttributeId();
           foreach($option as $key=>$value){
                $option['value'][$value][0]=$value;
                    foreach($allStores as $store){
                        $option['value'][$value][$store->getId()] = $value;
                    }
                }
                $eavSetup = $this->_eavSetupFactory->create();
                $eavSetup->addAttributeOption($option);}
}

Reference Link :-

Import Attribute Options Programmatically

8
  • this is for magento 1 way i have already tried
    – Sourav
    Commented Mar 23, 2019 at 11:39
  • this used in magento 2 also i used this in my module Commented Mar 23, 2019 at 12:04
  • I used same link pearlbells.co.uk/… but in backend there is not any options showing
    – Sourav
    Commented Mar 23, 2019 at 16:21
  • I want to update options values from csv file & using code in file that is at root of magento
    – Sourav
    Commented Mar 23, 2019 at 16:22
  • pearlbells.co.uk/… I use same code but in admin new values uploaded
    – Sourav
    Commented Mar 23, 2019 at 16:28
0

I've modified @Nagaraju Kasa's solution to allow the script to work with 2.4.4 (not tested higher than that, but it should be OK).

  • Since executable scripts need to be within the /pub dir, I've changed the require line
  • I've also added a check in there to not add the option if it exists already. Magento will just add them anyway and then you're in for a fun day deleting duplicates in the attributes page! This should now mean you don't need to do that :)

Place your csv file in pub/add_opts/csv.

The CSV file hasn't changed from the original answer, it just needs to be [attribute_code],[new_option], so:

color,red
color,blue
color,seafoam green

Place this file in pub/add_opts (name this directory whatever)

<?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().'/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 = 'csv/options.csv';

    $file = fopen($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();
            echo "<h2>" . $attributeCode . "</h2><Br />";

            // Unquote to see dump of current options
            //echo "<pre>" . print_r($options, true) . "</pre>";
            if($data[1])
            {
            foreach((array)$data[1] as $key => $value)
            {
                $str = '"'.$value.'"';
                
                if(in_array($value, array_column($options, 'label'))){
                    echo "<h4 style='color:#ff0000;'>" . $value . "</h4><br />";
                    echo "<p style='color:#ff0000;'>$value already exists in options</p>";
                }else{
                    echo "<p>Adding $value to options</p>";
                    $option['value'][$str][0]=str_replace('"','', $str);

                    foreach($storeArray as $storeKey => $store) 
                    {
                        $option['value'][$str][$storeKey] = str_replace('"','', $str);
                    }
                }

            }

            $eavSetup->addAttributeOption($option);
            echo "<hr />";

            }
        }
    }
        fclose($file);

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.