Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
configurable_product.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
8 require __DIR__ . '/../../ConfigurableProduct/_files/configurable_attribute.php';
9 require __DIR__ . '/simple_products.php';
10 
12 
13 $storeManager = $objectManager->get(\Magento\Store\Model\StoreManager::class);
14 $store = $storeManager->getStore('default');
15 $productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
16 
17 $installer = $objectManager->get(\Magento\Catalog\Setup\CategorySetup::class);
18 $attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');
21 
22 $attributeRepository = $objectManager->get(\Magento\Eav\Api\AttributeRepositoryInterface::class);
23 $attribute = $attributeRepository->get('catalog_product', 'test_configurable');
24 $options = $attribute->getOptions();
25 array_shift($options); //remove the first option which is empty
26 foreach (['simple1', 'simple2'] as $sku) {
27  $option = array_shift($options);
28  $product = $productRepository->get($sku);
29  $product->setTestConfigurable($option->getValue());
31  $attributeValues[] = [
32  'label' => 'test',
33  'attribute_id' => $attribute->getId(),
34  'value_index' => $option->getValue(),
35  ];
36  $associatedProductIds[] = $product->getId();
37 }
38 
39 $product = $objectManager->create(\Magento\Catalog\Model\Product::class)
40  ->setTypeId('configurable')
41  ->setId(666)
42  ->setAttributeSetId($attributeSetId)
43  ->setWebsiteIds([1])
44  ->setName('Configurable Product')
45  ->setSku('configurable')
46  ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
47  ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
48  ->setStockData([
49  'use_config_manage_stock' => 1,
50  'qty' => 100,
51  'is_qty_decimal' => 0,
52  'is_in_stock' => 1,
53  ]);
55  [
56  'attribute_id' => $attribute->getId(),
57  'code' => $attribute->getAttributeCode(),
58  'label' => $attribute->getStoreLabel(),
59  'position' => '0',
60  'values' => $attributeValues,
61  ],
62 ];
63 $optionsFactory = $objectManager->get(\Magento\ConfigurableProduct\Helper\Product\Options\Factory::class);
65 $extensionConfigurableAttributes = $product->getExtensionAttributes();
66 $extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
67 $extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
68 $product->setExtensionAttributes($extensionConfigurableAttributes);
$configurableAttributesData
$extensionConfigurableAttributes
defined('TESTS_BP')||define('TESTS_BP' __DIR__
Definition: _bootstrap.php:60
$productRepository
foreach(['simple1', 'simple2'] as $sku) $product
$associatedProductIds
$attributeRepository
$configurableOptions