Create Visual Swatch AttributeMagento 2 create custom swatch attribute programmaticallyConfigurable swatch images disappearedMagento2 programmatically adding a custom optionMagento 2, Text Swatch, can't turn off “Visible on catalog pages”!Magento2 : Custom Category Attribute value Not Saving?Magento 2: How to add “async” attribute to <script> links in document headMagento 2 - Get Swatch Image based on swatch labelCan't change dropdown attribute to visual swatch on Magento 2Product attribute don't save in backendM2.2.3 : How can I create a Category Attribute in the global scope?Magento 2 - Setting “Text Swatch” or “Visual Swatch” does not work. Attribute still shows as dropdown on frontend
Should I report a leak of confidential HR information?
How to fix a dry solder pin in BGA package?
Why transcripts instead of degree certificates?
Are metaheuristics ever practical for continuous optimization?
Most importants new papers in computational complexity
Who are these Discworld wizards from this picture?
How hard is it to sell a home which is currently mortgaged?
Why did this meteor appear cyan?
Where can I get macOS Catalina Beta version?
What is the line crossing the Pacific Ocean that is shown on maps?
Did Wakanda officially get the stuff out of Bucky's head?
Generate and graph the Recamán Sequence
How did researchers use to find articles before the Internet and the computer era?
Miss Toad and her frogs
Reverse of diffraction
Can 'leave' mean 'forget'?
Being paid less than a "junior" colleague
How can I get edges to bend to avoid crossing?
Is there a nice way to assign std::minmax(a, b) to std::tie(a, b)?
Can you sign using a digital signature itself?
What is the difference between x RadToDeg cos x div and COSC?
What are good ways to spray paint a QR code on a footpath?
Which resurrection spells are valid to use with the Zealot's 'Warrior of the Gods' Feature?
Can another character physically take something that Mage Hand is carrying/holding?
Create Visual Swatch Attribute
Magento 2 create custom swatch attribute programmaticallyConfigurable swatch images disappearedMagento2 programmatically adding a custom optionMagento 2, Text Swatch, can't turn off “Visible on catalog pages”!Magento2 : Custom Category Attribute value Not Saving?Magento 2: How to add “async” attribute to <script> links in document headMagento 2 - Get Swatch Image based on swatch labelCan't change dropdown attribute to visual swatch on Magento 2Product attribute don't save in backendM2.2.3 : How can I create a Category Attribute in the global scope?Magento 2 - Setting “Text Swatch” or “Visual Swatch” does not work. Attribute still shows as dropdown on frontend
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
Can anyone provide a working example for creating a visual swatch (or even a text swatch) attribute as part of a setup script.
I've tried the example on Magento 2 create custom swatch attribute programmatically but it doesn't work for me.
The issue I've ran into there is that the the attribute repository cannot find the new attribute that was created. I tried putting some cache clearing in between but no luck.
Thanks.
magento2 swatches
|
show 1 more comment
Can anyone provide a working example for creating a visual swatch (or even a text swatch) attribute as part of a setup script.
I've tried the example on Magento 2 create custom swatch attribute programmatically but it doesn't work for me.
The issue I've ran into there is that the the attribute repository cannot find the new attribute that was created. I tried putting some cache clearing in between but no luck.
Thanks.
magento2 swatches
You can set directly it from admin.
– Suresh Chikani
May 4 '17 at 8:39
I'm looking to do this in a setup script.
– Paul
May 4 '17 at 9:01
magento.stackexchange.com/questions/133237/…
– Ankit Shah
May 8 '17 at 7:25
@AnkitShah that's the one that I've tried and it doesn't work - the set up script cannot find the attribute after it's created it.
– Paul
May 8 '17 at 7:38
Hi Konstantin Gerasimov Could you Please help to add an image in visual swatch attribute option programmatically. Please help me to do this. Thanks
– Deepak Upadhyay
Jun 18 at 13:42
|
show 1 more comment
Can anyone provide a working example for creating a visual swatch (or even a text swatch) attribute as part of a setup script.
I've tried the example on Magento 2 create custom swatch attribute programmatically but it doesn't work for me.
The issue I've ran into there is that the the attribute repository cannot find the new attribute that was created. I tried putting some cache clearing in between but no luck.
Thanks.
magento2 swatches
Can anyone provide a working example for creating a visual swatch (or even a text swatch) attribute as part of a setup script.
I've tried the example on Magento 2 create custom swatch attribute programmatically but it doesn't work for me.
The issue I've ran into there is that the the attribute repository cannot find the new attribute that was created. I tried putting some cache clearing in between but no luck.
Thanks.
magento2 swatches
magento2 swatches
edited May 9 '17 at 8:45
Rakesh Jesadiya
30.9k15 gold badges80 silver badges134 bronze badges
30.9k15 gold badges80 silver badges134 bronze badges
asked May 4 '17 at 7:19
PaulPaul
1,1321 gold badge14 silver badges26 bronze badges
1,1321 gold badge14 silver badges26 bronze badges
You can set directly it from admin.
– Suresh Chikani
May 4 '17 at 8:39
I'm looking to do this in a setup script.
– Paul
May 4 '17 at 9:01
magento.stackexchange.com/questions/133237/…
– Ankit Shah
May 8 '17 at 7:25
@AnkitShah that's the one that I've tried and it doesn't work - the set up script cannot find the attribute after it's created it.
– Paul
May 8 '17 at 7:38
Hi Konstantin Gerasimov Could you Please help to add an image in visual swatch attribute option programmatically. Please help me to do this. Thanks
– Deepak Upadhyay
Jun 18 at 13:42
|
show 1 more comment
You can set directly it from admin.
– Suresh Chikani
May 4 '17 at 8:39
I'm looking to do this in a setup script.
– Paul
May 4 '17 at 9:01
magento.stackexchange.com/questions/133237/…
– Ankit Shah
May 8 '17 at 7:25
@AnkitShah that's the one that I've tried and it doesn't work - the set up script cannot find the attribute after it's created it.
– Paul
May 8 '17 at 7:38
Hi Konstantin Gerasimov Could you Please help to add an image in visual swatch attribute option programmatically. Please help me to do this. Thanks
– Deepak Upadhyay
Jun 18 at 13:42
You can set directly it from admin.
– Suresh Chikani
May 4 '17 at 8:39
You can set directly it from admin.
– Suresh Chikani
May 4 '17 at 8:39
I'm looking to do this in a setup script.
– Paul
May 4 '17 at 9:01
I'm looking to do this in a setup script.
– Paul
May 4 '17 at 9:01
magento.stackexchange.com/questions/133237/…
– Ankit Shah
May 8 '17 at 7:25
magento.stackexchange.com/questions/133237/…
– Ankit Shah
May 8 '17 at 7:25
@AnkitShah that's the one that I've tried and it doesn't work - the set up script cannot find the attribute after it's created it.
– Paul
May 8 '17 at 7:38
@AnkitShah that's the one that I've tried and it doesn't work - the set up script cannot find the attribute after it's created it.
– Paul
May 8 '17 at 7:38
Hi Konstantin Gerasimov Could you Please help to add an image in visual swatch attribute option programmatically. Please help me to do this. Thanks
– Deepak Upadhyay
Jun 18 at 13:42
Hi Konstantin Gerasimov Could you Please help to add an image in visual swatch attribute option programmatically. Please help me to do this. Thanks
– Deepak Upadhyay
Jun 18 at 13:42
|
show 1 more comment
1 Answer
1
active
oldest
votes
Disclaimer: Parts of this code were taken from Magento_SwatchesSampleData
core module. Also you might not need colorMap
but I just put it there.
This code was tested on Magento 2.1.4.
I assume you have an extension called Goivvy_Custom
. I also assume you know how to install the extension and have magento run install scripts.
The code below will create new_swatch_attribute
Visual Swatch.
Here is Goivvy/Custom/Setup/InstallData.php
:
<?php
namespace GoivvyCustomSetup;
use MagentoFrameworkSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoCatalogModelProductType;
use MagentoCatalogModelResourceModelEavAttribute as eavAttribute;
class InstallData implements SetupInstallDataInterface
private $attrOptionCollectionFactory;
private $eavSetupFactory;
private $eavConfig;
protected $colorMap = [
'Black' => '#000000',
'Blue' => '#1857f7',
'Brown' => '#945454',
'Gray' => '#8f8f8f',
'Green' => '#53a828',
'Lavender' => '#ce64d4',
'Multi' => '#ffffff',
'Orange' => '#eb6703',
'Purple' => '#ef3dff',
'Red' => '#ff0000',
'White' => '#ffffff',
'Yellow' => '#ffd500',
];
public function __construct(EavSetupFactory $eavSetupFactory,
MagentoEavModelConfig $eavConfig,
MagentoEavModelResourceModelEntityAttributeOptionCollectionFactory $attrOptionCollectionFactory
)
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
$this->attrOptionCollectionFactory = $attrOptionCollectionFactory;
public function install(SetupModuleDataSetupInterface $setup, SetupModuleContextInterface $moduleContext)
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
if(version_compare($moduleContext->getVersion(),'1.0.0') < 0)
$eavSetup->addAttribute(
MagentoCatalogModelProduct::ENTITY,
'new_swatch_attribute',
[
'type' => 'int',
'label' => 'New Swatch Attribute',
'input' => 'select',
'required' => false,
'user_defined' => true,
'searchable' => true,
'filterable' => true,
'comparable' => true,
'visible_in_advanced_search' => true,
'apply_to' => implode(',', [Type::TYPE_SIMPLE, Type::TYPE_VIRTUAL]),
'is_used_in_grid' => true,
'is_visible_in_grid' => false,
'option' => [
'values' => [
'Black',
'Blue',
'Brown',
'Gray',
'Green',
'Lavender',
'Multi',
'Orange',
'Purple',
'Red',
'White',
'Yellow'
]
]
]
);
$this->eavConfig->clear();
$attribute = $this->eavConfig->getAttribute('catalog_product', 'new_swatch_attribute');
if (!$attribute)
return;
$attributeData['option'] = $this->addExistingOptions($attribute);
$attributeData['frontend_input'] = 'select';
$attributeData['swatch_input_type'] = 'visual';
$attributeData['update_product_preview_image'] = 1;
$attributeData['use_product_image_for_swatch'] = 0;
$attributeData['optionvisual'] = $this->getOptionSwatch($attributeData);
$attributeData['defaultvisual'] = $this->getOptionDefaultVisual($attributeData);
$attributeData['swatchvisual'] = $this->getOptionSwatchVisual($attributeData);
$attribute->addData($attributeData);
$attribute->save();
protected function getOptionSwatch(array $attributeData)
$optionSwatch = ['order' => [], 'value' => [], 'delete' => []];
$i = 0;
foreach ($attributeData['option'] as $optionKey => $optionValue)
$optionSwatch['delete'][$optionKey] = '';
$optionSwatch['order'][$optionKey] = (string)$i++;
$optionSwatch['value'][$optionKey] = [$optionValue, ''];
return $optionSwatch;
private function getOptionSwatchVisual(array $attributeData)
$optionSwatch = ['value' => []];
foreach ($attributeData['option'] as $optionKey => $optionValue)
if (substr($optionValue, 0, 1) == '#' && strlen($optionValue) == 7)
$optionSwatch['value'][$optionKey] = $optionValue;
else if ($this->colorMap[$optionValue])
$optionSwatch['value'][$optionKey] = $this->colorMap[$optionValue];
else
$optionSwatch['value'][$optionKey] = $this->colorMap['White'];
return $optionSwatch;
private function getOptionDefaultVisual(array $attributeData)
$optionSwatch = $this->getOptionSwatchVisual($attributeData);
if(isset(array_keys($optionSwatch['value'])[0]))
return [array_keys($optionSwatch['value'])[0]];
else
return [''];
private function addExistingOptions(eavAttribute $attribute)
$options = [];
$attributeId = $attribute->getId();
if ($attributeId)
$this->loadOptionCollection($attributeId);
foreach ($this->optionCollection[$attributeId] as $option)
$options[$option->getId()] = $option->getValue();
return $options;
private function loadOptionCollection($attributeId)
if (empty($this->optionCollection[$attributeId]))
$this->optionCollection[$attributeId] = $this->attrOptionCollectionFactory->create()
->setAttributeFilter($attributeId)
->setPositionOrder('asc', true)
->load();
Here is how it looks in Magento 2.1.4:
Any questions - let me know.
Thank you, that works! I had to include an EAV cache clean after the attribute was created. I've propose a couple of edits just to make it clearer for anyone else who needs it. Thanks again.
– Paul
May 9 '17 at 9:17
you are very welcome!
– Konstantin Gerasimov
May 9 '17 at 13:41
Can you please help me i have to add options from CSV with visual swatch value. I have to import attribute option with visual swatch and swatch value is colorcode. I am following this link for upload attribute options it's working but not getting solution to add visual swatch value. Please help me. pearlbells.co.uk/…
– Magecode
Dec 6 '17 at 12:33
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f172964%2fcreate-visual-swatch-attribute%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Disclaimer: Parts of this code were taken from Magento_SwatchesSampleData
core module. Also you might not need colorMap
but I just put it there.
This code was tested on Magento 2.1.4.
I assume you have an extension called Goivvy_Custom
. I also assume you know how to install the extension and have magento run install scripts.
The code below will create new_swatch_attribute
Visual Swatch.
Here is Goivvy/Custom/Setup/InstallData.php
:
<?php
namespace GoivvyCustomSetup;
use MagentoFrameworkSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoCatalogModelProductType;
use MagentoCatalogModelResourceModelEavAttribute as eavAttribute;
class InstallData implements SetupInstallDataInterface
private $attrOptionCollectionFactory;
private $eavSetupFactory;
private $eavConfig;
protected $colorMap = [
'Black' => '#000000',
'Blue' => '#1857f7',
'Brown' => '#945454',
'Gray' => '#8f8f8f',
'Green' => '#53a828',
'Lavender' => '#ce64d4',
'Multi' => '#ffffff',
'Orange' => '#eb6703',
'Purple' => '#ef3dff',
'Red' => '#ff0000',
'White' => '#ffffff',
'Yellow' => '#ffd500',
];
public function __construct(EavSetupFactory $eavSetupFactory,
MagentoEavModelConfig $eavConfig,
MagentoEavModelResourceModelEntityAttributeOptionCollectionFactory $attrOptionCollectionFactory
)
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
$this->attrOptionCollectionFactory = $attrOptionCollectionFactory;
public function install(SetupModuleDataSetupInterface $setup, SetupModuleContextInterface $moduleContext)
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
if(version_compare($moduleContext->getVersion(),'1.0.0') < 0)
$eavSetup->addAttribute(
MagentoCatalogModelProduct::ENTITY,
'new_swatch_attribute',
[
'type' => 'int',
'label' => 'New Swatch Attribute',
'input' => 'select',
'required' => false,
'user_defined' => true,
'searchable' => true,
'filterable' => true,
'comparable' => true,
'visible_in_advanced_search' => true,
'apply_to' => implode(',', [Type::TYPE_SIMPLE, Type::TYPE_VIRTUAL]),
'is_used_in_grid' => true,
'is_visible_in_grid' => false,
'option' => [
'values' => [
'Black',
'Blue',
'Brown',
'Gray',
'Green',
'Lavender',
'Multi',
'Orange',
'Purple',
'Red',
'White',
'Yellow'
]
]
]
);
$this->eavConfig->clear();
$attribute = $this->eavConfig->getAttribute('catalog_product', 'new_swatch_attribute');
if (!$attribute)
return;
$attributeData['option'] = $this->addExistingOptions($attribute);
$attributeData['frontend_input'] = 'select';
$attributeData['swatch_input_type'] = 'visual';
$attributeData['update_product_preview_image'] = 1;
$attributeData['use_product_image_for_swatch'] = 0;
$attributeData['optionvisual'] = $this->getOptionSwatch($attributeData);
$attributeData['defaultvisual'] = $this->getOptionDefaultVisual($attributeData);
$attributeData['swatchvisual'] = $this->getOptionSwatchVisual($attributeData);
$attribute->addData($attributeData);
$attribute->save();
protected function getOptionSwatch(array $attributeData)
$optionSwatch = ['order' => [], 'value' => [], 'delete' => []];
$i = 0;
foreach ($attributeData['option'] as $optionKey => $optionValue)
$optionSwatch['delete'][$optionKey] = '';
$optionSwatch['order'][$optionKey] = (string)$i++;
$optionSwatch['value'][$optionKey] = [$optionValue, ''];
return $optionSwatch;
private function getOptionSwatchVisual(array $attributeData)
$optionSwatch = ['value' => []];
foreach ($attributeData['option'] as $optionKey => $optionValue)
if (substr($optionValue, 0, 1) == '#' && strlen($optionValue) == 7)
$optionSwatch['value'][$optionKey] = $optionValue;
else if ($this->colorMap[$optionValue])
$optionSwatch['value'][$optionKey] = $this->colorMap[$optionValue];
else
$optionSwatch['value'][$optionKey] = $this->colorMap['White'];
return $optionSwatch;
private function getOptionDefaultVisual(array $attributeData)
$optionSwatch = $this->getOptionSwatchVisual($attributeData);
if(isset(array_keys($optionSwatch['value'])[0]))
return [array_keys($optionSwatch['value'])[0]];
else
return [''];
private function addExistingOptions(eavAttribute $attribute)
$options = [];
$attributeId = $attribute->getId();
if ($attributeId)
$this->loadOptionCollection($attributeId);
foreach ($this->optionCollection[$attributeId] as $option)
$options[$option->getId()] = $option->getValue();
return $options;
private function loadOptionCollection($attributeId)
if (empty($this->optionCollection[$attributeId]))
$this->optionCollection[$attributeId] = $this->attrOptionCollectionFactory->create()
->setAttributeFilter($attributeId)
->setPositionOrder('asc', true)
->load();
Here is how it looks in Magento 2.1.4:
Any questions - let me know.
Thank you, that works! I had to include an EAV cache clean after the attribute was created. I've propose a couple of edits just to make it clearer for anyone else who needs it. Thanks again.
– Paul
May 9 '17 at 9:17
you are very welcome!
– Konstantin Gerasimov
May 9 '17 at 13:41
Can you please help me i have to add options from CSV with visual swatch value. I have to import attribute option with visual swatch and swatch value is colorcode. I am following this link for upload attribute options it's working but not getting solution to add visual swatch value. Please help me. pearlbells.co.uk/…
– Magecode
Dec 6 '17 at 12:33
add a comment |
Disclaimer: Parts of this code were taken from Magento_SwatchesSampleData
core module. Also you might not need colorMap
but I just put it there.
This code was tested on Magento 2.1.4.
I assume you have an extension called Goivvy_Custom
. I also assume you know how to install the extension and have magento run install scripts.
The code below will create new_swatch_attribute
Visual Swatch.
Here is Goivvy/Custom/Setup/InstallData.php
:
<?php
namespace GoivvyCustomSetup;
use MagentoFrameworkSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoCatalogModelProductType;
use MagentoCatalogModelResourceModelEavAttribute as eavAttribute;
class InstallData implements SetupInstallDataInterface
private $attrOptionCollectionFactory;
private $eavSetupFactory;
private $eavConfig;
protected $colorMap = [
'Black' => '#000000',
'Blue' => '#1857f7',
'Brown' => '#945454',
'Gray' => '#8f8f8f',
'Green' => '#53a828',
'Lavender' => '#ce64d4',
'Multi' => '#ffffff',
'Orange' => '#eb6703',
'Purple' => '#ef3dff',
'Red' => '#ff0000',
'White' => '#ffffff',
'Yellow' => '#ffd500',
];
public function __construct(EavSetupFactory $eavSetupFactory,
MagentoEavModelConfig $eavConfig,
MagentoEavModelResourceModelEntityAttributeOptionCollectionFactory $attrOptionCollectionFactory
)
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
$this->attrOptionCollectionFactory = $attrOptionCollectionFactory;
public function install(SetupModuleDataSetupInterface $setup, SetupModuleContextInterface $moduleContext)
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
if(version_compare($moduleContext->getVersion(),'1.0.0') < 0)
$eavSetup->addAttribute(
MagentoCatalogModelProduct::ENTITY,
'new_swatch_attribute',
[
'type' => 'int',
'label' => 'New Swatch Attribute',
'input' => 'select',
'required' => false,
'user_defined' => true,
'searchable' => true,
'filterable' => true,
'comparable' => true,
'visible_in_advanced_search' => true,
'apply_to' => implode(',', [Type::TYPE_SIMPLE, Type::TYPE_VIRTUAL]),
'is_used_in_grid' => true,
'is_visible_in_grid' => false,
'option' => [
'values' => [
'Black',
'Blue',
'Brown',
'Gray',
'Green',
'Lavender',
'Multi',
'Orange',
'Purple',
'Red',
'White',
'Yellow'
]
]
]
);
$this->eavConfig->clear();
$attribute = $this->eavConfig->getAttribute('catalog_product', 'new_swatch_attribute');
if (!$attribute)
return;
$attributeData['option'] = $this->addExistingOptions($attribute);
$attributeData['frontend_input'] = 'select';
$attributeData['swatch_input_type'] = 'visual';
$attributeData['update_product_preview_image'] = 1;
$attributeData['use_product_image_for_swatch'] = 0;
$attributeData['optionvisual'] = $this->getOptionSwatch($attributeData);
$attributeData['defaultvisual'] = $this->getOptionDefaultVisual($attributeData);
$attributeData['swatchvisual'] = $this->getOptionSwatchVisual($attributeData);
$attribute->addData($attributeData);
$attribute->save();
protected function getOptionSwatch(array $attributeData)
$optionSwatch = ['order' => [], 'value' => [], 'delete' => []];
$i = 0;
foreach ($attributeData['option'] as $optionKey => $optionValue)
$optionSwatch['delete'][$optionKey] = '';
$optionSwatch['order'][$optionKey] = (string)$i++;
$optionSwatch['value'][$optionKey] = [$optionValue, ''];
return $optionSwatch;
private function getOptionSwatchVisual(array $attributeData)
$optionSwatch = ['value' => []];
foreach ($attributeData['option'] as $optionKey => $optionValue)
if (substr($optionValue, 0, 1) == '#' && strlen($optionValue) == 7)
$optionSwatch['value'][$optionKey] = $optionValue;
else if ($this->colorMap[$optionValue])
$optionSwatch['value'][$optionKey] = $this->colorMap[$optionValue];
else
$optionSwatch['value'][$optionKey] = $this->colorMap['White'];
return $optionSwatch;
private function getOptionDefaultVisual(array $attributeData)
$optionSwatch = $this->getOptionSwatchVisual($attributeData);
if(isset(array_keys($optionSwatch['value'])[0]))
return [array_keys($optionSwatch['value'])[0]];
else
return [''];
private function addExistingOptions(eavAttribute $attribute)
$options = [];
$attributeId = $attribute->getId();
if ($attributeId)
$this->loadOptionCollection($attributeId);
foreach ($this->optionCollection[$attributeId] as $option)
$options[$option->getId()] = $option->getValue();
return $options;
private function loadOptionCollection($attributeId)
if (empty($this->optionCollection[$attributeId]))
$this->optionCollection[$attributeId] = $this->attrOptionCollectionFactory->create()
->setAttributeFilter($attributeId)
->setPositionOrder('asc', true)
->load();
Here is how it looks in Magento 2.1.4:
Any questions - let me know.
Thank you, that works! I had to include an EAV cache clean after the attribute was created. I've propose a couple of edits just to make it clearer for anyone else who needs it. Thanks again.
– Paul
May 9 '17 at 9:17
you are very welcome!
– Konstantin Gerasimov
May 9 '17 at 13:41
Can you please help me i have to add options from CSV with visual swatch value. I have to import attribute option with visual swatch and swatch value is colorcode. I am following this link for upload attribute options it's working but not getting solution to add visual swatch value. Please help me. pearlbells.co.uk/…
– Magecode
Dec 6 '17 at 12:33
add a comment |
Disclaimer: Parts of this code were taken from Magento_SwatchesSampleData
core module. Also you might not need colorMap
but I just put it there.
This code was tested on Magento 2.1.4.
I assume you have an extension called Goivvy_Custom
. I also assume you know how to install the extension and have magento run install scripts.
The code below will create new_swatch_attribute
Visual Swatch.
Here is Goivvy/Custom/Setup/InstallData.php
:
<?php
namespace GoivvyCustomSetup;
use MagentoFrameworkSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoCatalogModelProductType;
use MagentoCatalogModelResourceModelEavAttribute as eavAttribute;
class InstallData implements SetupInstallDataInterface
private $attrOptionCollectionFactory;
private $eavSetupFactory;
private $eavConfig;
protected $colorMap = [
'Black' => '#000000',
'Blue' => '#1857f7',
'Brown' => '#945454',
'Gray' => '#8f8f8f',
'Green' => '#53a828',
'Lavender' => '#ce64d4',
'Multi' => '#ffffff',
'Orange' => '#eb6703',
'Purple' => '#ef3dff',
'Red' => '#ff0000',
'White' => '#ffffff',
'Yellow' => '#ffd500',
];
public function __construct(EavSetupFactory $eavSetupFactory,
MagentoEavModelConfig $eavConfig,
MagentoEavModelResourceModelEntityAttributeOptionCollectionFactory $attrOptionCollectionFactory
)
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
$this->attrOptionCollectionFactory = $attrOptionCollectionFactory;
public function install(SetupModuleDataSetupInterface $setup, SetupModuleContextInterface $moduleContext)
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
if(version_compare($moduleContext->getVersion(),'1.0.0') < 0)
$eavSetup->addAttribute(
MagentoCatalogModelProduct::ENTITY,
'new_swatch_attribute',
[
'type' => 'int',
'label' => 'New Swatch Attribute',
'input' => 'select',
'required' => false,
'user_defined' => true,
'searchable' => true,
'filterable' => true,
'comparable' => true,
'visible_in_advanced_search' => true,
'apply_to' => implode(',', [Type::TYPE_SIMPLE, Type::TYPE_VIRTUAL]),
'is_used_in_grid' => true,
'is_visible_in_grid' => false,
'option' => [
'values' => [
'Black',
'Blue',
'Brown',
'Gray',
'Green',
'Lavender',
'Multi',
'Orange',
'Purple',
'Red',
'White',
'Yellow'
]
]
]
);
$this->eavConfig->clear();
$attribute = $this->eavConfig->getAttribute('catalog_product', 'new_swatch_attribute');
if (!$attribute)
return;
$attributeData['option'] = $this->addExistingOptions($attribute);
$attributeData['frontend_input'] = 'select';
$attributeData['swatch_input_type'] = 'visual';
$attributeData['update_product_preview_image'] = 1;
$attributeData['use_product_image_for_swatch'] = 0;
$attributeData['optionvisual'] = $this->getOptionSwatch($attributeData);
$attributeData['defaultvisual'] = $this->getOptionDefaultVisual($attributeData);
$attributeData['swatchvisual'] = $this->getOptionSwatchVisual($attributeData);
$attribute->addData($attributeData);
$attribute->save();
protected function getOptionSwatch(array $attributeData)
$optionSwatch = ['order' => [], 'value' => [], 'delete' => []];
$i = 0;
foreach ($attributeData['option'] as $optionKey => $optionValue)
$optionSwatch['delete'][$optionKey] = '';
$optionSwatch['order'][$optionKey] = (string)$i++;
$optionSwatch['value'][$optionKey] = [$optionValue, ''];
return $optionSwatch;
private function getOptionSwatchVisual(array $attributeData)
$optionSwatch = ['value' => []];
foreach ($attributeData['option'] as $optionKey => $optionValue)
if (substr($optionValue, 0, 1) == '#' && strlen($optionValue) == 7)
$optionSwatch['value'][$optionKey] = $optionValue;
else if ($this->colorMap[$optionValue])
$optionSwatch['value'][$optionKey] = $this->colorMap[$optionValue];
else
$optionSwatch['value'][$optionKey] = $this->colorMap['White'];
return $optionSwatch;
private function getOptionDefaultVisual(array $attributeData)
$optionSwatch = $this->getOptionSwatchVisual($attributeData);
if(isset(array_keys($optionSwatch['value'])[0]))
return [array_keys($optionSwatch['value'])[0]];
else
return [''];
private function addExistingOptions(eavAttribute $attribute)
$options = [];
$attributeId = $attribute->getId();
if ($attributeId)
$this->loadOptionCollection($attributeId);
foreach ($this->optionCollection[$attributeId] as $option)
$options[$option->getId()] = $option->getValue();
return $options;
private function loadOptionCollection($attributeId)
if (empty($this->optionCollection[$attributeId]))
$this->optionCollection[$attributeId] = $this->attrOptionCollectionFactory->create()
->setAttributeFilter($attributeId)
->setPositionOrder('asc', true)
->load();
Here is how it looks in Magento 2.1.4:
Any questions - let me know.
Disclaimer: Parts of this code were taken from Magento_SwatchesSampleData
core module. Also you might not need colorMap
but I just put it there.
This code was tested on Magento 2.1.4.
I assume you have an extension called Goivvy_Custom
. I also assume you know how to install the extension and have magento run install scripts.
The code below will create new_swatch_attribute
Visual Swatch.
Here is Goivvy/Custom/Setup/InstallData.php
:
<?php
namespace GoivvyCustomSetup;
use MagentoFrameworkSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoCatalogModelProductType;
use MagentoCatalogModelResourceModelEavAttribute as eavAttribute;
class InstallData implements SetupInstallDataInterface
private $attrOptionCollectionFactory;
private $eavSetupFactory;
private $eavConfig;
protected $colorMap = [
'Black' => '#000000',
'Blue' => '#1857f7',
'Brown' => '#945454',
'Gray' => '#8f8f8f',
'Green' => '#53a828',
'Lavender' => '#ce64d4',
'Multi' => '#ffffff',
'Orange' => '#eb6703',
'Purple' => '#ef3dff',
'Red' => '#ff0000',
'White' => '#ffffff',
'Yellow' => '#ffd500',
];
public function __construct(EavSetupFactory $eavSetupFactory,
MagentoEavModelConfig $eavConfig,
MagentoEavModelResourceModelEntityAttributeOptionCollectionFactory $attrOptionCollectionFactory
)
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
$this->attrOptionCollectionFactory = $attrOptionCollectionFactory;
public function install(SetupModuleDataSetupInterface $setup, SetupModuleContextInterface $moduleContext)
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
if(version_compare($moduleContext->getVersion(),'1.0.0') < 0)
$eavSetup->addAttribute(
MagentoCatalogModelProduct::ENTITY,
'new_swatch_attribute',
[
'type' => 'int',
'label' => 'New Swatch Attribute',
'input' => 'select',
'required' => false,
'user_defined' => true,
'searchable' => true,
'filterable' => true,
'comparable' => true,
'visible_in_advanced_search' => true,
'apply_to' => implode(',', [Type::TYPE_SIMPLE, Type::TYPE_VIRTUAL]),
'is_used_in_grid' => true,
'is_visible_in_grid' => false,
'option' => [
'values' => [
'Black',
'Blue',
'Brown',
'Gray',
'Green',
'Lavender',
'Multi',
'Orange',
'Purple',
'Red',
'White',
'Yellow'
]
]
]
);
$this->eavConfig->clear();
$attribute = $this->eavConfig->getAttribute('catalog_product', 'new_swatch_attribute');
if (!$attribute)
return;
$attributeData['option'] = $this->addExistingOptions($attribute);
$attributeData['frontend_input'] = 'select';
$attributeData['swatch_input_type'] = 'visual';
$attributeData['update_product_preview_image'] = 1;
$attributeData['use_product_image_for_swatch'] = 0;
$attributeData['optionvisual'] = $this->getOptionSwatch($attributeData);
$attributeData['defaultvisual'] = $this->getOptionDefaultVisual($attributeData);
$attributeData['swatchvisual'] = $this->getOptionSwatchVisual($attributeData);
$attribute->addData($attributeData);
$attribute->save();
protected function getOptionSwatch(array $attributeData)
$optionSwatch = ['order' => [], 'value' => [], 'delete' => []];
$i = 0;
foreach ($attributeData['option'] as $optionKey => $optionValue)
$optionSwatch['delete'][$optionKey] = '';
$optionSwatch['order'][$optionKey] = (string)$i++;
$optionSwatch['value'][$optionKey] = [$optionValue, ''];
return $optionSwatch;
private function getOptionSwatchVisual(array $attributeData)
$optionSwatch = ['value' => []];
foreach ($attributeData['option'] as $optionKey => $optionValue)
if (substr($optionValue, 0, 1) == '#' && strlen($optionValue) == 7)
$optionSwatch['value'][$optionKey] = $optionValue;
else if ($this->colorMap[$optionValue])
$optionSwatch['value'][$optionKey] = $this->colorMap[$optionValue];
else
$optionSwatch['value'][$optionKey] = $this->colorMap['White'];
return $optionSwatch;
private function getOptionDefaultVisual(array $attributeData)
$optionSwatch = $this->getOptionSwatchVisual($attributeData);
if(isset(array_keys($optionSwatch['value'])[0]))
return [array_keys($optionSwatch['value'])[0]];
else
return [''];
private function addExistingOptions(eavAttribute $attribute)
$options = [];
$attributeId = $attribute->getId();
if ($attributeId)
$this->loadOptionCollection($attributeId);
foreach ($this->optionCollection[$attributeId] as $option)
$options[$option->getId()] = $option->getValue();
return $options;
private function loadOptionCollection($attributeId)
if (empty($this->optionCollection[$attributeId]))
$this->optionCollection[$attributeId] = $this->attrOptionCollectionFactory->create()
->setAttributeFilter($attributeId)
->setPositionOrder('asc', true)
->load();
Here is how it looks in Magento 2.1.4:
Any questions - let me know.
edited May 9 '17 at 9:35
Paul
1,1321 gold badge14 silver badges26 bronze badges
1,1321 gold badge14 silver badges26 bronze badges
answered May 9 '17 at 0:41
Konstantin GerasimovKonstantin Gerasimov
3,38610 silver badges30 bronze badges
3,38610 silver badges30 bronze badges
Thank you, that works! I had to include an EAV cache clean after the attribute was created. I've propose a couple of edits just to make it clearer for anyone else who needs it. Thanks again.
– Paul
May 9 '17 at 9:17
you are very welcome!
– Konstantin Gerasimov
May 9 '17 at 13:41
Can you please help me i have to add options from CSV with visual swatch value. I have to import attribute option with visual swatch and swatch value is colorcode. I am following this link for upload attribute options it's working but not getting solution to add visual swatch value. Please help me. pearlbells.co.uk/…
– Magecode
Dec 6 '17 at 12:33
add a comment |
Thank you, that works! I had to include an EAV cache clean after the attribute was created. I've propose a couple of edits just to make it clearer for anyone else who needs it. Thanks again.
– Paul
May 9 '17 at 9:17
you are very welcome!
– Konstantin Gerasimov
May 9 '17 at 13:41
Can you please help me i have to add options from CSV with visual swatch value. I have to import attribute option with visual swatch and swatch value is colorcode. I am following this link for upload attribute options it's working but not getting solution to add visual swatch value. Please help me. pearlbells.co.uk/…
– Magecode
Dec 6 '17 at 12:33
Thank you, that works! I had to include an EAV cache clean after the attribute was created. I've propose a couple of edits just to make it clearer for anyone else who needs it. Thanks again.
– Paul
May 9 '17 at 9:17
Thank you, that works! I had to include an EAV cache clean after the attribute was created. I've propose a couple of edits just to make it clearer for anyone else who needs it. Thanks again.
– Paul
May 9 '17 at 9:17
you are very welcome!
– Konstantin Gerasimov
May 9 '17 at 13:41
you are very welcome!
– Konstantin Gerasimov
May 9 '17 at 13:41
Can you please help me i have to add options from CSV with visual swatch value. I have to import attribute option with visual swatch and swatch value is colorcode. I am following this link for upload attribute options it's working but not getting solution to add visual swatch value. Please help me. pearlbells.co.uk/…
– Magecode
Dec 6 '17 at 12:33
Can you please help me i have to add options from CSV with visual swatch value. I have to import attribute option with visual swatch and swatch value is colorcode. I am following this link for upload attribute options it's working but not getting solution to add visual swatch value. Please help me. pearlbells.co.uk/…
– Magecode
Dec 6 '17 at 12:33
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f172964%2fcreate-visual-swatch-attribute%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You can set directly it from admin.
– Suresh Chikani
May 4 '17 at 8:39
I'm looking to do this in a setup script.
– Paul
May 4 '17 at 9:01
magento.stackexchange.com/questions/133237/…
– Ankit Shah
May 8 '17 at 7:25
@AnkitShah that's the one that I've tried and it doesn't work - the set up script cannot find the attribute after it's created it.
– Paul
May 8 '17 at 7:38
Hi Konstantin Gerasimov Could you Please help to add an image in visual swatch attribute option programmatically. Please help me to do this. Thanks
– Deepak Upadhyay
Jun 18 at 13:42