Skip to content

How To Make My Data Dynamic – Checkout page

I have this custom module which I am using to check if the items in the cart are a promotional/Franke product. If they are then applying an affiliate coupon will have no effect. It works on the original page load and the correct success/error messages display. However when you remove an item from the cart the page does not reload only the cart summary does thus the array still contains the old data. I want to make the data dynamic so that whenever an item is added or removed the array changes and thus the correct popup message will display. Below is my onepage.phtml file which is where I retrieve the data and add it to the array.

helper(CodazonSalesProHelperData::class);
// Get all visible items in cart
$quote = $block->getData(“view_model”)->getQuoteData();
foreach($quote->getAllVisibleItems() as $_item) {
$_product = $_item->getProduct();
$categoryIds = $_product->getCategoryIds();
$isPromoItem = in_array(206, $categoryIds) ? ‘Yes’ : ‘No’;
$containsFranke = strpos($_item->getName(), ‘Franke’) !== false ? ‘Yes’ : ‘No’;

// echo “

";print_r($_item->debug());
    echo 'ID: '.$_item->getProductId().'
'; echo 'Name: '.$_item->getName().'
'; echo 'Sku: '.$_item->getSku().'
'; echo 'Quantity: '.$_item->getQty().'
'; echo 'Price: '.$_item->getPrice().'
'; echo 'Product Type: '.$_item->getProductType().'
'; echo 'Discount: '.$_item->getDiscountAmount();echo "
"; echo 'Category IDs: ' .implode(', ', $categoryIds)."
"; echo 'Promo: '. $isPromoItem.'
'; echo 'Franke: '.$containsFranke.'
'; echo "
"; } ?> escapeUrl($block->getViewFileUrl('images/loader-1.gif')) ?>" alt="escapeHtmlAttr(__('Loading...')) ?>"> renderStyleAsTag("position: absolute;", "#checkout-loader img") : ''; ?>
<script>
    var cdzOscConfig = <?= $helper->getCustomOptionsJson() ?>;
    require.config({
        config: {
            mixins: {
                'Magento_Checkout/js/view/shipping': {
                    'Codazon_SalesPro/js/checkout/view/shipping-mixin': true
                },
                'Magento_Checkout/js/view/payment': {
                    'Codazon_SalesPro/js/checkout/view/payment-mixin': true
                },
                'Magento_Checkout/js/view/billing-address': {
                    'Codazon_SalesPro/js/checkout/view/billing-address-mixin': true
                },
                'Magento_Checkout/js/view/shipping-address/address-renderer/default': {
                    'Codazon_SalesPro/js/checkout/view/shipping-address/address-renderer/default-mixin': true
                },
                'Magento_Checkout/js/view/sidebar': {
                    'Codazon_SalesPro/js/checkout/view/sidebar-mixin': true
                },
                'Magento_Checkout/js/model/place-order': {
                    'Codazon_SalesPro/js/checkout/model/place-order-mixin': true
                },
                'Magento_Checkout/js/model/checkout-data-resolver': {
                    'Codazon_SalesPro/js/checkout/model/checkout-data-resolver-mixin': true
                }<?php if ((bool)$helper->getConfig('codazon_osc/customization/enable_edit_qty')) : ?>,
                'Magento_Checkout/js/view/summary/item/details': {
                    'Codazon_SalesPro/js/checkout/view/summary/item/details-mixin': true
                }<?php endif ?>
            }
        }
    });
    <?php /* require(['jquery', 'Magento_Ui/js/core/app'], function($, app) {
        var opcConfig = <?= $block->getJsLayout() ?>, stepShipping, stepPayment;
        var steps = opcConfig.components.checkout.children.steps.children;
        opcConfig.components.checkout.children.sidebar.config.template = 'Codazon_SalesPro/checkout/sidebar';
        try {
            opcConfig.components.checkout.children.sidebar.children.agreements = {};
            opcConfig.components.checkout.children.sidebar.children.agreements = steps['billing-step'].children.payment.children['payments-list'].children['before-place-order'].children.agreements;
        } catch(err) {
        }
        app(opcConfig, $('#checkout'));
    }); */ ?>
    var cdzOpcConfig = <?= $block->getJsLayout() ?>, stepShipping, stepPayment;
    var steps = cdzOpcConfig.components.checkout.children.steps.children;
    cdzOpcConfig.components.checkout.children.sidebar.config.template = 'Codazon_SalesPro/checkout/sidebar';
    try {
        cdzOpcConfig.components.checkout.children.sidebar.children.agreements = {};
        cdzOpcConfig.components.checkout.children.sidebar.children.agreements = steps['billing-step'].children.payment.children['payments-list'].children['before-place-order'].children.agreements;
    } catch(err) {
    }
    var cdzOpcScript = document.createElement('script');
    cdzOpcScript.type = 'text/x-magento-init';
    cdzOpcScript.textContent = '{"#checkout":{"Magento_Ui/js/core/app":'+ JSON.stringify(cdzOpcConfig) + '}}';
    document.querySelector('body').append(cdzOpcScript)
</script>
<?php if (isset($secureRenderer)) : ?>
<?php include ($block->getTemplateFile('Codazon_SalesPro::checkout/onepage-secure-renderer.phtml')) ?>
<?php else : ?>
<script>
    window.checkoutConfig = <?= $block->getSerializedCheckoutConfig() ?>;
    window.isCustomerLoggedIn = window.checkoutConfig.isCustomerLoggedIn;
    window.customerData = window.checkoutConfig.customerData;
</script>
<script>
    require([
        'mage/url',
        'Magento_Ui/js/block-loader'
    ], function(url, blockLoader) {
        blockLoader("<?= $block->escapeJs($block->escapeUrl($block->getViewFileUrl('images/loader-1.gif'))) ?>");
        return url.setBaseUrl('<?= $block->escapeJs($block->escapeUrl($block->getBaseUrl())) ?>');
    })
</script>
<?php endif ?>
<?php if (!((bool)$helper->getConfig('codazon_osc/customization/enable_discount_code'))) : ?>
<style>
.payment-option.discount-code .payment-option-title, .payment-option.discount-code .payment-option-content{display:none !important;}
</style>
<?php endif ?>
<script type="text/javascript">
var promoItems = [];
var frankeItems = [];

<?php foreach($quote->getAllVisibleItems() as $_item): ?>
    var isPromoItem = <?php echo in_array(206, $_item->getProduct()->getCategoryIds()) ? 'true' : 'false'; ?>;
    var containsFranke = <?php echo strpos($_item->getName(), 'Franke') !== false ? 'true' : 'false'; ?>;

    promoItems.push(isPromoItem);
    frankeItems.push(containsFranke);
<?php endforeach; ?>
window.promoItems = promoItems;
window.frankeItems = frankeItems;

And then I retrieve the data in a different file called apply-coupon.js which is a Mageplaza module so the file is located in a different folder but it still works. The apply-coupon.js file is below

/**

define([
‘ko’,
‘jquery’,
‘Magento_Checkout/js/model/quote’,
‘Mageplaza_Affiliate/js/model/resource-url-manager’,
‘Magento_Checkout/js/model/error-processor’,
‘Mageplaza_Affiliate/js/model/messageList’,
‘mage/storage’,
‘mage/translate’,
‘Magento_Checkout/js/action/get-payment-information’,
‘Magento_Checkout/js/model/totals’,
‘Magento_Checkout/js/model/full-screen-loader’,
‘Magento_Checkout/js/action/recollect-shipping-rates’,
‘Magento_Checkout/js/action/get-totals’,
‘Mageplaza_Affiliate/js/model/coupon’
], function (ko, $, quote, urlManager, errorProcessor, messageContainer, storage, $t, getPaymentInformationAction,
totals, fullScreenLoader, recollectShippingRates, getTotalsAction, couponModel
) {
‘use strict’;

return function (couponCode, isApplied) {
var quoteId = quote.getQuoteId(),
url = urlManager.getApplyAffiliateCouponUrl(couponCode, quoteId),
data = {},
headers = {};

fullScreenLoader.startLoader();

return storage.put(
url,
data,
false,
null,
headers
).done(function (response) {
var deferred;

if (response) {
deferred = $.Deferred();

isApplied(true);
couponModel.isLoading(true);
totals.isLoading(true);
recollectShippingRates();
if ($('body').hasClass('checkout-cart-index')) {
getTotalsAction([], deferred);
} else {
getPaymentInformationAction(deferred);
}
$.when(deferred).done(function () {
fullScreenLoader.stopLoader();
totals.isLoading(false);
couponModel.isLoading(false);

// Check for promotional or Franke products before showing message
var message = checkProductsForMessages();
if (message) {
messageContainer.addErrorMessage({'message': message});
} else {
messageContainer.addSuccessMessage({
'message': $t('Your affiliate coupon was successfully applied.')
});
}
});
}
}).fail(function (response) {
fullScreenLoader.stopLoader();
totals.isLoading(false);
couponModel.isLoading(false);
errorProcessor.process(response, messageContainer);
});
};

// Function to check for promo or Franke products and return appropriate message
function checkProductsForMessages() {
if (window.promoItems.includes(true)) {
return $t("Can't apply due to Franke/Promo product. Remove them to apply coupon");
}

if (window.frankeItems.includes(true)) {
return $t("Coupon can't be applied due to a Franke product in your cart.");
}

// No promotional or Franke products found, return null
return null;
}

});

Any advice on how to make the popup message change on the fly(without a page reload) would be greatly appreciated.