Need way to add options to already created Color attribute.
-
Ref: webkul.com/blog/programmatically-add-options-attribute-magento2– Rakesh DongaMar 23, 2019 at 11:35
-
i have tried using this way but not working– SouravMar 23, 2019 at 11:37
-
Try this magento.stackexchange.com/questions/201226/…– Rizwan KhanMar 23, 2019 at 15:33
-
let me know whether you would like to associate option values using csv?– Nagaraju KasaMar 23, 2019 at 18:11
-
Hello @Sourav, any solution worked for you ?– PawanMar 25, 2019 at 2:52
4 Answers
Please follow below steps
1.Create csv with color and attribute values as shown below
& keep your csv at M2root/scripts/colorvalues.csv
- 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";
- 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?
-
-
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! May 17 at 16:14
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;
}
}
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 :-
-
-
-
I used same link pearlbells.co.uk/… but in backend there is not any options showing– SouravMar 23, 2019 at 16:21
-
I want to update options values from csv file & using code in file that is at root of magento– SouravMar 23, 2019 at 16:22
-
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);