Create a Database Trigger | Techila
single,single-post,postid-988,single-format-standard,ajax_updown_fade,page_not_loaded,,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-9.4.2,bridge,wpb-js-composer js-comp-ver-4.12,vc_responsive

Create a Database Trigger


Create a Database Trigger


Apex triggers are useful for implementing business logic that you can’t implement with clicks (such as workflow rules). In this tutorial, the business scenario is this: by default, master-detail relationships automatically cascade the deletion of a master record to all related detail records. Our Warehouse app needs to deviate from this default behavior and employ a trigger that prevents the deletion of Invoices that have Line Items.

Step 1: Create a Database Trigger

To create a trigger on the Invoice object.

1.       From Setup, enter Objects in the Quick Find box, then select Objects and click Invoice.

2.       Scroll down to Triggers and click New.

3.       In the editor, replace <name> with DeleteRestrictInvoice.

4.       Similarly, replace <events> with before delete.

5.       Replace the template code with the following.

6.       Click Save.

trigger DeleteRestrictInvoice on Invoice__c (before delete) {

// create a list of Invoices in Trigger.oldMap along with their Line Items

List<Invoice__c> invoices = [Select i.Name, (Select Name From Line_Items__r) From Invoice__c i                                                             Where i.Id IN :Trigger.oldMap.keySet()];

// loop through the Invoices, attaching errors to those that have Line Items

for (Invoice__c invoice : invoices) {

if (!invoice.Line_Items__r.isEmpty()) {

Trigger.oldMap.get(‘Cannot delete Invoice with Line Items’);




Step 2: Manually Test the Trigger

To test that the trigger does what you want it to, open an invoice that has line items, and click Delete. When you do, you should see an error.

Manually Test the Trigger

Next, try to delete an invoice that does not have any line items to make sure that the trigger does not prevent the deletion of such invoices.


“Know more about Salesforce Consulting at Techila”

Author: techila

No Comments

Post A Comment