I am trying to allow a user to select an object from a dropdown, and based on the chosen object, return a random number of records. The problem I'm having is that I am having trouble returning different types of object lists in the controller. What is the appropriate way to do this?
Controller
public with sharing class SearchObjectsToAudit {
@AuraEnabled(Cacheable=true)
public static Account[] searchAccounts(){
return [SELECT Id, Name FROM Account ORDER BY Name LIMIT 50];
}
@AuraEnabled(Cacheable=true)
public static Bear__c[] searchIntakes(){
return [SELECT Id, Name FROM Intake ORDER BY Name LIMIT 50];
}
@AuraEnabled(Cacheable=true)
public static Contact[] searchMatters(){
return [SELECT Id, Name FROM Contact ORDER BY Name LIMIT 50];
}
@AuraEnabled(Cacheable=true)
public static SearchObjects(String searchTerm) {
System.debug(searchTerm);
if (searchTerm == 'Account') {
return searchAccounts();
}
else if (searchTerm == 'Intake') {
return searchIntakes();
}
else if (searchTerm == 'Matters') {
return searchMatters();
}
return null;
}
}
HTML
<template>
<lightning-combobox
name="object"
label="Object"
value={searchTerm}
placeholder="Select Object To Audit"
options={options}
onchange={handleChange} >
</lightning-combobox>
<lightning-card title="Bears" icon-name="utility:animal_and_nature">
<div class="slds-card__body_inner">
<!-- Start bear list -->
<template if:true={bears.data}>
<lightning-layout multiple-rows="true" pull-to-boundary="small">
<template for:each={bears.data} for:item="bear">
<lightning-layout-item key={bear.Id} size="3" class="slds-p-around_x-small">
<p>{bear.Name}</p>
</lightning-layout-item>
</template>
</lightning-layout>
<!-- No bears found -->
<template if:false={hasResults}>
<div class="slds-align_absolute-center slds-m-vertical_small">
This is beary disturbing, we did not find results...
</div>
</template>
</template>
<!-- End bear list -->
<!-- Data failed to load -->
<template if:true={bears.error}>
<div class="slds-text-color_error">
An error occurred while loading the bear list
</div>
</template>
</div>
</lightning-card>
JS File
import { LightningElement, track, wire} from 'lwc';
import SearchObjects from
'@salesforce/apex/SearchObjectsToAudit.SearchObjects';
export default class ComboboxBasic extends LightningElement {
@track value = 'Account';
@track searchTerm = '';
@wire(SearchObjects, {searchTerm: '$searchTerm'})
bears;
get options() {
return [
{ label: 'Account', value: 'Account' },
{ label: 'Intake', value: 'Intake' },
{ label: 'Matter', value: 'Matter' },
];
}
handleChange(event) {
window.clearTimeout(this.delayTimeout);
const searchTerm = event.target.value;
// eslint-disable-next-line @lwc/lwc/no-async-operation
this.delayTimeout = setTimeout(() => {
this.searchTerm = searchTerm;
}, 300);
this.value = event.detail.value;
}
}