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
Rahul AlladaRahul Allada 

Problem with invoking apex class in lightning AURA

Hi everyone, 

I am stuck up with calling APEX class from Aura init handler as i am new to AURA component. Can someone help me in finding where the error is:

CMP File
<aura:component implements="flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes" controller="SurveyController" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <div id="footermenu">
    <div class="slds-box show-for-tablet">
        <lightning:layout horizontalAlign="space" class="slds-p-top--xx-small">
            <lightning:layoutItem class="slds-size_1-of-3"> 
                <a href="/wal/s" id ="dashboard" class="" alternativeText="DASHBOARD" title="DASHBOARD"> 
                    <span class="fmcicon slds-avatar slds-avatar--medium"><img src="{!$Resource.iconfooternavDashboard}" class="slds-" alt="DASHBOARD"/></span><br/>
                    <span class="fmctext">DASHBOARD</span>
                </a>
            </lightning:layoutItem>
            <lightning:layoutItem class="slds-size_1-of-3">
                <a href="/wal/s/surveys" id ="surveys" alternativeText="SURVEYS" title="SURVEYS">
                    <span class="fmcicon slds-avatar slds-avatar--medium"><img src="{!$Resource.iconfooternavSurveys}" alt="SURVEYS"/></span><br/>
                    <span class="fmctext">SURVEYS</span>
                </a>
            </lightning:layoutItem>
            <lightning:layoutItem class="slds-size_1-of-3">
                <a href="/wal/s/resources" id ="resources" alternativeText="RESOURCES" title="RESOURCES">
                    <span class="fmcicon slds-avatar slds-avatar--medium"><img src="{!$Resource.iconfooternavResources}" alt="RESOURCES"/></span><br/>
                    <span class="fmctext">RESOURCES</span>
                </a>
            </lightning:layoutItem>

        </lightning:layout>
    </div>
    <div>

    </div>
</div>
</aura:component>


JS File
({
     doInit : function(component, event, helper) {
         console.log('Raahul Allada '+window.document.title);
         var status;
        var idd = $A.get("$SObjectType.CurrentUser.Id");
        var action = component.get("c.getStatusOfSurveys");
        console.log('Action is '+action);
        action.setParams({
            "userId": idd
        }); 
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state == 'SUCCESS') {
                 status = response.getReturnValue();
                console.log('Status is '+response.getReturnValue());
            }
        });
        console.log('Status of survey 1 is '+ status['MDD-Survey-1']);
        $A.enqueueAction(action);
    }
})


Apex class
public with sharing class SurveyController {
@AuraEnabled
    public static Map<string,boolean> getStatusOfSurveys(String userId){
      List<string> listOfSurveys = new List<string>{'MDD-Survey-1','MDD-Survey-2','MDD-Survey-3'};
      Map<string,boolean> surveyStatus = new Map<string,boolean>();
      List<User> users = [SELECT Id,contactId FROM User WHERE id = :userId];
        if(users != null)   {
            string accId = [SELECT Id, AccountId,Account.CreatedDate, Account.Name,Account.Current_wk__c,Account.Current_Wk_Session2__c,Account.GoalStartDate__c,Account.GoalStartDate_Session2__c FROM Contact WHERE id=:users[0].contactId]?.AccountId;
        if(accId != null){
          for( Advanced_Survey_Response__c surveyResponses : [SELECT id,PLM_User__c,Status__c,Advanced_Survey__r.Survey_Number__c FROM Advanced_Survey_Response__c WHERE PLM_User__c =: accId AND Advanced_Survey__r.Survey_Number__c IN: listOfSurveys]){ 
            boolean status = (surveyResponses.Status__c == 'Complete') ? True : False;
            surveyStatus.put(surveyResponses.Advanced_Survey__r.Survey_Number__c,status);
          }
        }     
    }
    return surveyStatus;
    }}
Apex class is working very fine. I am sure there is a problem with JS file only. Can someone help me in this?
Suraj Tripathi 47Suraj Tripathi 47
Hi Rahul,

"This is the sample code in which I call apex Controller."
This will help you. In this, I displayed account names as a 
picklist and on select account display related Contact and
Opportunity.
component------>
<aura:component controller="AccountRelatedObj"          implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.myAction}" />
    <aura:attribute name="AccountObj" type="List"/>
    <aura:attribute name="ChooseAccount" type="String"/>
    
    <aura:attribute name="ContactObj" type="List"/>
    <aura:attribute name="ChooseContact" type="String"/>
    
    <aura:attribute name="OpportunityObj" type="List"/>
    <aura:attribute name="ChooseOpportunity" type="String"/>
    
    <div class="slds-p-around_x-large">
        <H1>List Of Accounts</H1>
        <br/>
        <lightning:select name="acc" label="Select a Account:" value="{!v.ChooseAccount}" onchange="{!c.changeAction}">
            <aura:iteration items="{!v.AccountObj}" var="opt">
                <option text="{!opt.Name}" value="{!opt.Id}" selected="{!opt.selected}"/>
            </aura:iteration>
        </lightning:select>
        <br/><br/>
        <H2>List Of Related Contacts</H2><br/>
        <lightning:select name="con" label="Select a Contact:" value="{!v.ChooseContact}">
            <aura:iteration items="{!v.ContactObj}" var="opt">
                <option text="{!opt.LastName}" value="{!opt.LastName}" selected="{!opt.selected}"/>
            </aura:iteration>
        </lightning:select><br/><br/>
        <H3>List Of Related Opportunity</H3><br/>
        <lightning:select name="opp" label="Select a Opportunity:" value="{!v.ChooseOpportunity}">
            <aura:iteration items="{!v.OpportunityObj}" var="opt">
                <option text="{!opt.Name}" value="{!opt.LastName}" selected="{!opt.selected}"/>
            </aura:iteration>
        </lightning:select>
    </div>
    
</aura:component>
---->controller
({
    myAction : function(component, event, helper) {
        helper.showAccount(component, event, helper);
    },
    changeAction : function(component, event, helper){
        helper.showContact(component, event, helper);
        helper.showOpportunity(component, event, helper);
   
    }
})
------Helper
({
    showAccount : function(component, event, helper) {
        var action = component.get('c.fetchAccount');
        
        action.setCallback(this, function(actionResult) {
            component.set('v.AccountObj', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
    },
    
    showContact : function(component, event, helper) {
        var conAccID = component.get("v.ChooseAccount");
        
        var action = component.get("c.fetchContact");
        action.setParams({"acId": conAccID});
        action.setCallback(this, function(actionResult) {
            component.set('v.ContactObj', actionResult.getReturnValue()); 
        });
        $A.enqueueAction(action);
    },
    showOpportunity : function(component, event, helper) {
        var oppAccID = component.get("v.ChooseAccount");
        
        var action = component.get("c.fetchOpportunity");
        action.setParams({"acId": oppAccID});
        action.setCallback(this, function(actionResult) {
            component.set('v.OpportunityObj', actionResult.getReturnValue()); 
        });
        $A.enqueueAction(action);
    }
})
------>Apex Class
public class AccountRelatedObj {
    @auraEnabled
    public static List<Account> fetchAccount()
    {
        List<Account> accList=[SELECT Id,Name FROM Account LIMIT 10000];
        return accList;
    }
    @auraEnabled
    public static List<Contact> fetchContact(String acId)
    {
        List<Contact> conList=[SELECT Id,LastName,AccountId FROM Contact WHERE AccountId=:acId LIMIT 10000];
        return conList;
    }
    @auraEnabled
    public static List<Opportunity> fetchOpportunity(String acId)
    {
        List<Opportunity> oppList=[SELECT Id,Name,AccountId FROM Opportunity WHERE AccountId=:acId LIMIT 10000];
        return oppList;
    }
    
    
}
If you find your Solution then mark this as the best answer. 

Thank you!

Regards,
Suraj Tripathi