0

I am using LWC in a screen flow. I get a response from an API and need to bind that value in the lightning combo box. It's in the JSON array format. Here is the code.

JS

 import { 
    LightningElement,
    track,
    wire,
    api
     
} from 'lwc';

    import getCooridinatesFromPinCode from '@salesforce/apex/ChurchNearYouController.getCooridinatesFromPinCode';
    import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
    
    export default class ChurchNearYouComponent extends LightningElement {
        @api postalCode;
        @api selectedChurch;
        @track churchDropDown = [];
        @track value;
        
        @wire(getCooridinatesFromPinCode, { postalCode: '$postalCode'})
        wiredChurchList({ error, data }) {
            if (data) {
                console.log(data);
                this.churchDropDown = data;
            }
        }
    
        get churchList() {
            console.log('Get' + this.churchDropDown);
            return this.churchDropDown;
            /*return [
                { label: 'St James Piccadilly', value: '623055' },
                { label: 'St Anne Soho', value: '623058' },
                { label: 'St Paul Covent Garden', value: '623070' },
            ];*/
    
            //return [{"value":623055,"label":"St James Piccadilly"},{"value":623058,"label":"St Anne Soho"},{"value":623070,"label":"St Paul Covent Garden"},{"value":623065,"label":"St Martin-in-the-Fields"},{"value":823011,"label":"Guards Chapel of Wellington Barracks"}];
        }
    
        /*set churchList(val){
            console.log('Set' + val);
            this.churchDropDown = val;
        }*/
       
    
        handleChange(event) {
            const attributeChangeEvent = new FlowAttributeChangeEvent('selectedChurch', event.detail.value);
            this.dispatchEvent(attributeChangeEvent);
        }
    
    }

HTML

<lightning-combobox
    name="ChurchListSource" 
    label="Church" value={value}
    placeholder="-Select-"
    options={churchList} onchange={handleChange}>
</lightning-combobox>
<lightning-formatted-text value={churchList} ></lightning-formatted-text>

Apex

    /**
 * @description       : Class to get the church near by using latitude and longitude
 * @author            : Vetriselvan Manoharan
 * @last modified on  : 09-17-2021
 * @last modified by  : Vetriselvan Manoharan
**/
public class ChurchNearYouController {


    /**
    * @description Method to get the geolocation details using the postal codes
    * @author Vetriselvan Manoharan | 09-10-2021 
    * @param postalCode 
    **/
    @AuraEnabled(cacheable = true)
    public static String getCooridinatesFromPinCode(String postalCode){
        List<ChurchListWrapper> churchWrapperList = new List<ChurchListWrapper>();
        String ancyResults = '';
        Geolocation_API_Details__c geoLocation = Geolocation_API_Details__c.getOrgDefaults();
        String restAPIURL = geoLocation.Callout_URL__c;
        HttpRequest req = new HttpRequest();
        req.setMethod('GET'); 
        req.setEndpoint(restAPIURL+'/'+postalCode); 
        try 
        {  
            Http http = new Http();   
            HttpResponse httpResponse = http.send(req);  
            if (httpResponse.getStatusCode() == 200) 
            { 
                PostCodeIOWrapper postCodeResponse = (PostCodeIOWrapper) System.JSON.deserialize(httpResponse.getBody(), PostCodeIOWrapper.class);
                if(!Test.isRunningTest()) {
                    ancyResults = getChurchNearYou(postCodeResponse.result.latitude,postCodeResponse.result.longitude);
                    ANCYWrapper ancyResponse = (ANCYWrapper) System.JSON.deserialize(ancyResults, ANCYWrapper.class);   
                    //insertorUpdateChurchestoDiocese(ancyResponse.results);
                    churchWrapperList = getChurchListDropDown(ancyResponse.results);
                    System.debug('Church Wrapper List' + churchWrapperList);
                    System.debug(JSON.serialize(churchWrapperList));
                    return JSON.serialize(churchWrapperList);
                }
            } 
            else 
            {  
                System.debug(' httpResponse ' + httpResponse.getBody() );  
                throw new CalloutException( httpResponse.getBody() );
            } 
            return '';
        } 
        catch( System.Exception e) 
        {  
            System.debug('ERROR: '+ e);  
            throw e; 
        } 
    }

    /**
    * @description Method to get the churches near you using the geolocation
    * @author Vetriselvan Manoharan | 09-08-2021 
    * @param latitude 
    * @param longitude 
    **/
    public static String getChurchNearYou(Double latitude, Double longitude){
        ANCY_API_Details__c ancy = ANCY_API_Details__c.getOrgDefaults();
        String authToken = ancy.Access_token__c;
        String restAPIURL = ancy.Callout_URL__c;
        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', 'Token ' + authToken);
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Accept', '*/*');
        req.setMethod('GET');
        req.setEndpoint(restAPIURL+'?id=&is_church=true&church_reference=&is_school=&name=&country=&phone_number=&website_url=&updated_at=&filter_geo_lat='+latitude+'&filter_geo_lon='+longitude+'&filter_geo_radius=0.5');
        try 
        {  
            Http http = new Http();   
            HttpResponse httpResponse = http.send(req);  
            if (httpResponse.getStatusCode() == 200 ) 
            {  
                return httpResponse.getBody();
            } 
            else 
            {  
                throw new CalloutException( httpResponse.getBody() );  
            }   
        } 
        catch( System.Exception e) 
        {  
            System.debug('ERROR: '+ e);  
            throw e;  
        } 
    }

    /**
    * @description Insert or update church and relate to Diocese
    * @author Vetriselvan Manoharan | 09-15-2021 
    * @param ancyResponse 
    **/
    public static void insertorUpdateChurchestoDiocese( List<ANCYWrapper.results> ancyResponse ) {
        List<Church__c> churchList = new List<Church__c>();
        Map<String,Id> dioceseMap = new Map<String,Id>();

        // Get the list of dioceses
        if(Diocese__c.SObjectType.getDescribe().isAccessible()) {
            List<Diocese__c> dioceseList  = [ SELECT Id, ACNY_Id__c FROM Diocese__c ];
            for( Diocese__c diocese : dioceseList ) {
                dioceseMap.put(diocese.ACNY_Id__c,diocese.Id);
            }
        }

        for( ANCYWrapper.results ancy : ancyResponse ){
            Church__c churchToUpsert = new Church__c();
            churchToUpsert.Diocese__c = dioceseMap.get(String.valueOf(ancy.church.diocese));
            churchToUpsert.Name = ancy.church.name;
            churchToUpsert.ACNY_Id__c = String.valueOf(ancy.church.id);
            churchList.add(churchToUpsert);
        }

        // Insert or update the churches
        if(churchList.size() > 0 && Church__c.SObjectType.getDescribe().isAccessible()){
            Database.UpsertResult[] results = Database.upsert(churchList, Church__c.ACNY_Id__c);
            System.debug(results);
        } 
    }

    /**
    * @description 
    * @author Vetriselvan Manoharan | 09-17-2021 
    * @param ancyResponse 
    * @return List<ChurchListWrapper> 
    **/
    public static List<ChurchListWrapper> getChurchListDropDown( List<ANCYWrapper.results> ancyResponse ){
        List<ChurchListWrapper> churchWrapperList = new List<ChurchListWrapper>();
        for( ANCYWrapper.results ancy : ancyResponse ){
            ChurchListWrapper churchDropDown = new ChurchListWrapper();
            churchDropDown.label = ancy.church.name;
            churchDropDown.value = ancy.church.id;
            churchWrapperList.add(churchDropDown);
        }
        return churchWrapperList;
    }


    public class ChurchListWrapper {
        String label;
        Integer value;
    }
}

If I hard code the json array and return then it binding the combo-box but when returing the churchDropDown it is not working as expected. I can see the response in the text value but not getting binded on the dropdown.

Any help will be appreciated

2
  • please provide code of getCooridinatesFromPinCode apex method Sep 19 at 16:52
  • Yes, add the controller code.. It returns a JSON array! the method basically performs callout and get the response back.. I serialize the response Sep 19 at 18:18
1

The problem is that you are returning serialized String and assigning String to the js property. Js expecting to have here an array of JSON objects, but not just String.

You have two options.

  • deserialize returned String by getCooridinatesFromPinCode;
  • return not String with the serialization of the list of objects, but List<ChurchListWrapper>, lwc framework will do the rest for you.

I prefer the second option. Apex getCooridinatesFromPinCode should look like:

@AuraEnabled(cacheable = true)
public static List<ChurchListWrapper> getCooridinatesFromPinCode(String postalCode){
    List<ChurchListWrapper> churchWrapperList = new List<ChurchListWrapper>();
    String ancyResults = '';
    Geolocation_API_Details__c geoLocation = Geolocation_API_Details__c.getOrgDefaults();
    String restAPIURL = geoLocation.Callout_URL__c;
    HttpRequest req = new HttpRequest();
    req.setMethod('GET'); 
    req.setEndpoint(restAPIURL+'/'+postalCode); 
    try 
    {  
        Http http = new Http();   
        HttpResponse httpResponse = http.send(req);  
        if (httpResponse.getStatusCode() == 200) 
        { 
            PostCodeIOWrapper postCodeResponse = (PostCodeIOWrapper) System.JSON.deserialize(httpResponse.getBody(), PostCodeIOWrapper.class);
            if(!Test.isRunningTest()) {
                ancyResults = getChurchNearYou(postCodeResponse.result.latitude,postCodeResponse.result.longitude);
                ANCYWrapper ancyResponse = (ANCYWrapper) System.JSON.deserialize(ancyResults, ANCYWrapper.class);   
                //insertorUpdateChurchestoDiocese(ancyResponse.results);
                churchWrapperList = getChurchListDropDown(ancyResponse.results);
                System.debug('Church Wrapper List' + churchWrapperList);
                System.debug(JSON.serialize(churchWrapperList));
                return JchurchWrapperList;
            }
        } 
        else 
        {  
            System.debug(' httpResponse ' + httpResponse.getBody() );  
            throw new CalloutException( httpResponse.getBody() );
        } 
    } 
    catch( System.Exception e) 
    {  
        System.debug('ERROR: '+ e);  
        throw e; 
    } 
}

and make properties of your wrapper ChurchListWrapper class aura enabled

public class ChurchListWrapper {
    @AuraEnabled
    public String label {get; set;}
    @AuraEnabled
    public Integer value {get; set;}
}
1
  • that worked.. thank you! Sep 20 at 4:30

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.