3

I am trying to add link on lightning-datatable. But I think javaScript does not accept this syntax

this.accounts = data.map(row => { return `{ ...${row}, nameUrl: /${row.Id}}`})

Here is my code:

HTML file

<template>
    <template if:true={accounts}>
        <lightning-datatable key-field="id" data={accounts} columns={columns} hide-checkbox-column="true" resize-column-disabled="true">
        </lightning-datatable>
    </template>
</template>

JS file

import { LightningElement, track, wire } from 'lwc';
import getAllAccounts from '@salesforce/apex/AccountCnt.allAccounts';

export default class accountList extends LightningElement {
    @track error;
    @track accounts;

    @track columns = [

        {
            label: 'Account Name',
            fieldName: 'nameUrl',
            type: 'url',
            typeAttributes: {
                label: { fieldName: 'Name' },
                target: '_blank'
            }


        },
        {
            label: 'Phone',
            fieldName: 'Phone',
            type: 'text',
            editable: true
        }

    ];

    @wire(getAllAccounts)
    wireAccountInfo({ data, error }) {
        if (data) {
            this.accounts = data.map(row => { return `{ ...${row}, nameUrl: /${row.Id}}`})
            window.console.log(" this.accounts => ", JSON.stringify(this.accounts))
            this.error = null;
        }
        if (error) {
            this.error = error;
            this.accounts = [];
        }
    }
}

Apex class

public with sharing class AccountCnt {

    @AuraEnabled(cacheable=true)
    public static List<Account> allAccounts() {
        return [SELECT Id, Name, Phone FROM Account];
    }
}

Here is what I get in the console:

this.accounts =>  ["{ ...[object Object], nameUrl: /0018E00001FqMcdQAF}","{ ...[object Object], nameUrl: /0018E00001FqMcnQAF}","{ ...[object Object], nameUrl: /0018E00001Fq7cCQAR}"]

2 Answers 2

2

The tilde (`) creates a template string. This is a normal string, not an object, as would be expected. Instead, you'd use normal object syntax:

this.accounts = data.map(record => ( { nameUrl: `/${record.Id}`, ...record } ) );
1
  • Thanks @sfdcfox, it works
    – enrico
    Commented Nov 17, 2019 at 16:18
0

This approach should work:

@wire(getAllAccounts)
    wireAccountInfo({ data, error }) {
        if (data) {
            let nameUrl;
            this.accounts = data.map(row => {
                nameUrl = `/${row.Id}`;
                return { ...row, nameUrl }
            })
            window.console.log(" this.accounts => ", JSON.stringify(this.accounts))
            this.error = null;
        }
        if (error) {
            this.error = error;
            this.accounts = [];
        }
    }

You must log in to answer this question.

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