1

I am trying to add multiple products in cart programmatically. This below code is working properly but I need to set quantity dynamically. If quantity is not set that product to be skipped without adding in cart.

   <?php
$count = 0;
$cartItems = array();
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$_childProducts = $_product->getTypeInstance()->getUsedProducts($_product);

foreach($_childProducts as $simpleProduct)
    {

    // echo '<pre>' , var_dump($simpleProduct->getData()) , '</pre>';

    $sku = $simpleProduct->getSku();
    $count++;
    $stringSku = '"' . $sku . '"';
    if ($simpleProduct['jasani_color'] == $tmp['value_index'])
        {
        $sql = "select * from inventory_stock_4 where sku =" . $stringSku;
        $result = $connection->fetchAll($sql);
?>
        <td>
                <?php
        echo $option_label = $result[0]['quantity'] ?>
                <input  type="number" min="0" max="1000" pattern="[0-9]*" id="qty" name="qty"  />
                <script>
            var qty = document.getElementById('qty').value; 

<?php
        $qty = "<script>document.write(qty)</script>" ?>  
    </script>
        </td>


    <?php
        if (isset($_POST['submit'])): ?>


    <?php
            $cart = $objectManager->create('Magento\Checkout\Model\Cart');
            $product = $objectManager->create('\Magento\Catalog\Model\Product')->load($simpleProduct->getId());
            $params = array();
            $params['qty'] = $qty;
            $params['product'] = $simpleProduct->getId();
            $cart->addProduct($product, $params);
            $cart->save();
            $cart->addProduct($product, $params);
            $cart->save();
            if (count($_childProducts) == $count)
                {
                header("Location:magento_controller/");
                exit;
                }

?>

            <?php
        endif; ?>

        <?php
        }

?>
</tr>

        </tbody>
        </table>

        <form method="post">
        <input class="cart-btn-custom float-right" type="submit" name="submit"/>
        </form>


        <?php
endif; ?>
</div>

<?php
}

?>

I can't assign a form tag before the quantity input tag because It is inside a loop. So that I cannot assign this quantity to cart quantity. I need this quantity to be the quantity given by the user in the multiple text box. The below image clarifies my question.

enter image description here

I need to enter this submit box with the assigned quantities like image above.

Your Answer

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

Browse other questions tagged or ask your own question.