2

I am new to magento2. I want to create a custom checkbox for a required option without checked checkbox customer cannot place an order. How to create terms and conditions checkbox custom field using custom code. I have an issue with magento2 default terms and conditions it is not working.

2
  • Issue with default terms and condition means?
    – Keyur Shah
    Apr 22, 2018 at 18:15
  • Issue with custom theme, we are using amasty one page checkout and default magento2 terms and conditions not working with amasty. So thats why we want create custom terms and conditions checkbox. Apr 23, 2018 at 5:56

2 Answers 2

2

Create New column 'agree' in 'quote' and 'sales_order' table at DB. and

Vendor\Module\etc\extension_attributes.xml

<?xml version="1.0"?> 
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
        <extension_attributes for="Magento\Quote\Api\Data\AddressInterface">
            <attribute code="agree" type="string" />
        </extension_attributes>
    </config>

Vendor\Module\view\frontend\layout\checkout_index_index.xml

<?xml version="1.0"?> 
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="checkout.root">
                <arguments>
                    <argument name="jsLayout" xsi:type="array">
                        <item name="components" xsi:type="array">
                            <item name="checkout" xsi:type="array">
                                <item name="children" xsi:type="array">
                                    <item name="steps" xsi:type="array">
                                        <item name="children" xsi:type="array">
                                            <item name="billing-step" xsi:type="array">
                                                <item name="children" xsi:type="array">
                                                    <item name="payment" xsi:type="array">
                                                        <item name="children" xsi:type="array">
    <!-- to show checkbox inside payment section-->
                                                            <item name="payments-list" xsi:type="array">
                                                                <item name="children" xsi:type="array">
                                                                    <item name="before-place-order" xsi:type="array">
                                                                        <item name="children" xsi:type="array">
                                                                            <item name="custom-checkbox" xsi:type="array">
                                                                                <item name="component" xsi:type="string">vendor_module/js/checkout/customJs</item>
                                                                                <item name="displayArea" xsi:type="string">before-place-order</item>
                                                                                <item name="sortOrder" xsi:type="string">3</item>
                                                                                <item name="dataScope" xsi:type="string">checkoutcomments</item>
                                                                                <item name="provider" xsi:type="string">checkoutProvider</item>
                                                                            </item>
                                                                        </item>
                                                                    </item>
                                                                </item>
                                                            </item>
    
    <!-- to show checkbox below the payment methods -->
                                                            <!-- <item name="afterMethods" xsi:type="array">
                                                                <item name="children" xsi:type="array">
                                                                    <item name="custom-checkbox" xsi:type="array">
                                                                        <item name="component" xsi:type="string">vendor_module/js/checkout/customJs</item>
                                                                        <item name="displayArea" xsi:type="string">before-place-order</item>
                                                                        <item name="sortOrder" xsi:type="string">3</item>
                                                                        <item name="dataScope" xsi:type="string">checkoutcomments</item>
                                                                        <item name="provider" xsi:type="string">checkoutProvider</item>
                                                                    </item>
                                                                </item>
                                                            </item> -->
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </argument>
                </arguments>
            </referenceBlock>
        </body>
    </page>

Vendor\Module\view\frontend\web\js\checkout\customJs.js

define(
[
    'ko',
    'jquery',
    'uiComponent',
    'mage/url'
],
function (ko, $, Component,url) {
    'use strict';
    return Component.extend({
        defaults: {
            template: 'vendor_module/checkout/customCheckbox'
        },
        initObservable: function () {

            this._super()
                .observe({
                    CheckVals: ko.observable(true) //default checked(true)
                });
            var checkVal=0;
            self = this;
            this.CheckVals.subscribe(function (newValue) {
                var linkUrls  = url.build('custom/checkout/saveInQuote');
                if(newValue) {
                    checkVal = 1;
                }
                else{
                    checkVal = 0;
                }
                $.ajax({
                    showLoader: true,
                    url: linkUrls,
                    data: {checkVal : checkVal},
                    type: "POST",
                    dataType: 'json'
                }).done(function (data) {
                    console.log('success');
                });
            });
            return this;
        }
    });
});

Vendor\Module\view\frontend\web\template\checkout\customCheckbox.html

<input type="checkbox" id="customCheckbox" name="customCheckbox" value="" data-bind='checked: CheckVals'/><label for="customCheckbox">Please uncheck this box if you <b>do not</b> want to hear from us about our inspirational, new arrivals and latest offers</label><br>

Vendor\Module\Controller\Checkout\saveInQuote.php

    <?php
namespace Vendor\Module\Controller\Checkout;

use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\ForwardFactory;
use Magento\Framework\View\LayoutFactory;
use Magento\Checkout\Model\Cart;
use Magento\Framework\App\Action\Action;
use Magento\Checkout\Model\Session;
use Magento\Quote\Model\QuoteRepository;

class saveInQuote extends Action
{
    protected $resultForwardFactory;
    protected $layoutFactory;
    protected $cart;

    public function __construct(
        Context $context,
        ForwardFactory $resultForwardFactory,
        LayoutFactory $layoutFactory,
        Cart $cart,
        Session $checkoutSession,
        QuoteRepository $quoteRepository
    )
    {
        $this->resultForwardFactory = $resultForwardFactory;
        $this->layoutFactory = $layoutFactory;
        $this->cart = $cart;
        $this->checkoutSession = $checkoutSession;
        $this->quoteRepository = $quoteRepository;

        parent::__construct($context);
    }

    public function execute()
    {
        $checkVal = $this->getRequest()->getParam('checkVal');
        $quoteId = $this->checkoutSession->getQuoteId();
        $quote = $this->quoteRepository->get($quoteId);
        $quote->setAgree($checkVal);
        $quote->save();
    }
} ?>

Vendor\Module\etc\events.xml

<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_model_service_quote_submit_before">
    <observer name="custom_checkbox_code_order_place_before_action" instance="Vendor\Module\Observer\PlaceOrder"/>
</event>

Vendor\Module\Observer\PlaceOrder.php

<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Quote\Model\QuoteFactory;
use Psr\Log\LoggerInterface;

class PlaceOrder implements ObserverInterface
{
    /**
    * @var \Psr\Log\LoggerInterface
    */
    protected $_logger;

    /**
    * @var \Magento\Customer\Model\Session
    */
    protected $quoteFactory;

    /**
     * Constructor
     *
     * @param \Psr\Log\LoggerInterface $logger
     */

    public function __construct(LoggerInterface $logger,
        QuoteFactory $quoteFactory) {
        $this->_logger = $logger;
        $this->quoteFactory = $quoteFactory;
    }

    public function execute(Observer $observer)
    {
        $order = $observer->getOrder();
        $quoteId = $order->getQuoteId();
        $quote  = $this->quoteFactory->create()->load($quoteId);
        $order->setAgree($quote->getAgree());
    }
} ?>
3
  • did you know how to validate this checkbox? Dec 7, 2021 at 15:30
  • add 'required' attribute in checKbox field at customCheckbox.html or you can validate through JS at 'Vendor\Module\view\frontend\web\js\checkout\customJs.js'
    – akashmalik
    Dec 8, 2021 at 17:55
  • How to checkbox checked if the value is already set to 1. Because after checked the checkbox if i reload the page then it should remain checked. Any idea? Jun 15 at 13:24
3

Just following devdocs (official magento documentation). I Break it into two

  1. How to do it.
  2. How it's work.

checkout is implemented using UI components. it can customize each step by changing the JavaScript implementation or template for a component, adding, removing or disabling a component.

1.Create Js file let consider it your yourcustom.js under VendorNameSpace/ModuleName/view/frontend/web/js/view folder

define(
    [
        'ko',
        'uiComponent'
    ],
    function (ko, Component) {
        "use strict";

        return Component.extend({
            defaults: {
                template: 'VendorNameSpace_ModuleName/yourtemplatefileName'
            },
            isRegisterNewsletter: true
        });
    }
);

Create yourtemplatefileName.html under YourVendorName/ModuleName/view/frontend/web/template folder

<div class="col-mp mp-12">
    <input type="checkbox" name="newsletter" data-bind="checked: isRegisterNewsletter, attr: {id: 'place-order-newsletter'}"/>
    <label data-bind="attr: {for: 'place-order-newsletter'}"><span data-bind="i18n: 'Custom checkbox'"></span></label>
</div>

component contains a js and take a html file as its template.

Add component to checkout page layout YourVendorName/ModuleName/view/frontend/layout/checkout_index_index.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.root">
                <arguments>
                    <argument name="jsLayout" xsi:type="array">
                        <item name="components" xsi:type="array">
                            <item name="checkout" xsi:type="array">
                                <item name="children" xsi:type="array">
                                    <item name="steps" xsi:type="array">
                                        <item name="children" xsi:type="array">
                                            <!-- Modifying an existing step-->
                                            <item name="shipping-step" xsi:type="array">
                                                <item name="children" xsi:type="array">
                                                    <item name="shippingAddress" xsi:type="array">
                                                        <item name="children" xsi:type="array">
                                                            <item name="before-form" xsi:type="array">
                                                                <item name="children" xsi:type="array">
                                                                    <item name="newsletter" xsi:type="array">
                                                                        <item name="component" xsi:type="string">YourVendorName_ModueName/js/view/yourcustom</item>
                                                                    </item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>

                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </argument>
                </arguments>
        </referenceBlock>
    </body>
</page>

In your custom module directory. <your_module_dir>/view/frontend/layout/checkout_index_index.xml. (For your checkout customization to be applied correctly, your custom module should depend on the Magento_Checkout module. you must add composer.json to add dependency

     {
      "name": "vendorname/modulename",
      "description": "custom checkout adding checkbox component",
      "license": "GPL-3.0",
      "type": "magento2-module",
      "version": "1.0.0",
      "authors": [
        {
          "email": "[email protected]",
          "name": "yourname"
        }
      ],
      "keywords": [
        "magento2-module"
      ],
      "minimum-stability": "dev",
      "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0",
        "magento/framework": "*",
        "magento/module-checkout": ">100.0",
      },
      "autoload": {
        "files": [
          "registration.php"
        ],
        "psr-4": {
          "VendorName\\ModuleName\\": ""
        }
      }
    }

2. How it's work **component is just javascript file as below but further more **

<item name="shipping_policy" xsi:type="array">
  <item name="component" xsi:type="string">Magento_Shipping/js/view/checkout/shipping/shipping-policy</item>
</item>

when open it

vendor/magento/module-shipping/view/frontend/web/js/view/checkout/shipping/shipping-policy.js

/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define([
    'uiComponent',
    'Magento_Shipping/js/model/config'

], function (Component, config) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Shipping/checkout/shipping/shipping-policy'
        },
        config: config()
    });
});

it's define template here

vendor/magento/module-shipping/view/frontend/web/template/checkout/shipping/shipping-policy.html
8
  • We have checked but default terms and conditions have problems with amasty one page checkout. So we want create custom terms and conditions checkbox. How to create terms and conditions with amasty one page checkout with required options checkbox. Apr 23, 2018 at 5:59
  • updated answer if Amasty doesn't have setting options for terms and conditions Apr 23, 2018 at 6:14
  • No there is no settings with amasty for terms and conditions . I go through the store - >terms and conditions but we have problems when we enable term and conditions through the store configuration it is show term and conditions for every payment method. So thats why we want create custom terms and conditions. Apr 23, 2018 at 6:16
  • How to create custom HTML checkbox with required fields when customer click on place order button without checked checkbox then we need to show error messages too without default magento2 code Apr 23, 2018 at 16:48
  • 1
    I'm pretty sure that in Vendor_Module/web/template you can only have html templates and not phtml as in your example (yourtemplatefileName.phtml)
    – Zankar
    Mar 7, 2019 at 12:15

Your Answer

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

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