1

My requirement is to display all the saved values on load for a Custom object called Company__c. Fields being Full_Name__c (text), Address__c(text area) , Director_Name__c (text), Phone__c (phone) and Additional_Information__c(text).

At present iteration is happening correctly and I can view inserted records via console.log in helper and system.debug in backend. However all the records getting displayed are empty with just one display button.

My research online apart from internal debugging is :- lightning aura iteration returning blank rows

https://developer.salesforce.com/forums/?id=906F0000000BJwAIAW

Apex returning rows but no data

Followed this example:- where similar functionality is done for contact object(this is working in my local org as expected) . https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_one_demo_load.htm

My Component code is as :- CompanyInfo.cmp

      <aura:component     implements="force:hasRecordId,           
 force:appHostable , flexipage:availableForRecordHome" 
            controller="CompanyController">
      <aura:registerevent name="forceNavig2Component" 
      type="force:navigateToComponent"/> 
<aura:attribute name="Companies" type="Company__c"/>

    <!-- Handle component initialization in a client-side controller -->
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

<!-- SHOW LOADING SPINNER--> 
<lightning:spinner variant="brand" size="large"       aura:id="Id_spinner"   
     class="slds-hide" />

 <!-- Attribute declaration -->
<aura:attribute name="companyObj" type="Company__c" default="    { 
'sobjectType': 'Company__c' ,'Name':'','Full_Name__c':'', 
  'Director_Name__c':'','Address__c':'','Phone__c':''}"/>


     <div class="slds-grid">
    <lightning:card title="New Record" footer="Click on Save button     to 
       create new Record.">
        <!-- Save button -->
        <aura:set attribute="actions">
            <lightning:button aura:id="saveId"
                              label="Save"   
                              onclick="{!c.doSave}"/>
        </aura:set>
        <!--/ Save button -->

        <!-- Body -->
        <p class="slds-p-horizontal_small">
            <lightning:input aura:id="CompanyName"
                             label="Company Name"
                             type="String"
                             required="true"
                             value="{!v.companyObj.Name}"/>
            <lightning:input aura:id="CompanyFullName"
                             label="Full Name"
                             type="String"
                             required="true"
                             value="{!v.companyObj.Full_Name__c}"/>
                <lightning:input aura:id="CompanyDirector"
                             label="Director Name"
                             type="String"
                                 required="true"
                             value="{!v.companyObj.Director_Name__c}"/>
                <lightning:input aura:id="CompanyAddress"
                             label="Address"
                                 required="true"
                             type="String"
                             value="{!v.companyObj.Address__c}"/>
            <lightning:input aura:id="CompanyPhone"
                             label="Phone No"
                             type="Number"
                             required="true"
                             value="{!v.companyObj.Phone__c}"/>
        </p>
        <!--/ Body -->
    </lightning:card>


 </div>

 <aura:iteration var="Company" items="{!v.Companies}">
            <!-- If you’re using a namespace, replace with                                       
       myNamespace:contacts-->
            <c:Companies Company="{!Company}"/>
        </aura:iteration>


 </aura:component>

Referred Component code for Companies.cmp is :-

   <aura:component>
     <aura:attribute name="Company" type="Company__c" />

    <lightning:card variant="Narrow" title="{!v.Company.Name}"                     
     iconName="standard:contact" >
        <aura:set attribute="actions">
            <lightning:button name="details" label="Details" onclick="              
          {!c.goToRecord}" />
        </aura:set>    
        <aura:set attribute="footer">
            <lightning:badge label="{!v.Company.Name}"/>
        </aura:set>
        <p class="slds-p-horizontal_small">
            {!v.Company.Name}
        </p>
        <p class="slds-p-horizontal_small">
            {!v.Company.Full_Name__c}
        </p>
          <p class="slds-p-horizontal_small">
            {!v.Company.Address__c}
        </p>
        <p class="slds-p-horizontal_small">
            {!v.Company.Director_Name__c}
        </p>
    </lightning:card>

     </aura:component>

Contoller code for main component is CompanyListController.js

({
  doInit : function(component, event, helper) {
    // Retrieve contacts during component initialization
    // 
    console.log("inside init function for loading companies")
    helper.loadCompanies(component,event, helper);
  },
  doSave : function(component, event, helper) {
/ ** Server side controller calling logic. **/

    //Calling server side controller's saveCompany() method.
    var action = component.get("c.saveCompany");
    //console.log(action);
    //
    //Set method parameter of saveCompany() method.
    action.setParams({"company":                                                                      
      component.get("v.companyObj")});

     action.setCallback(this, function(response){
        console.log('inside callback');
        //<response.getState()> return response status as                              
      SUCCESS/ERROR/INCOMPLETE etc.
        var state = response.getState();
        console.log("response state is"+ state);
        //If response from server side is <SUCCESS>, then we will                    
     display a success message.
        if (state === "SUCCESS"){
            //Success message display logic.
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "Success!",
                "message": "Company record has been inserted                               
         successfully."
            });
            toastEvent.fire();
        }else if (state === "INCOMPLETE") {
            //Offline message display logic.
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "OFFLINE!",
                "message": "You are in offline."
            });
            toastEvent.fire();
        }else if (state === "ERROR") {
            //Error message display logic.
            var errors = response.getError();
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "ERROR!",
                "message": errors[0].message
            });
            toastEvent.fire();
        }else {
            //Unknown message display logic.
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "UNKOWN!",
                "message": "Unknown error."
            });
            toastEvent.fire();
        }
    });

    $A.enqueueAction(action);
    }
   })

Helper code is as follows:-

  ({
    loadCompanies : function(component,event, helper) {
     // show spinner message
     component.find("Id_spinner").set("v.class" , 'slds-show');
     // Load all contact data
     var action = component.get("c.getCompanies");
     action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
             // show spinner message
        component.find("Id_spinner").set("v.class" , 'slds-hide');
            var data = JSON.stringify(response.getReturnValue());
            console.log(data)
            component.set("v.Companies", data);
            console.log(component.get("v.Companies"));
            //var val = JSON.stringify(response.getReturnValue());
            //console.log("return value is "+val);
        }

        // Display toast message to indicate load status
        var toastEvent = $A.get("e.force:showToast");
        if (state === 'SUCCESS'){
            toastEvent.setParams({
                "title": "Success!",
                "message": " Your contacts have been loaded                                
        successfully."
            });
        }
        else {
            toastEvent.setParams({
                    "title": "Error!",
                    "message": " Something has gone wrong."
            });
        }
        toastEvent.fire();
    });
     $A.enqueueAction(action);
 }
      })

Apex class is as follows:-

  public with sharing class CompanyController {

   @AuraEnabled
  public static void saveCompany(Company__c company){
     INSERT company;
   }

 @AuraEnabled
 public static List<Company__c> getCompanies() {
    List<Company__c> companies = 
            [SELECT Name,       Full_Name__c, Address__c,                              
Director_Name__c FROM Company__c];
 system.debug(companies);
    //Add isAccessible() check
    return companies;
  }
 }
1

The attribute needs to be a list:

<aura:attribute name="Companies" type="Company__c[]"/>

... or ...

<aura:attribute name="Companies" type="List" />

The return data must not be stringified:

component.find("Id_spinner").set("v.class" , 'slds-hide');
var data = response.getReturnValue();
component.set("v.Companies", data);

Evetyhing else is probably okay, but there's a lot of code here, so I may have missed something.

| improve this answer | |
  • Thanks sfdcfox, stringify removal worked. However i am curious on front end data is only visible with stringify in place. Thanks again. – Mayank Parnami May 12 '19 at 14:33
  • @MayankParnami I didn't understand your question? – sfdcfox May 12 '19 at 14:36
  • When i was writting console.log(response.getReturnValue()); it was showing [object object] [object object] and not the exact value on console. Hence, my question is while displaying, how it works without syltringify – Mayank Parnami May 12 '19 at 14:40
  • 1
    @MayankParnami If you do something like console.log('return value is: '+data), it calls toString(), which for an object returns [object Object]. If you want to log a value to the console, do not use the + operator in order to examine the data. – sfdcfox May 12 '19 at 14:46
  • Makes perfect sense. Thanks a lot – Mayank Parnami May 12 '19 at 15:14

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.