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
lxchlxch 

Return the values from Controller to the field in the <force:recordData /> 

Hi all, I'm working on get the current record with some fields (Name, Current_Balance__c) by <force:recordData /> in aura component. How do we get the value from Controller and update the record field?

Thanks!

Component
<aura:component controller="DueBalanceController" implements="force:lightningQuickAction,force:appHostable,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
   <aura:attribute name="accountRecord" type="Object"/>
   <aura:attribute name="sumBalance" type="Object"/>
   <aura:attribute name="today" type="Date" />
   <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    
    <force:recordData aura:id="recordLoader"
                      recordId="{!v.recordId}"
                      fields="Name,Current_Balance__c"
                      targetFields="{!v.accountRecord}"
                      /> 
    <div>
        <lightning:card aura:id="warning-box" title="Billing So-far" >
			<lightning:layout>
               <lightning:layoutItem class="slds-p-around_x-small" size="12">
                       <lightning:formattedNumber value="{!v.accountRecord.Current_Balance__c}"/></div>
               </lightning:layoutItem>
            </lightning:layout>
        </lightning:card>
    </div>
</aura:component>
Contorller.js
({
    init: function(component, event, helper) {
        var today = $A.localizationService.formatDate(new Date(), "YYYY-MM-DD");
        component.set('v.today', today);
        var accountRecord = component.get("v.accountRecord");
        var recordId = component.get ("v.recordId");      
        var action = component.get("c.sumBalance");
        action.setParams({recordId:recordId});
        action.setCallback(this, function(response){
            let state = response.getState();
            if (state === "SUCCESS") {
            component.set("v.sumBalance",response.getReturnValue());
            component.set("v.accountRecord.Current_Balance__c",sumBalance.bl);
            component.find("recordLoader").reloadRecord();
            } else {
                console.log("Failed with state: " + state);
            }
        });
        $A.enqueueAction(action);
    },
})

Apex Contorller
public with sharing class DueBalanceController{
    @AuraEnabled
    public static Object sumBalance (String recordId){
        Date d_today = system.Date.today();
        AggregateResult[] groupedResults = [
            SELECT SUM(Balance__c)bl,SUM(Paid_Total__c)pt,SUM(Billing_Total__c)bt, Tenant__c
            FROM Billing__c 
            WHERE Tenant__c	= :recordId AND (User_Due_Date__c <= :d_today OR Paid_Date__c <=:d_today) AND (Status__c='Unpaid' OR Status__c='Paid' OR Status__c='Captured' OR Status__c ='Chasing Overdue')
            GROUP BY Tenant__c
        ];
        return groupedResults[0];
       
    }
}



 
Best Answer chosen by lxch
lxchlxch

Hi Nayana,
Still the issue with formData. But I found a different solution to return the aggregatedResults into the record field in Apex Class. Since the aggregatedResults is calculated in Apex Class, I assigned and update within the same Class.

public with sharing class DueBalanceController{
    @AuraEnabled
    public static Object sumBalance (String recordId){
        Date d_today = system.Date.today();

// added this part. Keeping the record 
        Account acc = new Account();
        acc = [
            SELECT Id, Current_Balance__c
            FROM Account
            WHERE Id =:recordId
            LIMIT 1
        ];
//
      
        AggregateResult[] groupedResults = [
            SELECT   SUM(Balance__c)bl, SUM(Paid_Total__c)pt, SUM(Billing_Total__c)bt, Tenant__c
            FROM     Billing__c 
            WHERE    Tenant__c = :recordId AND (User_Due_Date__c <= :d_today OR Paid_Date__c <=:d_today) AND (Status__c='Unpaid' OR Status__c='Paid' OR Status__c='Captured' OR Status__c ='Chasing Overdue')
            GROUP BY Tenant__c
        ];  

// assigning the aggregatedResults value to the record       
        acc.Current_Balance__c = (Decimal)groupedResults[0].get('bl');
        update acc;
//        
        return groupedResults[0];      
        
    }
}

This demonstrated what I wanted to do. However, there should be a better way to do with Aura/LWC.  If you have any thought on this, please let me know!

All Answers

Nayana KNayana K
component.find("recordLoader").reloadRecord();

Above statement of reloadRecord will cause you to lose your current record, including any changes you’ve made.
Option1: 
Comment this line and check whether current balance is displayed as expected.

Option 2: (If Option 1 is not working)
<aura:component controller="DueBalanceController" implements="force:lightningQuickAction,force:appHostable,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
   <aura:attribute name="accountRecord" type="Object"/>
   <aura:attribute name="sumBalance" type="Object"/>
   <aura:attribute name="today" type="Date" />
   <!--aura:handler name="init" value="{!this}" action="{!c.init}"/-->
    
    <force:recordData aura:id="recordLoader"
                      recordId="{!v.recordId}"
                      fields="Name,Current_Balance__c"
                      targetFields="{!v.accountRecord}"
                      recordUpdated="{!c.recordUpdated}"
                      /> 
    <div>
        <lightning:card aura:id="warning-box" title="Billing So-far" >
			<lightning:layout>
               <lightning:layoutItem class="slds-p-around_x-small" size="12">
                       <lightning:formattedNumber value="{!v.accountRecord.Current_Balance__c}"/></div>
               </lightning:layoutItem>
            </lightning:layout>
        </lightning:card>
    </div>
</aura:component>
({
    
    recordUpdated : function(component, event, helper) {
 
              var changeType = event.getParams().changeType;
 
            if (changeType === "ERROR") { /* handle error; do this first! */ }
            else if (changeType === "LOADED") { /* handle record load */ 
              /*What I'm trying here?:
                    Once the record gets loaded, call the sumBalance and update the 
                 Current_Balance__c to reflect in the UI */
             */
                 var today = $A.localizationService.formatDate(new Date(), "YYYY-MM-DD");
                 component.set('v.today', today);
                 var accountRecord = component.get("v.accountRecord");
                 var recordId = component.get ("v.recordId");      
                var action = component.get("c.sumBalance");
                action.setParams({recordId:recordId});
                action.setCallback(this, function(response){
                 let state = response.getState();
                   if (state === "SUCCESS") {
                        component.set("v.sumBalance",response.getReturnValue());
                        component.set("v.accountRecord.Current_Balance__c",sumBalance.bl);
                     } else {
                        console.log("Failed with state: " + state);
                     }
                });
                 $A.enqueueAction(action);    
          }
    else if (changeType === "REMOVED") { /* handle record removal */ }
    else if (changeType === "CHANGED") { 
      
    }
})



 
lxchlxch
Hi Nayana, thanks for your adivce!
I tried both options but it says 
Uncaught Error in $A.getCallback() [sumBalance is not defined]
Callback failed: apex://DueBalanceController/ACTION$sumBalance
I also set random number '555555' in set, but it doesn' update the Current Balance field either.
component.set("v.accountRecord.Current_Balance__c",5555555);
Still looking around the soluton. Anyway thank you for your advice, I'll try a few more tests with your codes, and report back here.
 
lxchlxch

Hi Nayana,
Still the issue with formData. But I found a different solution to return the aggregatedResults into the record field in Apex Class. Since the aggregatedResults is calculated in Apex Class, I assigned and update within the same Class.

public with sharing class DueBalanceController{
    @AuraEnabled
    public static Object sumBalance (String recordId){
        Date d_today = system.Date.today();

// added this part. Keeping the record 
        Account acc = new Account();
        acc = [
            SELECT Id, Current_Balance__c
            FROM Account
            WHERE Id =:recordId
            LIMIT 1
        ];
//
      
        AggregateResult[] groupedResults = [
            SELECT   SUM(Balance__c)bl, SUM(Paid_Total__c)pt, SUM(Billing_Total__c)bt, Tenant__c
            FROM     Billing__c 
            WHERE    Tenant__c = :recordId AND (User_Due_Date__c <= :d_today OR Paid_Date__c <=:d_today) AND (Status__c='Unpaid' OR Status__c='Paid' OR Status__c='Captured' OR Status__c ='Chasing Overdue')
            GROUP BY Tenant__c
        ];  

// assigning the aggregatedResults value to the record       
        acc.Current_Balance__c = (Decimal)groupedResults[0].get('bl');
        update acc;
//        
        return groupedResults[0];      
        
    }
}

This demonstrated what I wanted to do. However, there should be a better way to do with Aura/LWC.  If you have any thought on this, please let me know!
This was selected as the best answer
shivam sharma 121shivam sharma 121
@Nayana K  mam, can you please connect with me on mail i have seen your blog form some refference but i am getting error I need some help in that please connect me on mail shivam.sharma@minditsystems.com