Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
swatch_attribute.php
Go to the documentation of this file.
1 <?php
7 
10 
11 $data = [
12  'is_required' => 1,
13  'is_visible_on_front' => 1,
14  'is_visible_in_advanced_search' => 0,
15  'attribute_code' => 'color_swatch',
16  'backend_type' => '',
17  'is_searchable' => 0,
18  'is_filterable' => 0,
19  'is_filterable_in_search' => 0,
20  'frontend_label' => 'Attribute ',
21  'entity_type_id' => 4
22 ];
24 
25 $data['frontend_input'] = 'swatch_visual';
26 $data['swatch_input_type'] = 'visual';
27 $data['swatchvisual']['value'] = array_reduce(
28  range(1, $optionsPerAttribute),
29  function ($values, $index) use ($optionsPerAttribute) {
30  $values['option_' . $index] = '#'
31  . str_repeat(
32  dechex(255 * $index / $optionsPerAttribute),
33  3
34  );
35  return $values;
36  },
37  []
38 );
39 $data['optionvisual']['value'] = array_reduce(
40  range(1, $optionsPerAttribute),
41  function ($values, $index) use ($optionsPerAttribute) {
42  $values['option_' . $index] = ['option ' . $index];
43  return $values;
44  },
45  []
46 );
47 
48 $data['options']['option'] = array_reduce(
49  range(1, $optionsPerAttribute),
50  function ($values, $index) use ($optionsPerAttribute) {
51  $values[] = [
52  'label' => 'option ' . $index,
53  'value' => 'option_' . $index,
54  ];
55  return $values;
56  },
57  []
58 );
59 
60 $options = [];
61 foreach ($data['options']['option'] as $optionData) {
62  $options[] = $objectManager->get(AttributeOptionInterface::class)
63  ->setLabel($optionData['label'])
64  ->setValue($optionData['value']);
65 }
66 
68  \Magento\Catalog\Api\Data\ProductAttributeInterface::class,
69  ['data' => $data]
70 );
71 $attribute->setOptions($options);
72 $attribute->save();
$optionData
$values
Definition: options.phtml:88
$optionsPerAttribute
$objectManager
$index
Definition: list.phtml:44
foreach($data['options']['option'] as $optionData) $attribute