Skip to main content
Hi,

I have custom object called ITEM

with three Fields:

  1. CUSTOMER   (lookup field from Account)
  2. LOCATION (lookup from field Well__c)
  3. PRIME CUSTOMER (checkbox)

 

I have another custom field: DIRECT INVOICE

where there are only two fields. This is kind of list of combination.

  1. CUSTOMER INVOICE  (lookup field from Account)
  2. LOCATION INVOICE (Lookup field from Well__c)

 

I need to write a trigger (after update, after insert) where if CUSTOMER and LOCATION from object ITEM matches with any of the records  with CUSTOMER INVOICE and LOCATION INVOICE from DIRECT INVOICE, then update a field PRIME CUSTOMER in item to TRUE.

 

I am maintaining a list of combination of customer invoice and location invoice in Direct invoice object, hence any new record of update record in object is to be checked with all records in Direct invoice to find if any records matches.

 

Thank you for your suggestion.

 
7 answers
  1. Dec 27, 2018, 2:27 AM

    Hi Sunil,

    First of all, you should use before insert and before update events, since you want to update trigger records. Trigger events of kind After, checks records as read-only.

    Take a look at the following code:

    trigger TriggerOportunidade on ITEM__c (before insert, before update ) {

        if( Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate) ) {

            List<ITEM__c> items = Trigger.new;

            Set<String> accountsIds = new Set<String>();

            Set<String> wellsIds = new Set<String>();

            for( ITEM__c item : items ) {

                if( item.Customer__c != null ) {

                    accountsIds.add( item.Customer__c );

                }

                if( item.Location__c != null ) {

                    wellsIds.add( item.Location__c );

                }

            }

            Map<String,Direct_Invoice__c> directInvoicesMap = new Map<String,Direct_Invoice__c>();

            for( Direct_Invoice__c di : [Select Customer_Invoice__c, Location_Invoice__c from Direct_Invoice__c where Customer_Invoice__c in :accountsIds and Location_Invoice__c in :wellsIds] ) {

                if( !directInvoicesMap.containsKey( di.Customer_Invoice__c + '-' +di.Location_Invoice__c ) ) {

                    directInvoicesMap.put( di.Customer_Invoice__c + '-' +di.Location_Invoice__c, di );

                }

            }

            for( ITEM__c item : items ) {

                if( directInvoicesMap.containsKey( item.Customer__c + '-' + item.Location_Invoice__c ) ) {

                    item.Prime_Customer__c = true;

                }

            }

        }

    }

    Hope that helps you somehow.

     

    Best regards.

0/9000