3

I want to add a date picker field into the checkout page but I have no idea where to start.

I have tried this Add date picker in checkout page but it's not working for me.

We are having the below folder structure:

app\code\siva\mymodule\view\frontend\web\template\shipping.html

In shipping.html, we have the form which needs to be shown on the frontend.

Now, can I add both the HTML input field and JS in the same file, shipping.html?

If anyone got the delivery date field works in Checkout, please help me with this.

Updated Code in shipping-mixin.js:

   define([
    'jquery',
    'underscore',
    'Magento_Ui/js/form/form',
    'ko',
    'Magento_Customer/js/model/customer',
    'Magento_Customer/js/model/address-list',
    'Magento_Checkout/js/model/address-converter',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/action/create-shipping-address',
    'Magento_Checkout/js/action/select-shipping-address',
    'Magento_Checkout/js/action/create-billing-address',
    'Magento_Checkout/js/action/select-billing-address',
    'Magento_Checkout/js/action/set-shipping-information',
    'Magento_Checkout/js/model/step-navigator',
    'Magento_Checkout/js/checkout-data',
    'mage/translate'
], function(
    $,
    _,
    Component,
    ko,
    customer,
    addressList,
    addressConverter,
    quote,
    createShippingAddress,
    selectShippingAddress,
    createBillingAddress,
    selectBillingAddress,
    setShippingInformationAction,
    stepNavigator,
    checkoutData,
    $t
) {
    'use strict';
    $('#conform-account-scola-btn').prop('disabled', false);
    $('#onepage-guest-register-button').prop('disabled', false);
    $('#loa').hide(); 
    return function (target) {
        return target.extend({
            defaults: {
                template: 'DCKAP_School/shipping'
            },
            setShippingInformation: function () {
                var flag=false;
                var count = 0;
                var scrollTo = '';
                if($('input[name=school-or-private-person]').val() == 'school'){

                    $(".school-required-entry").each(function() {
                        if (this.value == 0 || this.value == '') {
                            count++;
                            //$(this).next('.school_err').html("This is a required field.");
                $(this).next('.school_err').html("Vänligen fyll i detta obligatoriska fält.");
                            $(this)[0].style.borderColor = "#ed8380";
                            $(this).next('.school_err').css("display", "block");
                            if(count==1){
                                scrollTo = "#"+$(this).attr('id');
                            }
                            flag=true;
                        }else{
                            $(this).next('.school_err').html('');
                $(this)[0].style.borderColor = "";
                            if(this.value != '')
                            {
                              if($("#school-display").css('display') == 'block' ){
                               $("#schoolsearch").next('.school_err').html("Vänligen klicka på din skola från listan nedan");
                               $("#schoolsearch").next('.school_err').css("display","block");
                               $("#schoolsearch").css("borderColor", "#ed8380");
                   $("html, body").animate({ scrollTop: 180 }, "slow");
                              }
                            } 
                        }
                    });

                    if (flag) {
                        if($("#school-display").css('display') == 'block' ){
                          $("html, body").animate({ scrollTop: 180 }, "slow");
                        }
                        else
                        {
                          $('html, body').animate({
                            scrollTop: $(scrollTo).offset().top
                          });  
                        }                        
                        return false;
                    }
                var firstname = $('#dc_shipping_firstname').val();
                var lastname = $('#dc_shipping_lastname').val();
                $('#shipping-new-address-form [name="firstname"]').val(firstname).keyup();
                $('#shipping-new-address-form [name="lastname"]').val(lastname).keyup();
                $('#billing-address-form [name="firstname"]').val(firstname).keyup();
                $('#billing-address-form [name="lastname"]').val(lastname).keyup();

                }
                else if ($('input[name=school-or-private-person]').val() == 'private')
                {
                   if ($("#customer-email").val() == 0 || $("#customer-email").val() == '') {
                    $("#customer-email").css("borderColor","#ed8380");
                    $(".input-text.mage-error").next('.school_err').css("display","none");
                    $("#customer-email-error").html("Vänligen fyll i detta obligatoriska fält."); 
                   }
                } 

                if (this.validateShippingInformation() && this.validateBillingInformation()) {
                    setShippingInformationAction().done(
                        function () {
                            $("#majema-school").hide();
                            $("#place-order-trigger-wrapper").show();
                            $("#custom-info").appendTo("#co-payment-form");
                            $('#custom-shipping-method-buttons-container').hide();
                            $('#custom-subtotal').hide();
                            $('.opc-block-summary .table-totals').show();
                            stepNavigator.next();
                        }
                    );
                }
            },
            validateBillingInformation: function() {

                if($('[name="billing-address-same-as-shipping"]').is(":checked")) {
                    if (this.isFormInline) {
                        var shippingAddress = quote.shippingAddress();
                        var addressData = addressConverter.formAddressDataToQuoteAddress(
                            this.source.get('shippingAddress')
                        );
                        //Copy form data to quote shipping address object
                        for (var field in addressData) {

                            if (addressData.hasOwnProperty(field) &&
                                shippingAddress.hasOwnProperty(field) &&
                                typeof addressData[field] != 'function' &&
                                _.isEqual(shippingAddress[field], addressData[field])
                            ) {
                                shippingAddress[field] = addressData[field];
                            } else if (typeof addressData[field] != 'function' &&
                                !_.isEqual(shippingAddress[field], addressData[field])) {
                                shippingAddress = addressData;
                                break;
                            }
                        }

                        if (customer.isLoggedIn()) {
                            shippingAddress.save_in_address_book = 1;
                        }
                        var newBillingAddress = createBillingAddress(shippingAddress);
                        selectBillingAddress(newBillingAddress);
                    } else {
                        selectBillingAddress(quote.shippingAddress());
                    }

                    return true;
                }

                var selectedAddress = $('[name="billing_address_id"]').val();
                if(selectedAddress) {
                    var res = addressList.some(function (addressFromList) {
                        if (selectedAddress == addressFromList.customerAddressId) {
                            selectBillingAddress(addressFromList);
                            return true;
                        }
                        return false;
                    });

                    return res;
                }

                this.source.set('params.invalid', false);
                this.source.trigger('billingAddress.data.validate');

                if (this.source.get('params.invalid')) {
                    return false;
                }

                var addressData = this.source.get('billingAddress'),
                    newBillingAddress;

                if ($('#billing-save-in-address-book').is(":checked")) {
                    addressData.save_in_address_book = 1;
                }

                newBillingAddress = createBillingAddress(addressData);
                selectBillingAddress(newBillingAddress);

                return true;
            }

        });


initialize: function () {
                    this._super();
                    ko.bindingHandlers.datetimepicker = {
                        init: function (element, valueAccessor, allBindingsAccessor) {
                            var $el = $(element);
                            //initialize datetimepicker
                            var options = {
                                minDate: 0,
                                dateFormat: 'yy-mm-dd'
                            };

                            $el.datetimepicker(options);

                            var writable = valueAccessor();
                            if (!ko.isObservable(writable)) {
                                var propWriters = allBindingsAccessor()._ko_property_writers;
                                if (propWriters && propWriters.datetimepicker) {
                                    writable = propWriters.datetimepicker;
                                } else {
                                    return;
                                }
                            }
                            writable($(element).datetimepicker("getDate"));
                        },
                        update: function (element, valueAccessor) {
                            var widget = $(element).data("DateTimePicker");
                            //when the view model is updated, update the widget
                            if (widget) {
                                var date = ko.utils.unwrapObservable(valueAccessor());
                                widget.date(date);
                            }
                        }
                    };

                    return this;
                }    
    }
});

Error in the console:

enter image description here

  • @PrathapGunasekaran I have tried this extension but it's not working – Siva May 21 at 8:38
  • @siva magento.stackexchange.com/questions/197513/… - checkout this answer – aravind May 22 at 8:35
  • @aravind, Thanks. Let me try and update you – Siva May 22 at 9:58
  • @siva Ok sure.. – aravind May 22 at 9:59
  • @aravind I have tried the solution but it's not working for me – Siva May 29 at 6:48
0

app/code/SR/MagentoCommunity/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/view/shipping': {
                'SR_MagentoCommunity/js/mixin/shipping-mixin': true
            }
        }
    }
};

app/code/SR/MagentoCommunity/view/frontend/web/js/mixin/shipping-mixin.js

define(
    [
        'jquery',
        'ko',
        'mage/translate'
    ], function (
        $,
        ko,
        $t
    ) {
        'use strict';

        return function (target) {
            return target.extend({
                initialize: function () {
                    this._super();
                    ko.bindingHandlers.datetimepicker = {
                        init: function (element, valueAccessor, allBindingsAccessor) {
                            var $el = $(element);
                            //initialize datetimepicker
                            var options = {
                                minDate: 0,
                                dateFormat: 'yy-mm-dd'
                            };

                            $el.datetimepicker(options);

                            var writable = valueAccessor();
                            if (!ko.isObservable(writable)) {
                                var propWriters = allBindingsAccessor()._ko_property_writers;
                                if (propWriters && propWriters.datetimepicker) {
                                    writable = propWriters.datetimepicker;
                                } else {
                                    return;
                                }
                            }
                            writable($(element).datetimepicker("getDate"));
                        },
                        update: function (element, valueAccessor) {
                            var widget = $(element).data("DateTimePicker");
                            //when the view model is updated, update the widget
                            if (widget) {
                                var date = ko.utils.unwrapObservable(valueAccessor());
                                widget.date(date);
                            }
                        }
                    };

                    return this;
                }
            });
        }
    }
);

Now in shipping.html add following code:

<label class="label">Delivery Date</label>
<div class="control">
    <input class="input-text" type="text" data-bind="datetimepicker: true"  name="delivery_date" id="delivery_date" readonly="true"/>
</div>

Clear static content if your Magento mode is not developer

  • Thanks. Let me try it. But in the file "shipping-mixin.js", already have some code. So now, where to add the code which you suggest in "shipping-mixin.js". I have updated the question with the code. Please help me. – Siva May 31 at 4:53
  • no problem, just copy initialize method in your code. – Sohel Rana May 31 at 6:01
  • I have tried that, but getting an error and the error says "Error: Script error for: jquery/jquery-ui-timepicker-addon" – Siva May 31 at 6:07
  • Don't know how you add, can you show error and update shipping-mixin.js – Sohel Rana May 31 at 6:09
  • I have included the updated shipping-mixin.js and screenshot of the error. Still, I'm getting the error, Can you please help me with this. – Siva Jun 3 at 11:33

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.