pozil / sfdc-ui-lookup-lwc

Salesforce Lookup Component built with Lightning Web Components.
Apache License 2.0
582 stars 223 forks source link

Capturing correct target when implement custom data type for Datatable #129

Closed banderson-stripe closed 1 year ago

banderson-stripe commented 1 year ago

I am trying to implement the Lookup component in a Custom Data Type for the lightning-datatable

The issue I am having is where do I put the onsearch event so that I can capture the event.target correctly to then be able to call the setSearchResults() method correctly.

This stackexchange also describes the same issue: https://salesforce.stackexchange.com/questions/270252/event-getsource-alternative-in-lwc-considering-origin-reparenting

Here is my setup:

customTypeLookupEdit.html

<template>
    <c-lookup></c-lookup>
</template>

customDatatable.js

import LightningDatatable from "lightning/datatable";
import customLookupTemplate from "./customTypeLookupEdit.html"

export default class CustomDatatableType extends LightningDatatable {
  static customTypes = {
    customTypeLookup:{
      template: customLookupTemplate,
      standardCellLayout: true
    }
  };
}

actualComponent.html

<template>
    <c-custom-datatable columns={columns}></c-custom-datatable>
</template>

actualComponent.js

import { LightningElement } from 'lwc';

const columns = [
    { label: 'foo', fieldName: 'foo', type: 'customTypeLookup' },
];

export default class actualComponent extends LightningElement {
    columns = columns;

    /**
     * Handles the lookup search event.
     * Calls the server to perform the search and returns the resuls to the lookup.
     * @param {event} event `search` event emmitted by the lookup
     */
    handleLookupSearch(event) {
        const lookupElement = event.target;
        lookupElement.setSearchResults('[{"title":"title","subtitle":"subtitle","sObjectType":"type","id":"0010R00000yvEyRQAU","icon":"icon"}]');
    }
}
banderson-stripe commented 1 year ago

@pozil. Just wanted to give you an update.

@surajp was able to help me resolve this issue. It's actually very simple and elegant:

{ label: 'foo', fieldName: 'foo', type: 'customTypeLookup', typeAttributes: {'onseach':this.handleSearchFunction} }

which then gets passed to the customTypeLookupEdit.html

<template>
    <c-lookup onsearch={typeAttributes.onsearch}></c-lookup>
</template>
pozil commented 1 year ago

Wow, that was fast! I'm glad that you figured it out. This is what I was going to recommend, but I wanted to try it out first, just in case :)

banderson-stripe commented 1 year ago

@pozil only issue is the base lightining-datatable is not allowing the result dropdown to expand due to a slds-truncate CSS class that is part of the base component on the table

pozil commented 1 year ago

Damn. Perhaps you need to open a modal with lookup then? Not the best UX but I don't see how you can avoid it if you want to keep the datatable.