[SalesForce] Why is not setting value of checkboxes in LWC

I am getting data in my LWC from a wrapper class. In that data, I get object API name, field API name and value present in the field in the form of Strings. I iterate over the data from the wrapper class and take input from the user using lightning-input-field.

Code:

<!-- iterate over wrapper list -->
<template iterator:item={wrapperListCopy}>
     <tr key={item.value.index}>
           <td>
                <lightning-record-edit-form object-api-name={objectApiName}>
                     <lightning-input-field id={item.value.index} 
                                            field-name={item.value.inputFieldName} 
                                            value={item.value.filterValue}>
                     </lightning-input-field>
                </lightning-record-edit-form>
           </td>
     </tr>
</template>

The filterValue comes in String format. This code works for all fields except checkboxes. Even though filterValue contains true or false, the same is not reflected on checkbox in UI. By default, the checkbox appears checked on UI irrespective of the value present in filterValue.

It means that the checkbox is not getting value from the value attribute of lightning-input-field. Also, the checkbox always appears checked by default in UI. I want it to be unchecked by default. I am not able to understand why this is happening.

Is it because filterValue is a String? – I need it to be a string because all other fields are using it.

Or is it because I use value attribute instead of checked attribute? – I got an error saying that there is no such checked attribute.

Please help. Thank you!😄

Best Answer

Probably due to JavaScript's type conversion rules; a string is converted to a Boolean in the following way:

  • a string that is undefined, null or empty (i.e. "") becomes false
  • a string that is none of the above becomes true

Thus, the strings "true" and "false" both become true as a Boolean. You need to change the way your filterValue is generated or used to resolve this. For example, ensure that filterValue is set to null for false and "true" otherwise.

Related Topic