cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2 Object Instance Quesiton

Magento 2 Object Instance Quesiton

Some strange. I add color values and color swatches. I call it two times. First call \Magento\Catalog\Model\Product\Attribute\Repository   to check duplicated color label with current database. After checking, second time adding the safe color value and color swatch to the Magenot

 

Strange point is that first load color attribute seem to be cached so affect second cal object result. When I comment the first call, leave single call then no exception. Why so strange?

 

I doubt Magento singleton issue or I did not stamp an brand new object. However, tried but in vain.

 

So what's wrong I made?

 

Doing Color Swatch Reference Link:

http://www.marcelmoldovan.com/dev/create-custom-swatch-attributes-programmatically-in-magento-2/

 

Check Duplicated that is not included in reference link

$colorOptions = $this->attributeRepository->get('color')->getSource()->getAllOptions();
$colorArray = array();
foreach ($colorOptions as $option) { 
   // $option->getValue();  // Value
	$colorArray[] = $option['label'];  // Label
}
foreach ($attributesOptionsData as &$attributeOptionsData) {
	$order = 0;
	$swatchVisualFiles = isset($attributeOptionsData['optionvisual']['value'])
		? $attributeOptionsData['optionvisual']['value']
		: [];
	foreach ($swatchVisualFiles as $index => $swatchVisualFile) {
		if(in_array($swatchVisualFile[0], $colorArray)){
			unset($attributesOptionsData['color']['optionvisual']['value'][$index]);
			unset($attributesOptionsData['color']['swatchvisual']['value'][$index]);
			continue;
		}
	}
}

 

Save

foreach ($attributesOptionsData as $code => $attributeOptionsData) {
	/* @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
	$attribute = $this->attributeRepository->get($code);
	$attribute->addData($attributeOptionsData);
	$attribute->save();
}

 

 

 

1 REPLY 1

Re: Magento 2 Object Instance Quesiton

Same with me here. I also need color swatch import function and got what you encounter. Why so strange?

 

Could anyone solve it?