About

Edit photo

Showing posts with label collections. Show all posts
Showing posts with label collections. Show all posts

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');
            }
        }
    }
}

Wednesday, February 1, 2017

Insert Bulk records using collections





Create 10 records into account, and create 10 to contact and 10 to opportunities, and map the account name.

//Insert bulk records

list<contact> conlist = new list<contact>();
list<opportunity> opplist = new list<opportunity>();
list<account> acclist = new list<account>();

for(integer i=0;i<10;i++)
{
 account acc = new account();
 acc.name = 'account'+i;
 acc.AccountNumber = '234321';
 acclist.add(acc);
}
insert acclist;

for(integer i=0;i<10;i++)
{
 opportunity opp = new opportunity();
 opp.name = 'account'+i;
 opp.closedate = Date.parse('1/27/2017');
 opp.stagename = 'Prospecting';
 opp.accountid = acclist[i].id;
 opplist.add(opp);
}
insert acclist;

for(integer i=0;i<10;i++)
{
 contact con = new contact();
 con.lastname = 'account'+i;
 con.Department = 'account department';
 con.accountid = acclist[i].id;
 conlist.add(con);
}
insert acclist;