How to update a field value with a button in Salesforce Lightning

Apex class
-----------
public class updateSiteAC {
    @AuraEnabled
    public static list < Account > fetchAccount() {
       return [SELECT Id, name,site from Account Limit 10];
    }
   
     @AuraEnabled
    public static void updateRecord(List < String > lstRecordId) {
        List<account> lstAccToUpdate = new List<account>();
        for(account acc : [select id,Name,site from account where id IN : lstRecordId]){
            acc.site = 'Approved';
            lstAccToUpdate.add(acc);
        }
       
        if(lstAccToUpdate.size() > 0){
            update lstAccToUpdate;
        }
       
    }
}
Basic1.cmp
----------
<aura:component controller="updateSiteAC">
 
    <aura:attribute name="ListOfAccount" type="list" />
 
    <aura:handler name="init" value="{!this}" action="{!c.loadAccountList}"/>
   
    <div class="slds-grid slds-grid--align-end">
        <button class="slds-button slds-button--brand" onclick="{!c.upadateSite}">Update site</button>
    </div>
   
   
    <table class="slds-table slds-table--bordered slds-table--cell-buffer">
        <thead>
            <tr class="slds-text-title--caps">
                <th style="width:3.25rem;" class="slds-text-align--right">
                    <div class="slds-form-element">
                        <div class="slds-form-element__control">
                            <label class="slds-checkbox">
                                <!--header checkbox for select all-->
                                <ui:inputCheckbox aura:id="box3" change="{!c.selectAll}"/>
                                <span class="slds-checkbox--faux"></span>
                                <span class="slds-form-element__label text"></span>
                            </label>
                        </div>
                    </div>
                </th>
                <th>
                    <span class="slds-truncate">ID</span>     
                </th>
                <th>
                    <span class="slds-truncate">Name</span>
                </th>
                <th>     
                    <span class="slds-truncate">Site</span>
                </th>
            </tr>
        </thead>
       
        <tbody>
            <aura:iteration items="{!v.ListOfAccount}" var="acc">
                <tr>
                    <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                        <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                <label class="slds-checkbox">
                                    <ui:inputCheckbox text="{!acc.Id}" aura:id="boxPack" value=""/>
                                    <span class="slds-checkbox--faux"></span>
                                    <span class="slds-form-element__label text"></span>
                                </label>
                            </div>
                        </div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!acc.Id}"><a>{!acc.Id}</a></div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!acc.Name}">{!acc.Name}</div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!acc.Site}">{!acc.Site}</div>
                    </td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>


controller code
----------------
({
    loadAccountList: function(component, event, helper) {
        helper.onLoad(component, event);
    },
   
   
   
    selectAll: function(component, event, helper) {
       
        var selectedHeaderCheck = event.getSource().get("v.value");
        var getAllId = component.find("boxPack");
        if(! Array.isArray(getAllId)){
            if(selectedHeaderCheck == true){
                component.find("boxPack").set("v.value", true);   
            }else{
                component.find("boxPack").set("v.value", false);
            }
        }else{
            // check if select all (header checkbox) is true then true all checkboxes on table in a for loop 
            // and set the all selected checkbox length in selectedCount attribute.
            // if value is false then make all checkboxes false in else part with play for loop
            // and select count as 0
            if (selectedHeaderCheck == true) {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", true);
                }
            } else {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", false);
                }
            }
        } 
       
    },
   
   
    upadateSite: function(component, event, helper) {
       
        var updateId = [];
       
        var getAllId = component.find("boxPack");

        if(! Array.isArray(getAllId)){
            if (getAllId.get("v.value") == true) {
                updateId.push(getAllId.get("v.text"));
            }
        }else{

            for (var i = 0; i < getAllId.length; i++) {
                if (getAllId[i].get("v.value") == true) {
                    updateId.push(getAllId[i].get("v.text"));
                }
            }
        }
       
        helper.SelectedHelper(component, event, updateId);
       
    },
   
})



Helper
------

({
    onLoad: function(component, event) {
        var action = component.get('c.fetchAccount');
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.ListOfAccount', response.getReturnValue());
                component.find("box3").set("v.value", false);
            }
        });
        $A.enqueueAction(action);
    },
   
    SelectedHelper: function(component, event, RecordsIds) {
       
        var action = component.get('c.updateRecord');
        action.setParams({
            "lstRecordId": RecordsIds
        });
        action.setCallback(this, function(response) {
           
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log(state);
                this.onLoad(component, event);
            }
        });
        $A.enqueueAction(action);
    },
})

Lightning application
----------------------
<aura:application extends="force:slds" >
    <c:Basic1/>
</aura:application>



































































Comments

  1. Hello! Tһis post couldn't Ƅe wrіtten any bettеr! Reading thiѕ post reminds mе
    off my gooⅾ oⅼԁ room mate! He always kept talking about tһis.
    I willl forward tһis ԝrite-uр to him. Fairly certain hhe will
    hafe a good read. Thamk yоu for sharing!

    ReplyDelete
  2. Hi, its good article regarding media ⲣrint, we аll be familiar ѡith media is a fantastic source of facts.

    ReplyDelete
  3. Heⅼlo there! I knoѡ thіs is kinda off topic ƅut Ι'd figured Ӏ'ⅾ asқ.
    Would you be intereѕted in trading ⅼinks or
    mаybe guest authoring а blolg post or vice-versa?

    My website addresses а lot of the ѕame topics аs yօurs ɑnd І think we could greɑtly
    benefit fгom eacһ other. If yοu happеn to bee іnterested feel free tߋ send me an email.
    I look forward tο hearing frօm you! Wonderful blog Ьy
    the way!

    ReplyDelete
  4. Great blog here! Additionally your website rather a lot up very fast!
    What web host are you the use of? Can I get your associate link
    in your host? I wish my site loaded up as quickly as yours lol

    ReplyDelete
  5. I always spent my half an hour to read this webpage's content every day along
    with a mug of coffee.

    ReplyDelete
  6. Link exchange is nothing else except it is just placing the other person's blog link on your page at
    appropriate place and other person will also do similar for you.

    ReplyDelete
  7. Thank you foг tһe auspicious writeup. Іt іn rezlity waѕ oncе a entertainment
    account іt. Glance complex tо more аdded agreeable fгom ʏоu!

    By thhe ᴡay, hhow can wе keep սp a correspondence?

    ReplyDelete
  8. May I simply say what a relief to find an individual who genuinely understands
    what they're discussing on the web. You definitely understand how to
    bring a problem to light and make it important.
    A lot more people must check this out and understand this side of
    the story. I was surprised that you are not more popular because you definitely possess the gift.

    ReplyDelete
  9. I am really loving the theme/design of your weblog.
    Do you ever run into any internet browser compatibility problems?

    A number of my blog readers have complained about my website not working correctly in Explorer but looks great in Firefox.

    Do you have any suggestions to help fix this issue?

    ReplyDelete
  10. Hi there, the whole thing is going fine here and ofcourse every one is sharing
    data, that's actually fine, keep up writing.

    ReplyDelete
  11. There is definately a great deal to learn about this topic.
    I love all the points you made.

    ReplyDelete

Post a Comment