1

Is there any way possible that I can create a new assignment rule on lead via Apex code. If possible can someone help me with the code snippet for the same. Also is it possible to transfer assigment rule via Unmanaged Package from one org to another?

2 Answers 2

2

@happy
I want to make below points:
1) Assignment rules are used to update ownerid field. We can always have this solution with clicks instead of code.
2) Now coming to your requirement we can easily create this in apex class, trigger.
Taking an example of case assignment below:

for (case c : []Select Id,origin from case]){
    if(c.origin==phone){
    c.ownerid='User id or Queue Id';
    }
    else if(c.origin==web){
    c.ownerid='User id or Queue Id';
    }
}

However, if you want to fire assignment rules from apex we have to use Dmloptions class and set assignment header.

    //Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];

//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;

Case newCase = new Case(Status = 'New') ;
//Setting the DMLOption on Case instance
newCase.setOptions(dmlOpts);
insert newCase ;

However, from your question it looks like you want to create metadata and save in salesforce. For this go through metadata api guide. Now if you want to create a assignment rule via metadata api please check the below link:

https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_assignmentrule.htm

Here you can find how to create metadata using apex:

http://andyinthecloud.com/2013/10/27/introduction-to-calling-the-metadata-api-from-apex/

-1

This will help you all much more

http://developer.force.com/cookbook/recipe/running-case-assignment-rules-from-apex

1
  • Thanks, but my question was to create assignment rule via apex code/ metadata, not to run it via apex.
    – happy
    Oct 28, 2015 at 6:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .