Skip to content

Commit

Permalink
buttons and logic must be defined Sarveshgithub#11
Browse files Browse the repository at this point in the history
  • Loading branch information
mickaelgudin committed Mar 17, 2022
1 parent ba03833 commit eaf7f18
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 78 deletions.
65 changes: 36 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Salesforce Lightning Data table (LWC Version)

![Image description](https://github.com/Sarveshgithub/sfdc-lwc-lightning-datatable/blob/master/lwc-datatable.PNG?raw=true)
![Image description](https://user-images.githubusercontent.com/39730173/158386203-bca7099f-0070-48d2-8ec9-6936a68dd754.PNG)

## About

Expand Down Expand Up @@ -36,6 +36,7 @@ Design Attribute
Enter Related field API Name | :x: | String | Enter related field api name | Example AccountId for contact when component is on account layout.
Enter WHERE clause | :x: | String | provide aditional filters | Example `LastName like '%s' AND Account.Name like '%t'`
| Show the number of record | :x: | Boolean | append the number of records in the title | checked(true) OR not checked(false) |
| Buttons to display | :x: | String | buttons that we want to display | new,delete-selected |

## Columns JSON Example
``` yaml
Expand All @@ -61,53 +62,59 @@ Enter WHERE clause | :x: | String | provide aditional filters | Example `LastNam
"type": "text"
}]
```
## Buttons configuration (for developers, accessible in the component and from parent component)
## Buttons configuration

### Buttons definition(javascript controller) :
```
const buttonsOfList = {
'new' : { label : "New", variant: "neutral", needSelectedRows: false },
'delete-everything' : { label : "delete all", variant: "destructive", needSelectedRows: false },
'delete-selected' : { label : "delete selected", variant : "brand", needSelectedRows: true }
};
```
### Default displayed buttons
The "New" button is displayed by default, modify the method setDefaultListButtons to change default buttons.

### Call apex or javascript method
For a button that is going to call callApexFromButton, the properties must be :
- callApexFromButton: true

### Fire event to parent component
For a button that is going to fire an event, the properties must be :
- callApex: false
- needSelectedRows : can be true if you need to send selected rows to parent component
### Button logic definition (fire an event, call a method in the javascript controller)
You can implement your own logic for your new buttons based on button key (new, delete-selected...).

### Example
Javascript array (actionButtonsList property) :
```
[
{ label : "delete all", variant: "destructive", needSelectedRows: true, callApex: true },
{ label : "action button", variant : "brand", needSelectedRows: false, callApex: false },
{ label : "another action button", variant : "brand", needSelectedRows: true, callApex: false }
];
callButtonAction(event) {
//call desired javacript method or apex call, or throw an event based on the button key(new, delete-selected...)
//if button has needSelectedRows set to true, have selected rows using this.selectedRows
const buttonLabel = event.target.dataset.name;
if(buttonLabel === 'new') {
this.newRecord();
} else if(buttonLabel === 'delete-selected') {
new customEvent('deleteselected', {detail : this.rows});
}
console.log('callButtonAction, button clicked has label : '+buttonLabel);
}
```
Parent component (**you don't need parent component, you can define default buttons using actionButtonsList**) :

**From Parent component (for developers) :**
```
//in template
<c-lwc-related-list object-name="Contact"
columns={columns}
title="contacts-from-parent-component"
related-field-api="AccountId"
is-counter-displayed=true
action-buttons-list={actions}
show-checkboxes=true
onaction2={helloWorld}
onaction3={helloWorld}
action-buttons-to-display='new,delete-selected'
ondeleteselected={helloWorld} >
</c-lwc-related-list>
```
```
//in js controller
helloWorld(event) {
console.log('hello world');
console.log('event rows ', event.detail);
}
```

- The first button "delete all" is not going to send event to parent it will call the javascript method callApexFromButton you must
implement the desired javascript/apex call based on the button label.
- The button "action button" fires the event action2
- The button "another action button" fires the event action3

The results should be :
![Capture buttons](https://user-images.githubusercontent.com/39730173/158386203-bca7099f-0070-48d2-8ec9-6936a68dd754.PNG)

## Deploy
Click Button to deploy source in Developer/Sandbox

Expand Down
30 changes: 5 additions & 25 deletions force-app/main/default/lwc/lwcRelatedList/lwcRelatedList.html
Original file line number Diff line number Diff line change
@@ -1,39 +1,19 @@
<template>
<!-- Main content -->
<lightning-card variant="Narrow" title={titleFormatted} icon-name={iconName}>
<!--default button create -->
<template if:false={actionButtonsListNotEmpty}>
<lightning-button label="New" title="Non-primary action" onclick={newRecord} class="slds-m-left_x-small"
slot="actions"></lightning-button>
</template>

<!-- custom buttons for list -->
<!-- custom action buttons for list, by default new is displayed -->
<template if:true={actionButtonsListNotEmpty}>
<template for:each={actionButtonsList} for:item="actionButton" for:index="index">
<lightning-button if:true={actionButton.callApex}
key={actionButton.label}
<lightning-button key={actionButton.label}
label={actionButton.label}
title={actionButton.label}
variant={actionButton.variant}
onclick={callApexFromButton}
data-name={actionButton.label}
onclick={callButtonAction}
data-name={actionButton.uniqueName}
class="slds-m-left_x-small"
slot="actions"
>
</lightning-button>

<lightning-button if:false={actionButton.callApex}
data-index={index}
key={actionButton.label}
label={actionButton.label}
title={actionButton.label}
variant={actionButton.variant}
onclick={fireEventFromButton}
class="slds-m-left_x-small"
slot="actions"
>
</lightning-button>

</template>
</template>

Expand Down Expand Up @@ -80,4 +60,4 @@
onclick={lastPage} class="slds-m-left_xx-small slds-m-right_xx-small"></lightning-button>
</div>
</lightning-card>
</template>
</template>
80 changes: 56 additions & 24 deletions force-app/main/default/lwc/lwcRelatedList/lwcRelatedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ const actions = [
{ label: "Edit", name: "edit" },
{ label: "Delete", name: "delete" }
];

const buttonsOfList = {
'new' : { label : "New", variant: "neutral", needSelectedRows: false },
'delete-everything' : { label : "delete all", variant: "destructive", needSelectedRows: false },
'delete-selected' : { label : "delete selected", variant : "brand", needSelectedRows: true }
};

export default class LightningDatatable extends NavigationMixin(
LightningElement
) {
Expand All @@ -29,6 +36,7 @@ export default class LightningDatatable extends NavigationMixin(
@api whereClause;
@api limit = 10;
@api isCounterDisplayed;
@api actionButtonsToDisplay;
@api actionButtonsList; //buttons for the list
@api showCheckboxes;
// Private Property
Expand All @@ -44,6 +52,40 @@ export default class LightningDatatable extends NavigationMixin(
if (this.columns != null && this.columns != undefined) {
cols = JSON.parse(this.columns);
}

//defining custom list buttons based on actionButtonsToDisplay(string seperated design property)
if(this.actionButtonsToDisplay && this.actionButtonsToDisplay != undefined ) {
let arrayOfButtonsKeys = this.actionButtonsToDisplay.replace(/\s/g, '').split(',');
let actionsButtons = [];

if(arrayOfButtonsKeys && arrayOfButtonsKeys.length > 0) {
arrayOfButtonsKeys.forEach(buttonKey => {
//checking if button key is empty or button not defined
if(buttonKey && buttonsOfList[buttonKey]) {
let button = buttonsOfList[buttonKey];
button.uniqueName = buttonKey;

actionsButtons.push(button );

//if one button needs selected rows then we show checkboxes
if(buttonsOfList[buttonKey].needSelectedRows ) {
this.showCheckboxes = true;
}
}
});

if(actionsButtons.length > 0) {
this.actionButtonsList = actionsButtons;
} else {
this.setDefaultListButtons();
}
} else {
this.setDefaultListButtons();
}
} else {
this.setDefaultListButtons();
}

cols.push({
type: "action",
typeAttributes: { rowActions: actions }
Expand All @@ -56,6 +98,11 @@ export default class LightningDatatable extends NavigationMixin(
this.fetchRecords();
}

setDefaultListButtons() {
this.actionButtonsList = [];
this.actionButtonsList.push(buttonsOfList['new']);
}

fetchRecords() {
getRecords({ soql: this.soql, SObjectName: this.objectName, iconName: this.iconName })
.then((data) => {
Expand Down Expand Up @@ -267,35 +314,20 @@ export default class LightningDatatable extends NavigationMixin(
return (this.isCounterDisplayed) ? this.title + ` (${this.totalRows})` : this.title;
}

callApexFromButton(event) {
//call desired apex method based on buttonLabel value
callButtonAction(event) {
//call desired javacript method or apex call, or throw an event based on the button key(new, delete-selected...)
//if button has needSelectedRows set to true, have selected rows using this.selectedRows
const buttonLabel = event.target.dataset.name;
console.log('callApexFromButton, button clicked has label : '+buttonLabel);
}

fireEventFromButton(event) {
event.preventDefault();
console.log('fireEventFromButton');
const buttonPos = Number(event.target.dataset.index) + 1;
const button = this.actionButtonsList[buttonPos-1];
let buttonEvent = null;

console.log('action'+buttonPos);

if(button.needSelectedRows && button.needSelectedRows === true) {
buttonEvent = new CustomEvent(
'action'+buttonPos,
{ detail : JSON.stringify(this.selectedRows) }
);
} else {
buttonEvent = new CustomEvent('action'+buttonPos);
if(buttonLabel === 'new') {
this.newRecord();
} else if(buttonLabel === 'delete-selected') {
const eventDeleteSelected = new CustomEvent('deleteselected', {detail : JSON.stringify(this.selectedRows) });
this.dispatchEvent(eventDeleteSelected);
}

// Dispatches the event.
this.dispatchEvent(buttonEvent);
console.log('callButtonAction, button clicked has label : '+buttonLabel);
}

handleRowSelection(event){
this.selectedRows = JSON.parse(JSON.stringify(event.detail.selectedRows) );
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<property name="relatedFieldAPI" type="String" default="" label="Enter Related field API Name" />
<property name="whereClause" type="String" default="" label="Enter WHERE clause" />
<property name="isCounterDisplayed" type="Boolean" label="Show the number of record" />
<property name="actionButtonsToDisplay" type="String" label="Buttons to display" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

0 comments on commit eaf7f18

Please sign in to comment.