0

Product size and input

I want to add custom size with input field. Like this image and total quantity add to cart.

1 Answer 1

0

To achieve this,

  1. Add your desired option to the size attribute.

  2. Fetch these option values and create HTML with the input field along with each option that accepts the integer values. (please find the snippet below.)

  3. Create a custom route (multipleorder) that handles add-to-cart actions and adds multiple products (with qty values size attribute value) programmatically.

<?php
/** @var $block \Magento\Swatches\Block\Product\Renderer\Configurable */
$blockObj = $block->getLayout()->createBlock('\Magento\Swatches\Block\Product\Renderer\Configurable');
$viewModel = $block->getData('swatchOptions');
$_product = $blockObj->getProduct();
$id = $_product->getId();
$optionsnew = (array)json_decode($blockObj->getJsonConfig());
$array = json_decode(json_encode($optionsnew), true);
$ids[] = "";
$emptyIds = [];
foreach ($array['attributes']  as $attValue) {

    foreach ($attValue  as $key => $value) {
        if ($key == 'id') {
            $optionid = $value;
        }

        if ($key == 'options') {
            $value = (array)$value;
            $iii = count($value);
            foreach ($value as $key => $item) {
                $products = $item['products'];
                
                if (!empty($products)) {
                    $ids[$item['id']]['label'] = $item['label'];
                    $productId = $products[0];
                    $stock = $viewModel->getStock($productId);
                    if ($stock) {
                        $ids[$item['id']]['in_stock'] = 1;
                    } else {
                        $ids[$item['id']]['in_stock'] = 0;
                    }
                }
            }
        }
    }
}
?>

<form method="post" enctype="multipart/form-data" id="multipleform" data-role="tocart-form" data-product-sku="<?= $block->escapeHtml($_product->getSku()) ?>"> <?php echo $block->getBlockHtml('formkey') ?>
    <input type="hidden" name="product_id" value="<?= $id ?>">
    <div class="float-container-wrapper">
        <?php foreach ($ids as $key => $value) : ?>
            <?php if (!empty($value['label'])) : ?>
                <div class="float-container">
                    <div class="float-child">
                        <label class="label" for="qty"><span id="<?= /* @escapeNotVerified */ $key ?>"><?php /* @escapeNotVerified */ echo __($value['label']) ?></span></label>
                    </div>
                    <?php if ($block->shouldRenderQuantity()) : ?>
                        <div class="fields qtys">
                            <div class="control">
                                <div class="qty-minus"> <a class="<?php if ($value['in_stock']) : ?>btn-qtys minus <?php endif; ?>" <?php if ($value['in_stock']) : ?> href="#" <?php endif; ?>>-</a></div>
                                <div class="qty-input">
                                    <input type="number" name="<?= /* @escapeNotVerified */ $optionid ?>[<?= /* @escapeNotVerified */ $key ?>]" id="qtys-<?= /* @escapeNotVerified */ $value['label'] ?>" maxlength="12" value="0" title="<?php /* @escapeNotVerified */ echo __('Qty') ?>" class="input-text qty" data-validate="<?php echo $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>" <?php if (!$value['in_stock']) : ?> disabled="disabled" <?php endif; ?> />
                                </div>
                                <div class="qty-plus"> <a class="<?php if ($value['in_stock']) : ?>btn-qtys plus <?php endif; ?>" <?php if ($value['in_stock']) : ?> href="#" <?php endif; ?>>+</a></div>
                            </div>
                        </div>
                        <script type="text/javascript">
                            require(['jquery', 'domReady!'], function($) {
                                $(".btn-qtys").click(function(event) {
                                    var $button = $(this);
                                    var oldValue = $button.closest('.control').find("input#qtys-<?= /* @escapeNotVerified */ $value['label'] ?>").val();
                                    // var defaultValue = <?php // echo $block->getProductDefaultQty() * 1 
                                                            ?>;
                                    var defaultValue = 0;
                                    if ($button.hasClass('plus')) {
                                        var newVal = parseFloat(oldValue) + 1;
                                    } else {
                                        if (oldValue > defaultValue) {
                                            var newVal = parseFloat(oldValue) - 1;
                                        } else {
                                            newVal = defaultValue;
                                        }
                                    }
                                    $button.closest('.control').find("input#qtys-<?= /* @escapeNotVerified */ $value['label'] ?>").val(newVal);
                                    event.preventDefault();
                                });

                            });
                        </script>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>
    <div class="primary-form">
        <button type="submit" id="submit-btn" class="action submit primary tocart" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>"><span><?php /* @escapeNotVerified */ echo __('Add to Bag') ?></span></button>
    </div>
</form>
<script type="text/javascript">
    require(['jquery', 'Magento_Customer/js/customer-data'], function($, customerData) {

        $(document).ready(function() {
            $("#submit-btn").click(function(event) {
                //stop submit the form, we will post it manually.
                event.preventDefault();
                $("#submit-btn").html("Adding..");
                $("#submit-btn").prop("disabled", true);
                // Get form
                var form = $('#multipleform')[0];
                var url = "<?php /* @escapeNotVerified */ echo $block->getUrl('multipleorder/index/index'); ?>";
                var data = new FormData(form);
                $.ajax({
                    type: "POST",
                    enctype: 'multipart/form-data',
                    url: url,
                    data: data,
                    processData: false,
                    contentType: false,
                    timeout: 800000,
                    showLoader: true,
                    success: function(data) {
                        var sections = ['cart'];
                        customerData.invalidate(sections);
                        customerData.reload(sections, true);
                        $("#submit-btn").html("Added..");
                        $("#submit-btn").prop("disabled", true);
                        setTimeout(function() {
                            $("#submit-btn").prop("disabled", false);
                            $("#submit-btn").html("ADD TO BAG");
                        }, 1000);

                    },
                    error: function(e) {
                        $("#output").text(e.responseText);
                        console.log("ERROR : ", e);
                        $("#submit-btn").prop("disabled", false);
                    }

                });
            });
        });
    });
</script>

If any queries, please let me know.

2
  • I see many files folder structures in magento2 root directory. In which file should I write the code? Commented May 7 at 7:35
  • @MadhabKarmaker, you need to create your custom template and add logic there. It has to be called in the add-to-cart form. You can use the catalog_product_view.xml layout and call the custom template file. Commented May 16 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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