3

I am displaying a survey response table on a custom object and wish to dynamically color a cell based on the survey response answer. Ultimately I will want to have multiple answers to check for, but I am testing with just one value in the code below. Here is my HTML inside the LWC that displays the table:

<template>
    <lightning-card variant="Narrow" icon-name="standard:survey">
        <h1 slot="title" class="slds-card__header-link">Survey Responses</h1>
        <lightning-datatable
                key-field="Id"
                data={data}
                hide-checkbox-column
                columns={columns} sorted-by={sortBy} 
                    sorted-direction={sortDirection}  onsort={handleSortdata} >
        </lightning-datatable>
    </lightning-card>    
</template>

Here is my JS:

import { LightningElement,wire, track, api } from 'lwc';

import { refreshApex } from '@salesforce/apex';
import { getRecord } from 'lightning/uiRecordApi';
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';

import getSurvey from '@salesforce/apex/SurveyResponseTableCtrl.getSurvey';



const columns = [
    { fixedWidth: 120, label: 'Order', fieldName: 'questionOrder',sortable: 'true', type: 'text' ,cellAttributes: { alignment: 'left' }},
    { label: 'Question', fieldName: 'question',sortable: 'true', type: 'text' ,wrapText:'true',cellAttributes: { alignment: 'left',  }},
    { fixedWidth: 200, label: 'Answer', fieldName: 'answer',sortable: 'true', type: 'text' ,wrapText:'true', cellAttributes: { alignment: 'left' , class: { fieldName: 'statusColor' }}}
];

export default class surveyResponseTableLWC extends NavigationMixin(LightningElement) {
    data = [];
    dataTemp = [];
    isShowData = false;
    columns = columns;
    @api recordId;
    @track sortBy;
    @track sortDirection;
    // eslint-disable-next-line @lwc/lwc/no-async-await
    
     async connectedCallback() {
        getSurvey({recId: this.recordId})
                .then((result) => {
                    this.data = result;
                    this.error = undefined;
                    data.forEach(ele => {
                        ele.statusColor = ele.answer = "Moderately Dissatisfied" ? 'slds-text-color_error' : 'slds-text-color_success';
                    });
                    this.data = data;
                    sortData('questionOrder', 'asc');
                    console.log('data',data);
                })
                .catch((error) => {
                    this.error = error;
                    
                });

    }
    
    handleSortdata(event) {
        // field name
        this.sortBy = event.detail.fieldName;
        // sort direction
        this.sortDirection = event.detail.sortDirection;
        // calling sortdata function to sort the data based on direction and selected field
        this.sortData(event.detail.fieldName, event.detail.sortDirection);
    }

    sortData(fieldname, direction) {
        //this.data = this.messageRecordList;
        this.dataTemp = this.data;
        console.log('this.data' +this.data);
        console.log('this.messageDataList ' +this.messageRecordList );

        // serialize the data before calling sort function
        //let parseData = JSON.parse(JSON.stringify(this.data));
        let parseData = JSON.parse(JSON.stringify(this.dataTemp));
        console.log('parseData' +parseData);

        // Return the value stored in the field
        let keyValue = (a) => {
            return a[fieldname];
        };

        // cheking reverse direction 
        let isReverse = direction === 'asc' ? 1: -1;

        // sorting data 
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; // handling null values
            y = keyValue(y) ? keyValue(y) : '';

            // sorting values based on direction
            return isReverse * ((x > y) - (y > x));
        });

        // set the sorted data to data table data
        //this.data = parseData;
        this.data = parseData;
    }
}

I am trying to have the table color the cell or text red if the answer is "Moderately Dissatisfied" but nothing is happening. Here is what the table looks like currently: surveytable

1 Answer 1

2

You've missed the part in the documentation that says that you can't use custom classes with standard datatables.

Custom classes are currently not supported. To apply custom styling on your datatable cells, create a custom data type and then apply your custom CSS classes. See Custom Data Type Layout and Styles.

This is because of how CSS scoping works in the Shadow DOM. You can only use standard SLDS CSS classes.

To fix this, create a new component, such as surveyResponseTable, and populate it with this code:

import LightningDatatable from 'lightning/datatable';
export default class SurveyResponseTable extends LightningDatatable {
}

This should be everything you need.

Now, change your current template to use this new component:

<template>
    <lightning-card variant="Narrow" icon-name="standard:survey">
        <h1 slot="title" class="slds-card__header-link">Survey Responses</h1>
        <c-survey-response-table
                key-field="Id"
                data={data}
                hide-checkbox-column
                columns={columns} sorted-by={sortBy} 
                    sorted-direction={sortDirection}  onsort={handleSortdata} >
        </c-survey-response-table>
    </lightning-card>    
</template>

Your JS file looks like it should work just fine as is. It's unclear from the documentation, but I believe you may need to move your CSS file into the custom component.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .