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
Michael Merino 1Michael Merino 1 

Return record fields to lightning controller

I need to grab a few fields from a custom account for my lightning componnet doInit method.  Currently I do about 4 apex calls and each returns a single field.  This approach is working fine.  But I would like the apex method to return the whole record .  this is not working
/////////////////////////////////////
@AuraEnabled
public static String getRoyaltyAccount(Id raId) {
        List<Royalty_Account__c> x = [Select r.Proposed_Email__c, r.Name, r.Id, r.Number__c, r.active__c From Royalty_Acct__c r where Id=:raId];
        String response = JSON.serialize(x);
        system.debug('### response '+response);
        return response; 
}
/////////////////////////////////////
10:08:31:014 USER_DEBUG [287]|DEBUG|### response [{"attributes":{"type":"Royalty_Acct__c","Name":"Al Hansen","Id":"a0t0v000001M","Number__c":"12345538836389","Email__c":"aa@aardvark.org","Phone_Type__c":"landline",
/////////////////////////////////////
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride" access="global" 
                controller="RoyaltyServicesController_RR"> 
    <aura:attribute name="record" type="Object" 
    <aura:attribute name="simpleRecord" type="Object" />
    <aura:attribute name="recordError" type="String" 
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div class="slds-clearfix">
        <div class="slds-float_right">
            <lightning:button label="Edit" variant="neutral" onclick="{!c.handleClick}"/>    
            <lightning:button label="Generate Cardless " aura:id="generateCardBtn" variant="neutral" onclick="{!c.generateCard1}" />
   
        </div>
    </div>
    
    <force:recordData aura:id="currentRecord"
                      recordId="{!v.recordId}"
                      targetRecord="{!v.simpleRecord}"
                      targetError="{!v.error}"
                      layoutType="FULL" 
                      recordUpdated="{!c.recordUpdated}" />

/////////////////////////////////////                      
doInit  : function(component, event, helper) {
        var action = component.get("c.getAcctRec");
        action.setParams({raId : component.get("v.recordId") });
        action.setCallback(this, function(a){
            var state = a.getState(); // get the response state
            if(state === 'SUCCESS') {
                var responseObj = JSON.parse(a.getReturnValue());
            component.set("v.simpleRecord",responseObj);
            /////////////NEXT LINE DOES NOT WORK /////////////////
        var pe = component.get("v.simpleRecord").fields.Proposed_Email__c.value; // uses RecordData
            }});
        $A.enqueueAction(action);
    } 
/////////////////////////////////////
here is what I see in Inspect on the responseObj
responseObj = "[{"attributes":{"type":"Royalty_Acct__c","Name":"Al ...

so the string is being returned into the controller I just need to know how to parse it to get the four fields
Deepak GulianDeepak Gulian
You can achieve the same without using an apex as well
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride" access="global" > 

    <aura:attribute name="record" type="Object" />
    <aura:attribute name="simpleRecord" type="Object" />
    <aura:attribute name="recordError" type="String" />
    
    <force:recordData aura:id="currentRecord"
                      recordId="{!v.recordId}"
                      targetRecord="{!v.record}"
                      targetFields="{!v.simpleRecord}"
                      targetError="{!v.recordError}"
                      layoutType="FULL"
                      fields="Id,Name,Proposed_Email__c,Number__c,Active__c" 
                      recordUpdated="{!c.recordUpdated}" />

                      <!-- DISPLAY INFORMATION -->
                      {!v.simpleRecord.Name}<br/>
                      {!v.simpleRecord.Proposed_Email__c}<br/>
                      {!v.simpleRecord.Number__c}<br/>
                      {!v.simpleRecord.Active__c}

</aura:component>

Note: Please correct typing errors in the code if there are any.

Thanks
DG
 

Michael Merino 1Michael Merino 1
Thank you, but I need these values to either hide or show some buttons on initialization.  
Michael Merino 1Michael Merino 1
Ok I figured it out.  On the doInit, you can't grab the RecordData value because it is asynchronous, which many websites explain.  BUT you can grab the record by going to a serverside apex class.  This code hides or reveals buttons based on field values. the helper class gets called by my doInit AND by the RecordData recordUpdated method.
//////////////////////////////
/////////////////////////////////////
APEX CLASS
        @AuraEnabled
    public static Map<Id, Roy_Acct__c> getOneRoyaltyAccount(Id raId) {
        return new Map<Id,Roy_Acct__c >([Select r.Proposed_Email__c, r.Name, r.Id, r.Account_Number__c, r.Proposed_Phone_Type__c, r.Proposed_Phone__c, r.active__c From Roy_Acct__c r where Id=:raId]);
    }
/////////////////////////////////////
10:08:31:014 USER_DEBUG [287]|DEBUG|### response [{"attributes":{"type":"Roy_Acct__c","Name":"Al Hansen","Id":"a0t0v000001M","Proposed_Phone_Type__c":"landline","Proposed_Email__c":"aa@aardvark.org"
/////////////////////////////////////
COMPONENT
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride" access="global" 
                controller="RoyaltyServicesController_RR"> 
    <aura:attribute name="record" type="Object" 
    <aura:attribute name="simpleRecord" type="Object" />
    <aura:attribute name="recordError" type="String" 
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div class="slds-clearfix">
        <div class="slds-float_right">
            <lightning:button label="Edit" variant="neutral" onclick="{!c.handleClick}"/>    
            <lightning:button label="Generate Cardless " aura:id="generateCardBtn" variant="neutral" onclick="{!c.generateCard1}" />
   
        </div>
    </div>
    
    <force:recordData aura:id="currentRecord"
                      recordId="{!v.recordId}"
                      targetRecord="{!v.simpleRecord}"
                      targetError="{!v.error}"
                      layoutType="FULL" 
                      recordUpdated="{!c.recordUpdated}" />

/////////////////////////////////////
CONTROLLER
    doInit : function(component, event, helper) {        
        var action = component.get("c.getOneRoyaltyAccount");
        action.setParams({raId : component.get("v.recordId") });
        action.setCallback(this, function(a){
            var state = a.getState(); // get the response state
            if(state === 'SUCCESS') {
                var royAcct = [];
                var responseValue = a.getReturnValue();
                for (var key in responseValue)
                {
                    royAcct.push({
                        Id: key,
                        name : responseValue[key].Name,
                        proposedEmail: responseValue[key].Proposed_Email__c,
                        proposedPhone: responseValue[key].Proposed_Phone__c,
                        proposedPhoneType: responseValue[key].Proposed_Phone_Type__c,
                        active: responseValue[key].Active__c,
                        accountNumber: responseValue[key].Account_Number__c
                    });
                }
                var name = royAcct[0].name;
                var pe = royAcct[0].proposedEmail;
                var pp = royAcct[0].proposedPhone;
                var ppt = royAcct[0].proposedPhoneType;
                var act = royAcct[0].active;
                var an = royAcct[0].accountNumber;
                
                helper.setButtons(component,pe,pp,ppt,act,an);                
            }});
        $A.enqueueAction(action);
    }
/////////////////////////////////////
HELPER
    setButtons : function(component,pe,pp,ppt,act,an){
        if(!pe || pe=="") // null or blank
        {
            $A.util.addClass(component.find("sendVerificationEmailBtn"), 'slds-hide');
            $A.util.addClass(component.find("verifyEmailAddressBtn"), 'slds-hide');
        } 
        else
        {
            $A.util.removeClass(component.find("sendVerificationEmailBtn"), 'slds-hide');
            $A.util.removeClass(component.find("verifyEmailAddressBtn"), 'slds-hide');
        }
        if(!pp || pp=="")
        {
            $A.util.addClass(component.find("sendVerificationCallBtn"), 'slds-hide');
            $A.util.addClass(component.find("verifyPhoneNumberBtn"), 'slds-hide');
        } 
        else
        {
            $A.util.removeClass(component.find("sendVerificationCallBtn"), 'slds-hide');
            $A.util.removeClass(component.find("verifyPhoneNumberBtn"), 'slds-hide');
        }
 
Deepak GulianDeepak Gulian
A more simplified version of what you trying to achieve is this
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride" access="global" > 

    <aura:attribute name="record" type="Object" 
    <aura:attribute name="simpleRecord" type="Object" />
    <aura:attribute name="recordError" type="String" 
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />


    
    <force:recordData aura:id="currentRecord"
                      recordId="{!v.recordId}"
                      targetRecord="{!v.record}"
                      targetFields="{!v.simpleRecord}"
                      targetError="{!v.error}"
                      layoutType="FULL"
                      fields="Id,Name,Proposed_Email__c,Proposed_Phone__c"
                       />

    <lightning:buttonGroup>
    	<lightning:button label="Send Email Verification" onclick="{!c.handleClick}" 
    					  disabled="{!is(empty({!v.simpleRecord.Proposed_Email__c}))" />
        <lightning:button label="Verify Email Address" onclick="{!c.handleClick}"
                          disabled="{!is(empty({!v.simpleRecord.Proposed_Email__c}))" />
        <lightning:button label="Send Call Verification" onclick="{!c.handleClick}"
                          disabled="{!is(empty({!v.simpleRecord.Proposed_Phone__c}))" />
        <lightning:button label="Verify Phone Number" onclick="{!c.handleClick}"
                          disabled="{!is(empty({!v.simpleRecord.Proposed_Phone__c}))" />
    </lightning:buttonGroup>

</aura:component>
Michael Merino 1Michael Merino 1
Yours works
            <lightning:button label="Generate Cardless Account" onclick="{!c.generateCard1}" 
                          disabled="{! !v.v.simpleRecord.Proposed_Email__c }"/>

but this code disables the button, whereas mine, though vastly more complex, removes the button, saving real estate.
Michael Merino 1Michael Merino 1
typo
 <lightning:button label="Generate Cardless Account" onclick="{!c.generateCard1}" 
                          disabled="{! !v.simpleRecord.Proposed_Email__c }"/>
Deepak GulianDeepak Gulian

You can use below any of 2

APPROACH 1

<aura:if isTrue="{!not(empty({!v.simpleRecord.Proposed_Email__c}))}">
    		<lightning:button label="Generate Cardless Account" 
                                           onclick="{!c.generateCard1}"  />
</aura:if>
APPROACH 2
<lightning:button label="Generate Cardless Account" onclick="{!c.generateCard1}" 
                          class="{!(empty(v.simpleRecord.Proposed_Email__c) ? 'slds-hide' : 'slds-show')}" />