About

Edit photo

Wednesday, February 8, 2017

Find count of related list records in parent object - salesforce


Scenario-1): If a customer is already existed with a transaction, then need to throwh the error message.

I would like to find the number of child records in the parent object. here i can use related list i.e. "__r" and  can find the __r size by writing "inner query".

In my example, transaction is child, and customer is parent object.

trigger tranToCustomer on transaction__c (before insert,before update)
{
    if(trigger.isbefore)
    {
        set<id> setCustID = new set<id>();
        for(transaction__c tran: trigger.new)
        {
            setCustID.add(tran.customer__c);
        }
     
        map<id,customer__c> mapCustomer = new map<id,customer__c>([select id,name,(select id from transactions__r) from customer__c where id in:setCustID]);
     
        for(transaction__c tran:trigger.new)
        for(customer__c cust:mapCustomer.values())
        {          
                if(cust.transactions__r.size() > 0)
                {
                    tran.adderror('cannot create a record under customer, because one transaction is already exist');
            }
        }
    }
}

0 comments:

Post a Comment