Create an Apex controller to delete a specified record with the delete operation. The following Apex controller deletes an expense object record.
@AuraEnabled public static Expense__c deleteExpense(Expense__c expense) { // Perform isDeletable() check here delete expense; return expense; }
Depending on how your components are set up, you might need to create an event to tell another component that a record has been deleted. For example, you have a component that contains a sub-component that is iterated over to display the records. Your sub-component contains a button (1), which when pressed fires an event that’s handled by the container component (2), which deletes the record that’s clicked on.
<aura:registerEvent name="deleteExpenseItem" type="c:deleteExpenseItem"/> <lightning:button label="Delete" onclick="{!c.delete}"/>
Create a component event to capture and pass the record that’s to be deleted. Name the event deleteExpenseItem.
<aura:event type="COMPONENT"> <aura:attribute name="expense" type="Expense__c"/> </aura:event>
Then, pass in the record to be deleted and fire the event in your client-side controller.
delete : function(component, evt, helper) { var expense = component.get("v.expense"); var deleteEvent = component.getEvent("deleteExpenseItem"); deleteEvent.setParams({ "expense": expense }).fire(); }
In the container component, include a handler for the event. In this example, c:expenseList is the sub-component that displays records.
<aura:handler name="deleteExpenseItem" event="c:deleteExpenseItem" action="c:deleteEvent"/> <aura:iteration items="{!v.expenses}" var="expense"> <c:expenseList expense="{!expense}"/> </aura:iteration>
And handle the event in the client-side controller of the container component.
deleteEvent : function(component, event, helper) { // Call the helper function to delete record and update view helper.deleteExpense(component, event.getParam("expense")); }
Finally, in the helper function of the container component, call your Apex controller to delete the record and update the view.
deleteExpense : function(component, expense, callback) { // Call the Apex controller and update the view in the callback var action = component.get("c.deleteExpense"); action.setParams({ "expense": expense }); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { // Remove only the deleted expense from view var expenses = component.get("v.expenses"); var items = []; for (i = 0; i < expenses.length; i++) { if(expenses[i]!==expense) { items.push(expenses[i]); } } component.set("v.expenses", items); // Other client-side logic } }); $A.enqueueAction(action); }
The helper function calls the Apex controller to delete the record in the database. In the callback function, component.set("v.expenses", items) updates the view with the updated array of records.