0

In Magento 2 I try to get shipping method in this js file : vendor/magento/module-checkout/view/frontend/web/template/billing-address.html

I try this :

quote.shippingMethod()['method_code'];

And I have this error :

Uncaught TypeError: Cannot read property 'method_code' of null

But when I console.log(quote); I can see shippingMethod method code exist: enter image description here

Do you have any idea how can I get shipping method attributes here ?

Thank you

EDIT

My goal is to change data-bind in this file : /vendor/magento/module-checkout/view/frontend/web/template/billing-address.html

<fieldset class="fieldset" data-bind="visible: !isAddressDetailsVisible()">

In order that isAddressDetailsVisible() method return false if current shipping method is "colissimo pickup".

  • What do you see if you add console.log(quote.shippingMethod())? – Ben Crook Sep 15 at 14:57
  • @BenCrook I see "null" – Fbr Sep 15 at 15:02
  • It sounds like your code is running before the shipping method is set (in code, not necessarily by the user). Have you tried subscribing to quote.shippingMethod then running your code when it updates? Off the top of my head I think it would be quote.shippingMethod.subscribe(function(value) { console.log(value); }) – Ben Crook Sep 16 at 8:48
  • Thanks it seems to work (I had to add code in initObservable function). But I have to refresh page, it doesn't work on the first page load. Do you know why ? – Fbr 8 hours ago
  • It still sounds like your code is running before the value is populated, once the user loads the page that value gets populated (possibly server side and then passed to the component). It's hard to say without being able to debug. – Ben Crook 7 hours ago
0

Try a simple way:

quote.shippingMethod().method_code

Where quote is 'Magento_Checkout/js/model/quote'

Avoiding js error, try the following way:

if (quote.shippingMethod() != undefined) {
    quote.shippingMethod().method_code
}

[Update]

Add the following code in your js class inside initialize method. Ex. view/frontend/web/js/view/billing-address.js initialize

quote.shippingMethod.subscribe(function (method) {
    if (method.method_code == 'your_method_code') {
        this.isAddressDetailsVisible(true);
    }
}, this);
| improve this answer | |
  • Thanks but I have this error : Uncaught TypeError: Cannot read property 'method_code' of null. You can see my edit I add more information about what I want. – Fbr Sep 15 at 14:29
  • Check the updated answer – Sohel Rana Sep 15 at 15:46
  • Thanks it seems to work (I had to add code not in initialize but in initObservable function). But I have to refresh page, it doesn't work on the first page load. Do you know why ? – Fbr 8 hours ago

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.