5

Please provide a proper way to call this method from LWC passing date parameter.

public with sharing class ApexClass {
    @AuraEnabled(cacheable = true) 
    public Date string apexMethod(Date z) {
        return z;
    }
}

We got date type in aura component for this situation. Any such way in LWC?

2 Answers 2

4

Hi i have used following code -

APEX Class -

  @AuraEnabled(cacheable=true)
    public static Date getDate(Date dt)
    {
        System.Debug('dt '+dt);
        return dt;

    }

and JS Code -

@wire(getDate,{dt:"2019-12-31"})
   date({data})
  { if(data){
      console.log("Data"+JSON.stringify(data));
  }
} 

or

 @wire(getDate,{dt:new Date("2019-12-31")})
    date({data})
   { if(data){
       console.log("Data"+JSON.stringify(data));
   }

    } 

And for My understanding, the date parameter accepts in YYYY-MM-DD format.

2
  • 1
    I feel really great to know Date is accepting 'YYYY-MM-DD' format. Thank you so much Jan 23, 2020 at 12:56
  • Could you give DateTime format as well? Jan 23, 2020 at 13:04
2

The first thing is your apex method return value is wrong. Your method expect a string value to return but you are returning a date value.

The correct code is:-

@AuraEnabled(cacheable = true) 
public static string apexMethod(Date z) {
    return String.valueOf(z);
}

Now, to call it from LWC, You can pass a date object value as parameter from JavaScript code:-

import { LightningElement } from 'lwc';
import apexMethod from '@salesforce/apex/ContactController.apexMethod';

export default class CurrencyInputField extends LightningElement {
     handleChange() {
        var d = new Date();
        apexMethod({ z: d })
            .then(result => {
                JSON.stringify('result ' + result);
            })
            .catch(error => {
                JSON.stringify('error ' + error);
            });
    }
}

Learn more about how to create a date instance in JavaScript here:-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

and calling an apex method in LWC here:- https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.apex

1
  • I tried yesterday, wire decorator was not calling the method. Now it's working wonder why. Anyway thanks for the answer and question fix. @sanket kumar Jan 23, 2020 at 12:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .