0

currently, I'm passing in a options array to the options attribute of a lightning-checkbox-group. I need to mimic the behavior of that tag, but I need to do it in html because I don't think I can get the checkboxes to display horizontally. I've tried <template for:each and have not had any luck.

My goal would be to pass in the same name/value pair array, loop through it and call the same change handler that is called when using lightning-checkbox-group.

A simple code snippet would be awesome.

This is what I've tried so far:

{lineItemObjectInfo.data.fields.Reason__c.label}
 <template for:each={reasonOptions} for:item="option" for:index="index">
     <div key={option}>
         <lightning-input onchange={handleChange} 
                          name={lineItemObjectInfo.data.fields.Reason__c.apiName} 
                          type="checkbox" label={option.label} 
                          value={recordInput.fields.Reason__c}></lightning-input>
     </div>
 </template>

That actually gets me pretty close. When changed it fires the change handler and fails when I'm trying to do a .join on the recordInput for the field:

handleChange(event) {
    const {target: {name, value}} = event;   
    switch (name ) {
        case "Reason__c":
            this.recordInput.fields[name] = value.join(";");
            break;
        default:
            this.recordInput.fields[name] = value;
            break;
    }
}

I've also tried using a form tag with input and label tags but that didn't get me much further. The switch has been reduced for purpose of making it more clear.

This is my original use of lightning-checkbox-group which functionally worked but styling is inflexible:

<div class="slds-col slds-size_3-of-12">
    <lightning-checkbox-group
    onchange={handleChange}
    name={lineItemObjectInfo.data.fields.Reason__c.apiName}
    label={lineItemObjectInfo.data.fields.Reason__c.label}
    options={reasonOptions}
    value={recordInput.fields.Reason__c}></lightning-checkbox-group>
</div>
4
  • normally, we would expect you to provide what you have tried, and then take it from there. do you have any code you started? any particular issue? – glls May 8 at 22:38
  • lightning-checkbox-group will only render from top to bottom. You do need to create your own component/HTML for this. Strictly speaking, we're not a code-writing service, but if you include what you've tried so far, we'll be glad to spot errors and suggestions on how to fix them. – sfdcfox May 8 at 23:08
  • Fair enough. Question edited. – mackmama May 8 at 23:36
  • You can customize the base components github.com/salesforce/base-components-recipes/tree/master/… – manjit5190 May 9 at 16:28
0
<lightning-checkbox-group   class="checkboxClass"
                            name="Checkbox Group"
                              label="Checkbox Group"
                              options={options}
                              value={value}
                              onchange={handleChange}></lightning-checkbox-group>

we have to override CSS :

Create a CSS file and add in static resource

File Content :

.checkboxClass .slds-form-element__control{
    display: -webkit-box;
    display: flex;
}

Import That static resource file in your component
import { loadStyle } from 'lightning/platformResourceLoader';

import CUSTOMCSS from '@salesforce/resourceUrl/{yourfileName}';

a) Define variable like : isCssLoaded = false;

Call it in reRenderCallback

renderedCallback(){

if(this.isCssLoaded) return
this.isCssLoaded = true;
loadStyle(this,CUSTOMCSS).then(()=>{
    console.log('loaded');
})
.catch(error=>{
    console.log('error to load');
});
}
1
  • A little different approach than the one above. I'll give this one a try and let you know. – mackmama May 10 at 17:53
3

You will need to write your own checkbox group. I took the SLDS core checkbox group and added a few styles to cause it to span 4 wide before wrapping around (feel free to fix this to suit your needs).

The checkbox code is as follows:

<template>
  <fieldset class="slds-form-element">
    <legend class="slds-form-element__legend slds-form-element__label">{label}</legend>
    <div class="slds-form-element__control">
      <div class="slds-grid slds-wrap">
        <div class="slds-checkbox slds-col slds-size_1-of-4" for:each={_options} for:item="option" key={option.value}>
          <input type="checkbox" name={name} id={option.value} value={option.value} checked={option.checked} onchange={updateSelected}/>
          <label class="slds-checkbox__label" for={option.value}>
        <span class="slds-checkbox_faux"></span>
        <span class="slds-form-element__label">{option.label}</span>
      </label>
        </div>
      </div>
    </div>
  </fieldset>
</template>

And the controller:

import { LightningElement, api } from 'lwc';

export default class CustomCheckboxGroup extends LightningElement {
  _selectedValues = [];
  _options = [];
  @api name;
  @api label;
  @api set options(value) {
    this._options = [...value];
    this.manageSelected();
  }
  get options() {
    return [...this._options];
  }
  @api set value(value) {
    this._selectedValues = [...value];
    this.manageSelected();
  }
  get value() {
    return [...this._selectedValues];
  }
  manageSelected() {
    this._options = this._options.map(
      element => ({...element, checked: this._selectedValues.includes(element.value)})
    );
  }
  updateSelected() {
    this._selectedValues = [...this.template.querySelectorAll('input')]
      .filter(element => element.checked)
      .map(element => element.value);
    this.manageSelected();
    this.dispatchEvent(
      new CustomEvent('change', { detail: {selected: [...this._selectedValues]}})
    );
  }
}

I may have missed a few implementation details, but hopefully this is the code you're looking for.

I have implemented a demo of this for you to use.

I have not implemented variants, any validity checking, etc, but these should be pretty easy to hack into the code from this starting point.

2
  • At this point, you could just make this a custom component :) – Caspar Harmer May 9 at 4:17
  • I created two components from this. One for lightning-checkbox-group and one for lightning-radio-group with very minor changes. Thank you @sfdcfox! – mackmama May 10 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.