Skip to main content

//Handler Class

public class InvoiceClass {

public static void invoiceProduct(List<Invoice_Product__c> invProduct){

for(Invoice_Product__c inv : invProduct){

inv.Total_Price__c = inv.Price__c * inv.Quantity__c;

}

}

public static void invoiceAmountUpdate(List<Invoice_Product__c> invProduct ){

Set<id> invoiceIds = new Set<id>();

for(Invoice_Product__c invPro : invProduct){

if(invPro.InvoiceLookUp__c != Null){

invoiceIds.add(invPro.InvoiceLookUp__c);

}

}

List<Invoice__c> invoices = [Select id, Total_Amount__c, (Select id, Total_Price__c

From Invoice_Products__r)

From Invoice__c where id in : invoiceIds];

for(Invoice__c inv: invoices){

inv.Total_Amount__c = 0;

for(Invoice_Product__c invProd : inv.Invoice_Products__r){

inv.Total_Amount__c += invProd.Total_Price__c;

}

}

if(invoices != Null){

update invoices;

}

}

}

//trigger

trigger InvoiceProductTrigger on Invoice_Product__c (before insert, before update, after insert, after update, after delete) {

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

InvoiceClass.invoiceProduct(Trigger.new);

}

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

InvoiceClass.invoiceAmountUpdate(Trigger.new);

}

if(Trigger.isAfter && Trigger.isDelete){

InvoiceClass.invoiceAmountUpdate(Trigger.old);

}

if(Trigger.isAfter && Trigger.isUpdate){

InvoiceClass.invoiceAmountUpdate(Trigger.old);

}

}

 
9 件の回答
  1. 2020年1月15日 13:24
    Hi 

    trigger InvoiceProductTrigger on Invoice_Product__c (before insert, before update, after insert, after update, after delete) {

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

            for(Invoice_Product__c inv : trigger.new){

                Set<id> invoiceIds = new Set<id>();

                inv.Total_Price__c = inv.Price__c * inv.Quantity__c;

                if(invPro.InvoiceLookUp__c != Null){

                    invoiceIds.add(invPro.InvoiceLookUp__c);   

                }

            }

            

            for(Invoice__c inv: [Select id, Total_Amount__c, (Select id, Total_Price__c

                                                                      From Invoice_Products__r)

                                         From Invoice__c where id in : invoiceIds]){

                inv.Total_Amount__c = 0;

                for(Invoice_Product__c invProd : inv.Invoice_Products__r){

                    inv.Total_Amount__c += invProd.Total_Price__c;

                }

            }

            

            

        }

    You dont have to write DML stmt inside before context.