Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
product_with_dropdown_option.php
Go to the documentation of this file.
1 <?php
9 
10 $objectManager->removeSharedInstance(\Magento\Catalog\Model\ProductRepository::class);
11 $objectManager->removeSharedInstance(\Magento\Catalog\Model\Product\Option\Repository::class);
12 $objectManager->removeSharedInstance(\Magento\Catalog\Model\Product\Option\SaveHandler::class);
13 
14 $productRepository = $objectManager->get(\Magento\Catalog\Model\ProductRepository::class);
15 
17 $product = $objectManager->create(\Magento\Catalog\Model\Product::class);
18 
19 $product->setTypeId(
20  'simple'
21 )->setAttributeSetId(
22  4
23 )->setWebsiteIds(
24  [1]
25 )->setName(
26  'Simple Product With Custom Options'
27 )->setSku(
28  'simple_dropdown_option'
29 )->setPrice(
30  200
31 )->setMetaTitle(
32  'meta title'
33 )->setMetaKeyword(
34  'meta keyword'
35 )->setMetaDescription(
36  'meta description'
37 )->setVisibility(
38  \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH
39 )->setStatus(
40  \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
41 )->setCanSaveCustomOptions(
42  true
43 )->setStockData(
44  [
45  'qty' => 0,
46  'is_in_stock' => 0,
47  'manage_stock' => 1,
48  ]
49 );
50 
52  [
53  'title' => 'drop_down option',
54  'type' => 'drop_down',
55  'is_require' => true,
56  'sort_order' => 4,
57  'values' => [
58  [
59  'title' => 'drop_down option 1',
60  'price' => 10,
61  'price_type' => 'fixed',
62  'sku' => 'drop_down option 1 sku',
63  'sort_order' => 1,
64  ],
65  [
66  'title' => 'drop_down option 2',
67  'price' => 20,
68  'price_type' => 'percent',
69  'sku' => 'drop_down option 2 sku',
70  'sort_order' => 2,
71  ],
72  ],
73  ]
74 ];
75 
77 
79 $customOptionFactory = $objectManager->create(\Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory::class);
81  \Magento\Catalog\Api\Data\ProductCustomOptionValuesInterfaceFactory::class
82 );
83 
84 foreach ($options as $option) {
86  $customOption = $customOptionFactory->create(['data' => $option]);
87  $customOption->setProductSku($product->getSku());
88  if (isset($option['values'])) {
89  $values = [];
90  foreach ($option['values'] as $value) {
91  $value = $optionValueFactory->create(['data' => $value]);
92  $values[] = $value;
93  }
94  $customOption->setValues($values);
95  }
97 }
98 
99 $product->setOptions($customOptions);
100 $product->save();
$customOption
Definition: products.php:73
$values
Definition: options.phtml:88
$value
Definition: gender.phtml:16