开发者

Update opportunity when lead is inserted via trigger in salesforce

I want to write a bulk trigger (keeping governer l开发者_开发问答imits in mind) such that when a new lead is inserted whose 'x' field value is same as 'y' field value of some opporunity, It updates field 'z' of this opportunity.

I am new to salesforce and apex so facing problem.

Any help would be appreciated.

Thanks

Jitendra


Do you have any development experience? How many records are you dealing with? If you've got over 10k opportunities then you'll run into issues pretty quickly!

The (untested) code below should make sense if you are a developer, but remember you can only perform 20 SOQL queries allowing for 19 update calls with 200 records per call — so this will only work if you have a max of 3800 opportunities with any given value of Y. If you need more then you'll want to write a class that uses the Batchable interface and fire it from the trigger — you'll need to pass through the list of X values before calling execute on it so you can use them in the query (see here for the docs on Batch Apex.

trigger LeadAfterInsert on Lead (after insert)
{
    // assuming string for the type of fields X & Y
    set<string> setXValues = new set<string>();
    list<Opportunity> liOpptysToUpdate = new list<Opportunity>();

    for(Lead sLead : trigger.new)
    {
        setXValues.add(sLead.FieldX);
    }

    for(Opportunity [] sOpportunityArr : [select Id, FieldZ, FieldY
                                            from Opportunity
                                            where FieldY in : setXValues
                                            limit 1000])
    {
        for(Opportunity sOpportunity : sOpportunityArr)
        {
            // field logic here, e.g.
            if(sOppty.FieldY != 0)
            {
                sOppty.FieldZ ++;
            }

            liOpptysToUpdate.add(sOppty);

            // can only update 200 records at once so we check the list size here
            if(liOpptysToUpdate.size() == 200)
            {
                update liOpptysToUpdate;
                liOpptysToUpdate.clear();
            }
        }
    }

    // deal with any stragglers
    if(liOpptysToUpdate.size() > 0)
    {
        update liOpptysToUpdate;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜