How to update the records with a button in salesforce lightning


Apex class
==========
public class AccountController
{
    @AuraEnabled
    public static Account getAccountData(String AccountId){
        Account acc= [select Id,Name,Site from Account where Id=:AccountId];
        return acc;
    }
    @AuraEnabled
    public static Account updateSite(Account acc){
        acc.site='Approved by brahmanaidu as per the comments';
try{
update acc;
}
catch(Exception e){
throw new auraHandledException('unable to update the record due to'+e.getMessage());
}
        return acc;
    } 
}

component
=========
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global"
                            controller="AccountController" >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="account" type="Account" default="{'sobjectType':'Account'}"/>
    <lightning:button label="Approve"  onclick="{!c.updateStatus}"/>
 </aura:component>   

controller
==========
({
   doInit : function(component, event, helper)
   {
        var action = component.get("c.getAccountData");
        action.setParams({
AccountId:component.get("v.recordId")
           
        });
        action.setCallback(this, function(response){
    var state=response.getState();
if(state==='SUCCESS'){
component.set("v.account",response.getReturnValue());
}
else if(state==='ERROR'){
var error=response.getError();
console.log('Error in fetching the data'+error[0].message);
}
        });
        $A.enqueueAction(action);
    },
    updateStatus:function(component,event,helper)
    {
        var action=component.get('c.updateSite');
        action.setParams({
           acc:component.get("v.account")
        });
        action.setCallback(this,function(response){
var state=response.getState();
if(state==='SUCCESS'){
component.set("v.account",response.getReturnValue());
$A.get('e.force:refreshView').fire();
var dismissActionPanel = $A.get("e.force:closeQuickAction");
dismissActionPanel.fire();
}
else if(state==='ERROR'){
var error=response.getError();
console.log('Error in updating the data'+error[0].message);
}
        });
        
        $A.enqueueAction(action);
    }
})

Comments

  1. I actually still cannot quite believe I could always be
    one of those reading through the important tips found on this blog.
    My family and I are really thankful on your generosity and for giving me the advantage
    to pursue the chosen profession path. Thank you for the important information I got
    from your web-site.

    ReplyDelete
  2. BOFC application helps user to create up to 500 fields of different field types, in duration of 10-15 min, in a single go. It will reduce manual effort of users & will increase productivity. Read More

    ReplyDelete

Post a Comment