Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
attribute_with_option.php
Go to the documentation of this file.
1 <?php
7 /* Create attribute */
10  \Magento\Catalog\Setup\CategorySetup::class
11 );
14  \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
15 );
16 $attribute->setData(
17  [
18  'attribute_code' => 'attribute_with_option',
19  'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
20  'is_global' => 1,
21  'frontend_input' => 'select',
22  'is_filterable' => 1,
23  'option' => ['value' => ['option_0' => [0 => 'Option Label']]],
24  'backend_type' => 'int',
25  ]
26 );
27 $attribute->save();
28 
29 /* Assign attribute to attribute set */
30 $installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId());
31 
32 /* Create simple products per each option */
35  \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class
36 );
37 $options->setAttributeFilter($attribute->getId());
38 
39 foreach ($options as $option) {
42  \Magento\Catalog\Model\Product::class
43  );
44  $product->setTypeId(
45  \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE
46  )->setAttributeSetId(
47  $installer->getAttributeSetId('catalog_product', 'Default')
48  )->setWebsiteIds(
49  [1]
50  )->setName(
51  'Simple Product ' . $option->getId()
52  )->setSku(
53  'simple_product_' . $option->getId()
54  )->setPrice(
55  10
56  )->setCategoryIds(
57  [2]
58  )->setVisibility(
59  \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH
60  )->setStatus(
61  \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
62  )->setStockData(
63  ['use_config_manage_stock' => 1, 'qty' => 5, 'is_in_stock' => 1]
64  )->save();
65 
67  \Magento\Catalog\Model\Product\Action::class
68  )->updateAttributes(
69  [$product->getId()],
70  [$attribute->getAttributeCode() => $option->getId()],
71  $product->getStoreId()
72  );
73 }