Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace VendorAddallControllerIndex;
- use MagentoFrameworkAppActionContext;
- class Add extends MagentoFrameworkAppActionAction{
- protected $resultJsonFactory;
- protected $request;
- protected $form_key;
- protected $cart;
- protected $product;
- protected $message_manager;
- public function __construct(Context$context,MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,MagentoFrameworkAppRequestInterface $request,MagentoFrameworkDataFormFormKey $form_key,MagentoCheckoutModelCart $cart,MagentoCatalogModelProduct $product,MagentoFrameworkMessageManagerInterface $message_manager) {
- $this->request=$request;
- $this->resultJsonFactory=$resultJsonFactory;
- $this->form_key = $form_key;
- $this->cart = $cart;
- $this->product = $product;
- $this->message_manager = $message_manager;
- parent::__construct($context);
- }
- public function execute() {
- $result = $this->resultJsonFactory->create();
- $childs_product_arr=json_decode($this->request->getParam('childs_product_arr'));
- $parent_product=json_decode($this->request->getParam('parent_product_id'));
- $parent_product=$parent_product[0];
- try {
- $params = [];
- foreach ($childs_product_arr as $child_product){
- $options = [];
- $_product = $this->product->load($parent_product);
- $child_product=(array)$child_product;
- $param = array(
- 'form_key' => $this->form_key->getFormKey(),
- 'super_attribute' => $options,
- 'qty' => 1,
- 'selected_configurable_option' => $child_product['simple_product_id'],
- );
- $this->cart->addProduct($_product->getId(), $param);
- }
- $this->cart->save();
- $msg="You added {$_product->getName()} to your shopping cart";
- $this->message_manager->addSuccess(__($msg));
- return $result->setData(['success' => true]);
- } catch (Exception $e) {
- $this->message_manager->addSuccess(__($e->getMessage()));
- return $result->setData(['success' => false,'error'=>$e->getMessage()]);
- }
- }
- }
Add Comment
Please, Sign In to add comment