Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CreateOptions.php
Go to the documentation of this file.
1 <?php
8 
9 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
11 use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;
12 
13 class CreateOptions extends Action implements HttpPostActionInterface
14 {
20  const ADMIN_RESOURCE = 'Magento_Catalog::products';
21 
25  protected $jsonHelper;
26 
30  protected $attributeFactory;
31 
37  public function __construct(
38  Action\Context $context,
39  \Magento\Framework\Json\Helper\Data $jsonHelper,
40  AttributeFactory $attributeFactory
41  ) {
42  $this->jsonHelper = $jsonHelper;
43  $this->attributeFactory = $attributeFactory;
44  parent::__construct($context);
45  }
46 
52  public function execute()
53  {
54  $this->getResponse()->representJson($this->jsonHelper->jsonEncode($this->saveAttributeOptions()));
55  }
56 
66  protected function saveAttributeOptions()
67  {
68  $options = (array)$this->getRequest()->getParam('options');
69  $savedOptions = [];
70  foreach ($options as $option) {
71  if (isset($option['label']) && isset($option['is_new'])) {
72  $attribute = $this->attributeFactory->create();
73  $attribute->load($option['attribute_id']);
74  $optionsBefore = $attribute->getSource()->getAllOptions(false);
75  $attribute->setOption(
76  [
77  'value' => ['option_0' => [$option['label']]],
78  'order' => ['option_0' => count($optionsBefore) + 1],
79  ]
80  );
81  $attribute->save();
82  $attribute = $this->attributeFactory->create();
83  $attribute->load($option['attribute_id']);
84  $optionsAfter = $attribute->getSource()->getAllOptions(false);
85  $newOption = array_pop($optionsAfter);
86  $savedOptions[$option['id']] = $newOption['value'];
87  }
88  }
89  return $savedOptions;
90  }
91 }
__construct(Action\Context $context, \Magento\Framework\Json\Helper\Data $jsonHelper, AttributeFactory $attributeFactory)