function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andrew WolderAndrew Wolder 

response.getReturnValue() returns empty result when populated from public class.

Hi All,
    I am having an issue, which I haven't been able to solve.  in my Apex controller, I have a defined a public class as follows:
public class ContactsAndUser {
        public String userName      {get; set;}
        public String userEmail     {get; set;}
        public String userId        {get; set;}
        public String conImage      {get; set;}
        public String role          {get; set;}
    }

I am populating this class from a soql query into an array as follows ( The idea is to populate the List ContactList from users from the Case Object, Opportunity, User, and Contact Object to make a list of everyone associated wtih a deal ):

list<ContactsAndUser> contactList       = new list<ContactsAndUser>();  
              ContactsAndUser newUser = new ContactsAndUser();
              newUser.userEmail    = ownerInfo[0].Email;
              newUser.userName     = ownerInfo[0].Name;
              newUser.userId       = ownerInfo[0].Id;
              newUser.conImage     = ownerInfo[0].SmallPhotoUrl;
              newUser.role         = '[ Case Owner ]';
              contactList.add(newUser);  

When i debug the function (system.debug('LIGHTNING DEBUG ' + contactList);) I see a populated result in the logs, however, the result items are enclosed in [] square brackets instead of {}. i.e. LIGHTNING DEBUG (ContactsAndUser:[conImage=https://ciscosales--gve--c.xx.content.force.com/profilephoto/005/T, role=[ Case Owner ], userEmail=email=example.com@example.com, userId=00580000007IKULAA4, userName=Leads & Prospects Management Site Guest User])
 
In this example above, the response.getReturnValue() on my lightning event comes back empty.

If I run the same against the standard opportunity or case object as follows:

List<Opportunity> opportunities =
                [SELECT Id, Name, CloseDate FROM Opportunity];
        system.debug('LIGHTNING DEBUG ' + opportunities);
        return opportunities;
I notice the debug log returns the result encapulated in {} curly brackets instead of square brackets, and the result is returned in the response.getReturnValue() event.


Sorry for the very detailed description of the issue, but hoping for some input so I can get this working.

Best Regards,

Andrew
Best Answer chosen by Andrew Wolder
Akhil AnilAkhil Anil
Try adding @AuraEnabled to your class as below. Also, ensure that the method in which you are creating the contactList is  @AuraEnabled.
 
public class ContactsAndUser {

       @AuraEnabled

        public String userName      {get; set;}

        @AuraEnabled

        public String userEmail     {get; set;}

        @AuraEnabled

        public String userId        {get; set;}

        @AuraEnabled

        public String conImage      {get; set;}

        @AuraEnabled

        public String role          {get; set;}

    }

 

All Answers

Navee RahulNavee Rahul
Hi Andrew,

Thats the response return type of JSON and that is why results are encapsulated in that way with curly braces.

you can use the Json parsing for extraction of values.

please see below link.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsonparser.htm

 Thanks
D Naveen Rahul
Akhil AnilAkhil Anil
Can you paste your lightning component's snippet here ?
I mean the entire function that calls your apex controller, so that we can have a closer look.
Akhil AnilAkhil Anil
Try adding @AuraEnabled to your class as below. Also, ensure that the method in which you are creating the contactList is  @AuraEnabled.
 
public class ContactsAndUser {

       @AuraEnabled

        public String userName      {get; set;}

        @AuraEnabled

        public String userEmail     {get; set;}

        @AuraEnabled

        public String userId        {get; set;}

        @AuraEnabled

        public String conImage      {get; set;}

        @AuraEnabled

        public String role          {get; set;}

    }

 
This was selected as the best answer
Andrew WolderAndrew Wolder
Thanks All.  It now works great after AuraEnabling the Strings in the public class.  I appreaciate the help.

Andrew
Prashant Ahuja 14Prashant Ahuja 14
Thanks it worked for me also when I made @auraneabled for the public strings. 
srihari koyilasrihari koyila

my seinario is created contact is automatically appears in the component without refreshing the page using parent component contact list and child component is quick contact for create contacts 

and response.getReturnValue() returns undefined and its not  fire(); the event ........

quickcontact.cmp

<aura:component controller="contactlistcontroller">
  <aura:attribute name="accountId" type="string" />
    <aura:attribute name="ErrorMessage" type="string"/>
    
    
    <aura:registerEvent name="quickcontact" type="c:QuickEvent"/>
    
    <aura:attribute
    name="createcontact"
    type="contact"
    default="{sobjectName: 'Contact', FirstName: '',LastName: '', Email: '', Phone: '' }" />   
                                                           
  {!v.ErrorMessage}
  <div class="slds-p-around_small">
    <lightning:input
      type="text"
       aura:id="contactForm" messageWhenValueMissing=" please enter firstname"
      value="{!v.createcontact.FirstName}"
      label="FirstName"
      required="true"
    />
    <lightning:input
      type="text"
         aura:id="contactForm"   messageWhenValueMissing=" please enter lastname is required to save"          
      value="{!v.createcontact.LastName}"
      label="LastName"
      required="true"
    />
    <lightning:input
      type="Email"  
        aura:id="contactForm"
      value="{!v.createcontact.Email}"
      label="Email"
      required="true"
    />
    <lightning:input
         aura:id="contactForm"             
      type="Phone"
      value="{!v.createcontact.Phone}"
      label="Phone"
      required="true"
    />
    <br />

    <lightning:button
      label="create contact"
      variant="brand"
      onclick="{!c.doSave}"
    />
  </div>
</aura:component>

 

 

quickcontactcontriller.js

({
    doSave : function(component, event, helper) {
         alert('testing again')
        var action = component.get('c.createContact');
    
    action.setParams({
    con: component.get('v.createcontact'),
    AccountId: component.get('v.accountId')
    
});
   
     action.setCallback(this, function(response){
    
    var state=response.getState();
    alert(state);
        alert(responseValue)
    if(state ==='SUCESS' || state ==='DRAFT'){
       var responseValue = response.getReturnValue();
       var compEvent = cmp.getEvent("quickcontact");
        compEvent.setParams({
            contactRecord : responseValue 
        });
        compEvent.fire();
        
    }else if(state === 'INCOMPLETE'){
        
    }else if(state === 'ERROR'){
       alert('not save record')
        var errors = response.gerError();
        console.log('Error', errors[0].duplicateResults);
         console.log('Error', errors[0].fieldErrors);
         console.log('Error', errors[0].pageErrors[0].message);
         component.set('v.ErrorMessage', errors[0].pageErrors[0].message);
    }
    
  },'ALL');
      $A.enqueueAction(action);
        },
})

 

 

parent component as contactlist.cmp

<aura:component
  controller="contactlistcontroller"
  implements="force:hasRecordId,force:hassobjectName,flexipage:availableForAllpageTypes"
>
  <aura:attribute name="contactlist" type="contact[]" />

  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
 
<aura:handler name="quickcontact" event="c:QuickEvent"
    action="{!c.handlecompevent}"/>

  <div> <c:quickcontact accountId="{!v.recordId}" /> </div>

  <div class="slds-p-around_small">
    <div class="slds-grid slds-wrap">
      <aura:iteration items="{!v.contactlist}" var="con">
        <div class="slds-col slds-size_1-of-3">
          <lightning:card
            title="{!con.LastName}"
            footer="{!con.Email}"
            iconName="standerd:contact"
          >
            <aura:set attribute="actions">
              <lightning:button
                name="{!con.Id}"
                label="VIEW DETAILS"
                variant="brand"
                onclick="{!c.doredirect}"
              />
            </aura:set>

            <p class="slds-p-horizontal_small">
              {!con.FirstName} &nbsp;&nbsp;{!con.LastName} <br /> {!con.Phone}
            </p>
          </lightning:card>
        </div>
      </aura:iteration>
    </div>
  </div>
</aura:component>

 

contactlistcontrller.js

({
    doInit : function(component, event, helper) {
        var action=component.get('c.getcontactlist');
        action.setParams({
            accountId : component.get('v.recordId')
        });
    
    action.setCallback(this, function(response){
    
    var responseValue =response.getReturnValue();
    console.log('responseValue', responseValue);
    component.set('v.contactlist',responseValue);
});
     $A.enqueueAction(action,false);
},
    doredirect : function(component, event, helper) {
    
    var eventSource = event.getSource();
    var id = eventSource.get('v.name');
   
     var navEvt = $A.get("e.force:navigateToSObject");
    navEvt.setParams({
      "recordId": id,
      "slideDevName": "detail"
    });
    navEvt.fire();
    
},
    handlecompevent : function(component, event, helper) {
        alert('test')
         var availablecontact =component.get('v.contactlist');
        var contactRecord = event.getParam('contactRecord');
        console.log(contactRecord)
        availablecontact.push(contactRecord);
        component.set('v.contactlist' , availablecontact);
    }
    
})

 

and lightning event


    <aura:event type="COMPONENT" description="Event template" >
    
    
        <aura:attribute name="contactRecord" type="Contact" />
    
    </aura:event>