LWC: Convert list of records to multi checkboxes in LWC

We have a requirement to display list of records as multi checkboxes/picklist on UI. Salesforce out of box don't support this requirement. hence we have to use customize the UI as LWC screen. Please find the below code snippet.

Step 1- Create a LWC component as below.

/*
    Author          : Rajesh Kumar
    Created         : August 24 2021  
   
*/
import { apiLightningElementwire } from 'lwc';
import getContactList from '@salesforce/apex/AccountController.getContactList';

export default class contacts extends LightningElement {
    @api recordId;
    value ='';
  //assigning data
    @wire(getContactList, { recordId: '$recordId'})
    wiredContacts;
    
    handleChange(e) {
        
        this.value = e.detail.value;
        let cont = { 'sobjectType': 'DS_CX_Handshake__c' };
        cont.Id = this.recordId;
        for(let i=0i<this.value.lengthi++){
            console.log(this.value[i]);
        }
    }
        
        
}


<!--
    Author          : Rajesh Kumar
    Created         : August 24 2021  
   
-->
<template>
    <lightning-card>
        <lightning-accordion active-section-name="Contacts" allow-multiple-sections-open>
            <lightning-accordion-section name="Contacts" label="Contacts">
                <lightning-checkbox-group name="Contacts"
                        label="Contacts"
                        options={wiredContacts.data}
                        value={value}
                        onchange={handleChange}>
                    </lightning-checkbox-group>
            </lightning-accordion-section>
        </lightning-accordion>
    </lightning-card>
</template>


Step-2 Create a controller class as below.

public with sharing class AccountController{
    
    
    @AuraEnabled(cacheable=true)
    public static list<ContactListgetContactList(string recordId){
        list<ContactListcontactList = new list<ContactList>();
        
        List<ContactscContactList = new List<Contact>();
        scContactList = [SELECT Id, Name FROM Contact
        WHERE AccountId = : recordId WITH SECURITY_ENFORCED
        ORDER BY Name];
        List<Map<String,String>> optionsList = new List<Map<String,String>>();
        for(Contact scContactscContactList)
        {
            contactList.add(new ContactList(scContact.Name,scContact.Id));
        }
        return contactList;
    }
   
    public class ContactList{
        @AuraEnabled
        public String label;
        @AuraEnabled
        public String value;
       
        public ContactList(string label,string value)
        {
            this.label = label;
            this.value = value;
        }
    }
    
}


Happy Learning!!

Comments