Newer Version Available
Deleting Records
Create an Apex controller to delete a specified record with the delete operation. The following Apex controller deletes an expense object record.
1@AuraEnabled
2public static Expense__c deleteExpense(Expense__c expense) {
3 // Perform isDeletable() check here
4 delete expense;
5 return expense;
6}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.
1<aura:registerEvent name="deleteExpenseItem" type="c:deleteExpenseItem"/>
2<ui:button label="Delete" press="{!c.delete}"/>
Create a component event to capture and pass the record that’s to be deleted. Name the event deleteExpenseItem.
1<aura:event type="COMPONENT">
2 <aura:attribute name="expense" type="Expense__c"/>
3</aura:event>Then, pass in the record to be deleted and fire the event in your client-side controller.
1delete : function(component, evt, helper) {
2 var expense = component.get("v.expense");
3 var deleteEvent = component.getEvent("deleteExpenseItem");
4 deleteEvent.setParams({ "expense": expense }).fire();
5}In the container component, include a handler on your sub-component. In this example, c:expenseList is the sub-component.
1<aura:iteration items="{!v.expenses}" var="expense">
2 <c:expenseList expense="{!expense}" deleteExpenseItem="{!c.deleteEvent}"/>
3</aura:iteration>And handle the event in the client-side controller of the container component.
1deleteEvent : function(component, event, helper) {
2 // Call the helper function to delete record and update view
3 helper.deleteExpense(component, event.getParam("expense"));
4}Finally, in the helper function of the container component, call your Apex controller to delete the record and update the view.
1deleteExpense : function(component, expense, callback) {
2 // Call the Apex controller and update the view in the callback
3 var action = component.get("c.deleteExpense");
4 var self = this;
5 action.setParams({
6 "expense": expense
7 });
8 action.setCallback(this, function(response) {
9 var state = response.getState();
10 if (state === "SUCCESS") {
11 // Remove only the deleted expense from view
12 var expenses = component.get("v.expenses");
13 var items = [];
14 for (i = 0; i < expenses.length; i++) {
15 if(expenses[i]!==expense) {
16 items.push(expenses[i]);
17 }
18 }
19 component.set("v.expenses", items);
20 // Other client-side logic
21 }
22 });
23 $A.enqueueAction(action);
24}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.