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
Frank van Meegen 42Frank van Meegen 42 

Lightning component Toggle Checbox field update

Hi,

I'm a bit stuck with a toggle checkbox in a lighting component datatable that should reflect a checkbox on the sobject (Contact.Active__c) in the datatable and update the specific checkbox when changed.

The datatable is a list of contacts related to the account that is opened in the screen. I would like to achieve the following scenarios:
  1. When the datatable is loaded the Toggle checkboxes in the SWITCH pane should reflect the true or false checkbox in the ACTIVE pane
  2. When the toggle checkbox is switched this should update the ACTIVE checkbox on the contact record to reflect the switched toggle checkbox
I cannot find a good example how to achieve this. Unfortunately the documentation regarding the ui:inputCheckbox is limited. I hope someone can help me with examples.

User-added image

APEX Controller
public class AccountsController1 {
    @AuraEnabled
    public static List <Contact> getAccounts(String aid) {
        system.debug('aid: ' +aid);
        List <Contact> Contacts = [SELECT Id, name,Email,Phone,Active__c  FROM Contact where AccountId=:aid ORDER BY createdDate ASC];
        System.debug('Contacts: ' +Contacts);
        return Contacts;
    }
}
Lightning component
<aura:component controller="AccountsController1" Implements="flexipage:availableForRecordHome,force:hasRecordId" >
    
    <aura:attribute name="contacts" type="List" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <!-- Use a data table from the Lightning Design System: https://www.lightningdesignsystem.com/components/data-tables/ -->
    <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
        <thead>
            <tr class="slds-text-heading_label">
                <th scope="col"><div class="slds-truncate" title="ID">ID</div></th>
                <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
                <th scope="col"><div class="slds-truncate" title="Email">Email</div></th>
                <th scope="col"><div class="slds-truncate" title="Phone">Phone</div></th>
                <th scope="col"><div class="slds-truncate" title="Active__c">Active</div></th>
                <th scope="col"><div class="slds-truncate" title="Switch">Switch</div></th>
                
            </tr>
        </thead>
        <tbody>
            <!-- Use the Apex model and controller to fetch server side data -->
            <aura:iteration items="{!v.contacts}" var="contact">
                <tr>
                    <th scope="row"><div class="slds-truncate" title="{!contact.Id}">{!contact.Id}</div></th>
                    <td><div class="slds-truncate" title="{!contact.Name}">{!contact.Name}</div></td>
                    <td><div class="slds-truncate" title="{!contact.Email}">{!contact.Email}</div></td>
                    <td><div class="slds-truncate" title="{!contact.Phone}">{!contact.Phone}</div></td>
                    <td><div class="slds-truncate" title="{!contact.Active__c}">{!contact.Active__c}</div></td>
                    <td>
                        <div class="slds-m-around--large">
                            <!--PART 1 for create toggle switch/checkbox form element-->    
                            <div class="slds-form-element">
                                <label class="slds-checkbox_toggle slds-grid">
                                    <span class="slds-form-element__label slds-m-bottom_none"></span>
                                    <ui:inputCheckbox change="{!c.selectChange}"/>
                                    
                                    <span id="toggle-desc" class="slds-checkbox_faux_container" aria-live="assertive">
                                        <span class="slds-checkbox_faux"></span>
                                        <span class="slds-checkbox_on">Active</span>
                                        <span class="slds-checkbox_off">Inactive</span>
                                    </span>
                                    
                                </label>
                            </div>
                            
                        </div>
                        
                    </td>
                    
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>

Lightning Component Controller
({
      doInit: function(component, event, helper) {
        // Fetch the account list from the Apex controller
        helper.getContactList(component);
      }
})
Lightning Component Helper
({
// Fetch the accounts from the Apex controller
      getContactList: function(component) {
        var action = component.get('c.getAccounts');
        action.setParams({
            "aid": component.get("v.recordId")
        });
        // Set up the callback
        var self = this;
        action.setCallback(this, function(actionResult) {
         component.set('v.contacts', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
      }
})


 
Best Answer chosen by Frank van Meegen 42
Sampath SuranjiSampath Suranji
Hi,
Check below code. when you toggle, value of Active__c field getting update.
Apex controller,
public class AccountsController1 {
    @AuraEnabled
    public static List <Contact> getAccounts(String aid) {
        system.debug('aid: ' +aid);
        List <Contact> Contacts = [SELECT Id, name,Email,Phone,Active__c  FROM Contact where AccountId=:aid ORDER BY createdDate ASC];
        System.debug('Contacts: ' +Contacts);
        return Contacts;
    }
    @AuraEnabled
    public static void updateContact(string contactId,boolean status){
        try{
            contact objCon=[select Id, name,Email,Phone,Active__c  FROM Contact where Id=:contactId limit 1];
            if(objCon !=null){
                objCon.Active__c = status;
                update objCon;
            }
            
        }
        catch(Exception ex){}
    }
}
modify the check box field as below,
<ui:inputCheckbox change="{!c.selectChange}" name="{!contact.Id}" value="{!contact.Active__c}"/>
js controller,
({
      doInit: function(component, event, helper) {
        // Fetch the account list from the Apex controller
        helper.getContactList(component);
      },
    
      selectChange:function(component, event, helper) {
        helper.updateContact(component,event);
      },
})
js helper,
({
// Fetch the accounts from the Apex controller
      getContactList: function(component) {
        var action = component.get('c.getAccounts');
        action.setParams({
            "aid": component.get("v.recordId")
        });
        // Set up the callback
        var self = this;
        action.setCallback(this, function(actionResult) {
         component.set('v.contacts', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
      },
    
    updateContact: function(component,event) {
        var status= event.getSource().get("v.value");
        var contactId= event.getSource().get("v.name");
        var action = component.get('c.updateContact');
        action.setParams({
            "contactId": contactId,
            "status" : status
        });
        
        var self = this;
        action.setCallback(this, function(actionResult) {
            var state= actionResult.getState();
            if(state=='SUCCESS'){
                //add message or something
            }
        });
        $A.enqueueAction(action);
      },
    
})

regards





 

All Answers

Ravi Dutt SharmaRavi Dutt Sharma
Hi Frank,

I have simplified your code (only component) to some extent. Please use the below code and let me know if it works. Please mark this as the best answer if it resolves your issue. Thanks.

ContactTable.cmp
<aura:component controller="AccountsController1" Implements="flexipage:availableForRecordHome,force:hasRecordId" >
    
    <aura:attribute name="contacts" type="List" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <!-- Use a data table from the Lightning Design System: https://www.lightningdesignsystem.com/components/data-tables/ -->
    <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
        <thead>
            <tr class="slds-text-heading_label">
                <th scope="col"><div class="slds-truncate" title="ID">ID</div></th>
                <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
                <th scope="col"><div class="slds-truncate" title="Email">Email</div></th>
                <th scope="col"><div class="slds-truncate" title="Phone">Phone</div></th>
                <th scope="col"><div class="slds-truncate" title="Active__c">Active</div></th>
                <th scope="col"><div class="slds-truncate" title="Switch">Switch</div></th>
                
            </tr>
        </thead>
        <tbody>
            <!-- Use the Apex model and controller to fetch server side data -->
            <aura:iteration items="{!v.contacts}" var="contact">
                <tr>
                    <th scope="row"><div class="slds-truncate" title="{!contact.Id}">{!contact.Id}</div></th>
                    <td><div class="slds-truncate" title="{!contact.Name}">{!contact.Name}</div></td>
                    <td><div class="slds-truncate" title="{!contact.Email}">{!contact.Email}</div></td>
                    <td><div class="slds-truncate" title="{!contact.Phone}">{!contact.Phone}</div></td>
                    <td>
                        <lightning:input type="checkbox" name="{!contact.Active__c}" checked="{!contact.Active__c}"/>
                    </td>
                    <td>
                        <lightning:input type="toggle"  name="{!contact.Active__c}" checked="{!contact.Active__c}"/>
                    </td>
                    
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>


 
Sampath SuranjiSampath Suranji
Hi,
Check below code. when you toggle, value of Active__c field getting update.
Apex controller,
public class AccountsController1 {
    @AuraEnabled
    public static List <Contact> getAccounts(String aid) {
        system.debug('aid: ' +aid);
        List <Contact> Contacts = [SELECT Id, name,Email,Phone,Active__c  FROM Contact where AccountId=:aid ORDER BY createdDate ASC];
        System.debug('Contacts: ' +Contacts);
        return Contacts;
    }
    @AuraEnabled
    public static void updateContact(string contactId,boolean status){
        try{
            contact objCon=[select Id, name,Email,Phone,Active__c  FROM Contact where Id=:contactId limit 1];
            if(objCon !=null){
                objCon.Active__c = status;
                update objCon;
            }
            
        }
        catch(Exception ex){}
    }
}
modify the check box field as below,
<ui:inputCheckbox change="{!c.selectChange}" name="{!contact.Id}" value="{!contact.Active__c}"/>
js controller,
({
      doInit: function(component, event, helper) {
        // Fetch the account list from the Apex controller
        helper.getContactList(component);
      },
    
      selectChange:function(component, event, helper) {
        helper.updateContact(component,event);
      },
})
js helper,
({
// Fetch the accounts from the Apex controller
      getContactList: function(component) {
        var action = component.get('c.getAccounts');
        action.setParams({
            "aid": component.get("v.recordId")
        });
        // Set up the callback
        var self = this;
        action.setCallback(this, function(actionResult) {
         component.set('v.contacts', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
      },
    
    updateContact: function(component,event) {
        var status= event.getSource().get("v.value");
        var contactId= event.getSource().get("v.name");
        var action = component.get('c.updateContact');
        action.setParams({
            "contactId": contactId,
            "status" : status
        });
        
        var self = this;
        action.setCallback(this, function(actionResult) {
            var state= actionResult.getState();
            if(state=='SUCCESS'){
                //add message or something
            }
        });
        $A.enqueueAction(action);
      },
    
})

regards





 
This was selected as the best answer
Frank van Meegen 42Frank van Meegen 42

Hi guys,

Thank you for your very fast replies! Both solutions look good only the solution by Sampath included the server side update to the contact record.

Regards,

Frank

Jordan Chevalier 8Jordan Chevalier 8
Hey guys,
Do you know how to write the Test Class to for the following Apex Class ?
public class AccountsController1 {
    @AuraEnabled
    public static List <Contact> getAccounts(String aid) {
        system.debug('aid: ' +aid);
        List <Contact> Contacts = [SELECT Id, name,Email,Phone,Active__c  FROM Contact where AccountId=:aid ORDER BY createdDate ASC];
        System.debug('Contacts: ' +Contacts);
        return Contacts;
    }
    @AuraEnabled
    public static void updateContact(string contactId,boolean status){
        try{
            contact objCon=[select Id, name,Email,Phone,Active__c  FROM Contact where Id=:contactId limit 1];
            if(objCon !=null){
                objCon.Active__c = status;
                update objCon;
            }
            
        }
        catch(Exception ex){}
    }
}

Thanks a lot, I'm stuck since weeks