4

I want to add configurable product pragmatically. If product is ABC it has 3 size options XS M L so I want to add all options same time only changeable thing is quantity. I tried but it added as first selected option 3 times, need help. thanks.

0

Finally I have tried ajax method,Its worked but should have write wait method.

// -------------- add this function to custom.js file. -----------

function fncSubmitAjax(){
   var customurl = 
   jQuery('#product_addtocart_form').attr('action');
   var flag =false;
   var arrOptions = new Array();
   var productId =  jQuery("input[name='productId'").val();
   jQuery(".sproduct_qty").each(function () {
         var qty = jQuery('#' + this.id).val();
         if(qty > 0){
             var name = jQuery('#' + this.id).attr('name');
             var optionId =  name; 
             var vid  = name.replace('qty','size_id');
             var optionValueId = jQuery("input[name='"+vid+"'").val();
              arrOptions.push({'option_id':optionId,"option_value_id":optionValueId,"qty":qty});
             flag = true;
         }
     });
     if(flag){
         for (var i = 0; i < arrOptions.length; i++) {
             jQuery.ajax({
                 url: customurl,
                 type: 'POST',
                 dataType: 'json',
                 data: {
                     action:'addWholeSale',
                     id:productId,
                     options:arrOptions[i],
                 },
                 complete: function(response) {
                     if (response.responseJSON.success == 'true') {
                         // Update minicart after product add
                         require([
                           'Magento_Customer/js/customer-data'
                           ], function (customerData) {
                               var sections = ['cart'];
                               customerData.invalidate(sections);
                               customerData.reload(sections, true);

                           });
                           // end update minicart
                         // ---------------- Open Minicart --------------
                          jQuery('[data-block="minicart"]').on('contentUpdated', function ()  {});
                         // --------------- End -------------------------
                         }
                       },
                       error: function (xhr, status, errorThrown) {
                         console.log('Error happens. Try again.');
                     }
                 });
         }
         // return true;
       }
      else{
         alert('Please add quantity in one of the option');
         return false;
      }

    }
            ------------------------------------ Add this to  Product add Controller 
            ---------------------------- AddItems.php under execute() funtion

            $action = $this->getRequest()->getPostValue('action');

            if ("addWholeSale" == $action) {
              $FormKey = 
              $this->_objectManager->get('Magento\Framework\Data\Form\FormKey');
              $Formkeyget=$FormKey->getFormKey();

              try {
                $productId = $this->getRequest()->getPostValue('id');
                $productOptions = $this->getRequest()->getPostValue('options');
                //$productRepository = 
                $this->_objectManager->get('\Magento\Catalog\Model\ProductRepository');
                // $product = $productRepository->getById($productId);
                $product = $this->_initProduct($productId);
                if ($product) {
                $productName = $product->getName();
                $productQty = $productOptions["qty"];
                $optionId = 
                str_replace('superattr[','',$productOptions["option_id"]);
                $optionId = str_replace('][qty]','',$optionId);
                $optionId = explode("][",$optionId);
                $optionId = $optionId[1];
                $option_value_id = $productOptions['option_value_id'];
                $options = array($optionId => $option_value_id );

                if ($productQty > 0) {
                  $params = array(
                  'form_key' => $Formkeyget,
                  'product' => $product->getId(),
                  'wholesaler'=>true,
                  'super_attribute' => $options,
                  'qty'   => $productQty //quantity of 
                  product
                  );
                  $this->cart->addProduct($product, $params);
                  $this->cart->save();
                }

              }
              $arrResponse['success'] = "true";
              $this->messageManager->addSuccess(__("$productName is successfully added 
              to bag") );
              echo json_encode($arrResponse);

              } catch (\Magento\Framework\Exception\LocalizedException $e) {
              $arrResponse['success'] = "false";
              // $this->_loggerInterface->critical($e);
              $this->messageManager->addError(__("Error! some products 
              could not added to bag.") );
              //return parent::_goBack();
              } catch (Exception $ex) {
              $arrResponse['success'] = "false";
              // $this->_loggerInterface->critical($e);
              $this->messageManager->addError(__("Error! some products 
              could not added to bag.") );
              //return parent::_goBack();
              }
            }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.