Skip to content

Knockout js – Check Payment method if is only one

I was tried validate with knockout js if payment method is one default checked but not works, actually default is not checked:

This is my code:

view/frontend/web/template/payment/payu.html

<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
    <div class="payment-method-title field choice">
        <input type="radio"
               name="payment[method]"
               class="radio"
               data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()" />
        <label data-bind="attr: {'for': getCode()}" class="label">
            <div class="dot"></div>
            <img class="logopayu" data-bind="attr: {src: window.checkoutConfig.staticBaseUrl + 'frontend/ElTiempo/default/es_CO/images/checkout/img-payu.png'}"/>
        </label>
    </div>

    <div class="payment-method-content">
        <!-- ko foreach: getRegion('messages') -->
        <!-- ko template: getTemplate() --><!-- /ko -->
        <!--/ko-->
        <div class="payment-method-billing-address">
            <!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->
            <!-- ko template: getTemplate() --><!-- /ko -->
            <!--/ko-->
        </div>
        <div id="seccion-payu" class="hide">
            <div class="info-payu">
                <div class="arrow-top"><img data-bind="attr: {src: require.toUrl('ElTiempo_Efecty/images/flechainfo.svg')}" /></div>
                <img class="img-bancospayu" data-bind="attr: {src: window.checkoutConfig.staticBaseUrl + 'frontend/ElTiempo/default/es_CO/images/icons/icon-cards.png'}"/>
                <p>Pagos PSE, con tarjetas de crédito, débito o transacción bancaria de forma segura a través de PayU</p>
            </div>

            <div class="actions-toolbar">
                <div class="primary">
                    <button id="button_payu" class="action primary checkout metricas-pagar"
                            type="submit"
                            data-bind="
                            click: placeOrder,
                            attr: {title: $t('Place Order')},
                            css: {disabled: !isPlaceOrderActionAllowed()},
                            enable: (getCode() == isChecked())
                            "
                            disabled
                            data-posicion="1"
                            data-origen="informacion-de-pago">
                        <span data-bind="i18n: 'Place Order'"></span>
                        <span data-bind="i18n: getTotalValue()"></span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

Magento_Checkout/web/js/view/payment/default.js

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define([
    'ko',
    'jquery',
    'uiComponent',
    'Magento_Checkout/js/action/place-order',
    'Magento_Checkout/js/action/select-payment-method',
    'Magento_Checkout/js/model/quote',
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/payment-service',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/checkout-data-resolver',
    'uiRegistry',
    'Magento_Checkout/js/model/payment/additional-validators',
    'Magento_Ui/js/model/messages',
    'uiLayout',
    'Magento_Checkout/js/action/redirect-on-success',
    'Magento_Checkout/js/model/totals',
    'Magento_Catalog/js/price-utils',
    'Magento_Checkout/js/model/paymentMethodRendered'
], function (
    ko,
    $,
    Component,
    placeOrderAction,
    selectPaymentMethodAction,
    quote,
    customer,
    paymentService,
    checkoutData,
    checkoutDataResolver,
    registry,
    additionalValidators,
    Messages,
    layout,
    redirectOnSuccessAction,
    totals,
    priceUtils,
    methodsRendered
) {
    'use strict';

    return Component.extend({
        redirectAfterPlaceOrder: true,
        isPlaceOrderActionAllowed: ko.observable(quote.billingAddress() != null),
        totals: quote.getTotals(),

        /**
         * After place order callback
         */
        afterPlaceOrder: function () {
            // Override this function and put after place order logic here
        },

        /**
         * Initialize view.
         *
         * @return {exports}
         */
        initialize: function () {
            var billingAddressCode,
                billingAddressData,
                defaultAddressData;

            this._super().initChildren();
            quote.billingAddress.subscribe(function (address) {
                this.isPlaceOrderActionAllowed(address !== null);
                this.isCheckedToShowTooltip();
            }, this);
            checkoutDataResolver.resolveBillingAddress();

            billingAddressCode = 'billingAddress' + this.getCode();
            registry.async('checkoutProvider')(function (checkoutProvider) {
                defaultAddressData = checkoutProvider.get(billingAddressCode);

                if (defaultAddressData === undefined) {
                    // Skip if payment does not have a billing address form
                    return;
                }
                billingAddressData = checkoutData.getBillingAddressFromData();

                if (billingAddressData) {
                    checkoutProvider.set(
                        billingAddressCode,
                        $.extend(true, {}, defaultAddressData, billingAddressData)
                    );
                }
                checkoutProvider.on(billingAddressCode, function (providerBillingAddressData) {
                    checkoutData.setBillingAddressFromData(providerBillingAddressData);
                }, billingAddressCode);
            });

            setTimeout(function(){
                methodsRendered.addMethod(this.name);
            }.bind(this),100);

            return this;
        },

        /**
         * Initialize child elements
         *
         * @returns {Component} Chainable.
         */
        initChildren: function () {
            this.messageContainer = new Messages();
            this.createMessagesComponent();
            return this;
        },

        /**
         * Create child message renderer component
         *
         * @returns {Component} Chainable.
         */
        createMessagesComponent: function () {

            var messagesComponent = {
                parent: this.name,
                name: this.name + '.messages',
                displayArea: 'messages',
                component: 'Magento_Ui/js/view/messages',
                config: {
                    messageContainer: this.messageContainer
                }
            };

            layout([messagesComponent]);

            return this;
        },

        /**
         * Place order.
         */
        placeOrder: function (data, event) {
            /* DTM */
            var bk_event_pago = "https://tags.bluekai.com/site/" + _satellite.getDataElement('BK_SiteId') + "?phint=clic%3Dpago";
            $('<img />').on('load').attr('src', bk_event_pago);
            /* DTM */
            var self = this;

            if (event) {
                event.preventDefault();
            }

            if (this.validate() && additionalValidators.validate()) {
                this.isPlaceOrderActionAllowed(false);

                this.getPlaceOrderDeferredObject()
                    .fail(
                        function () {
                            self.isPlaceOrderActionAllowed(true);
                        }
                    ).done(
                        function () {
                            self.afterPlaceOrder();

                            if (self.redirectAfterPlaceOrder) {
                                redirectOnSuccessAction.execute();
                            }
                        }
                    );

                return true;
            }

            return false;
        },

        /**
         * @return {*}
         */
        getPlaceOrderDeferredObject: function () {
            return $.when(
                placeOrderAction(this.getData(), this.messageContainer)
            );
        },

        /**
         * @return {Boolean}
         */
        selectPaymentMethod: function () {
            selectPaymentMethodAction(this.getData());
            checkoutData.setSelectedPaymentMethod(this.item.method);
            if(quote.billingAddress() == null) {
                $("div.shipping-address-item.same-as-shipping").trigger("click");
            }
            // quote.billingAddress(null);
            this.isCheckedToShowTooltip();
            return true;
        },

        isChecked: ko.computed(function () {
            return quote.paymentMethod() ? quote.paymentMethod().method : null;
        }),

        isCheckedToShowTooltip: function () {
            $(".loading-mask").addClass("hide");

            if($(".payment-method").length > 1 && $(".multiple_payment_method").length == 0) {
                $(".billing-address-list").before('<h4 class="multiple_payment_method"><span>Datos de envío</span></h4>');
                $(".block.items-in-cart.active div.title").addClass("hide");
                $(".block.items-in-cart").before('<h4 class="multiple_payment_method"><span>Resumen de tu compra</span></h4>');
                $("#checkout-payment-method-load").before('<h4 class="multiple_payment_method"><span>Método de pago</span></h4>');
            }

            if(quote.paymentMethod()) {
                if($("#seccion-payu-below").length > 0) {
                    $("#seccion-payu-below").remove();
                }

                if($("#seccion-efecty-below").length > 0) {
                    $("#seccion-efecty-below").remove();
                }

                switch(quote.paymentMethod().method) {
                  case "payu":
                          $("#payment-methods-group-list" ).after("<div id='seccion-payu-below'>" + $("#seccion-payu").html() + "</div>");
                          $("#seccion-payu-below button").removeAttr("data-bind data-posicion data-origen");

                          if($("#seccion-payu button").hasClass("disabled")) {
                              $("#seccion-payu-below button").attr('disabled','disabled').addClass("disabled");
                          } else {
                              $("#seccion-payu-below button").removeAttr('disabled','disabled').removeClass("disabled");
                          }

                          $("#seccion-payu-below button").attr({ id: "button_payu_below", type: "button", onclick: "submitPaymentMethod('" + quote.paymentMethod().method + "');" });

                          if($('#payu').is(':checked')) {
                              $('#seccion-payu-below').show();
                          }
                    break;
                  case "efecty":
                          $("#payment-methods-group-list" ).after("<div id='seccion-efecty-below'>" + $("#seccion-efecty").html() + "</div>");
                          $("#seccion-efecty-below button").removeAttr("data-bind data-posicion data-origen");

                          if($("#seccion-efecty button").hasClass("disabled")) {
                              $("#seccion-efecty-below button").attr('disabled','disabled').addClass("disabled");
                          } else {
                              $("#seccion-efecty-below button").removeAttr('disabled','disabled').removeClass("disabled");
                          }

                          $("#seccion-efecty-below button").attr({ id: "button_efecty_below", type: "button", onclick: "submitPaymentMethod('" + quote.paymentMethod().method + "');" });

                          if($('#efecty').is(':checked')) {
                              $('#seccion-efecty-below').show();
                          }
                    break;
                }
            }
        },

        isRadioButtonVisible: ko.computed(function () {
            return paymentService.getAvailablePaymentMethods().length !== 1;
        }),

        /**
         * Get payment method data
         */
        getData: function () {
            return {
                'method': this.item.method,
                'po_number': null,
                'additional_data': null
            };
        },

        /**
         * Get payment method type.
         */
        getTitle: function () {
            return this.item.title;
        },

        /**
         * Get payment method code.
         */
        getCode: function () {
            return this.item.method;
        },

        /**
         * @return {Boolean}
         */
        validate: function () {
            return true;
        },

        /**
         * @return {String}
         */
        getBillingAddressFormName: function () {
            return 'billing-address-form-' + this.item.method;
        },

        /**
         * Dispose billing address subscriptions
         */
        disposeSubscriptions: function () {
            // dispose all active subscriptions
            var billingAddressCode = 'billingAddress' + this.getCode();

            registry.async('checkoutProvider')(function (checkoutProvider) {
                checkoutProvider.off(billingAddressCode);
            });
        },


        // TOTAL
        /**
         * @return {*|String}
         */
        getTotalValue: function () {
            var price = 0;

            if (this.totals()) {
                price = totals.getSegment('grand_total').value;
            }

            return this.getFormattedPrice(price);
        },

        /**
         * @param {*} price
         * @return {*|String}
         */
        getFormattedPrice: function (price) {
            return priceUtils.formatPrice(price, quote.getPriceFormat());
        }
    });
});

Thanks!