function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rob.RosenRob.Rosen 

Trigger to Change Case Owner When Case Created from Customer Portal

Hi all,

 

I am very much a newbie at Apex development.  What I'm trying to do is automatically assign cases when they are created by our customers using the Customer Portal.  Case Assignment Rules are just not flexible enough for what I want:  I want the owner to be grabbed from a custom field on the related Account object (that field is named Support_Manager__c, and is a User lookup).

 

Here's what I've got:

 

trigger AddSupportOwnerToPortalCase on Case (before insert) {

	for (Case c : Trigger.new) {
		User u = [Select Id, PortalRole From User where ID = :c.CreatedById];
		if (u.PortalRole.contains('Customer')) {
			Account a = [Select Id, Support_Manager__c From Account where Id = :c.AccountId];
			c.OwnerId = a.Support_Manager__c;			
		}
	}
}

 If I try this using BEFORE insert, I get an error that says "Apex trigger AddSupportOwnerToPortalCase caused an unexpected exception, contact your administrator: AddSupportOwnerToPortalCase: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AddSupportOwnerToPortalCase: line 8, column 1".

 

If I try AFTER INSERT, I get an error on the line c.OwnerId = a.Support_Manager__c saying that the record is read-only.

 

Thanks very much for any help!

Rob

Subhash GarhwalSubhash Garhwal

Hi Rob,

 

In before insert trigger the account id is null, so you need to fire your trigger on after insert.

 

one more thing you query user and account in loop so by doing this you can hit apex Governors limits

 

For Apex Governors limits you can follow this link

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_gov_limits.htm

 

In your trigger you can update case owner like this way

 

trigger AddSupportOwnerToPortalCase on Case (after insert) {

 

List<Case> cases = new List<Case>();

 

for (Case c : [Select Id, OwnerId, CreatedById, CreatedBy.PortalRole, AccountId, Account.Support_Manager__c From Case

Where Id IN : Trigger.newMap.keySet()) {

 

if(c.CreatedBy.PortalRole.contains('Customer')) {

c.OwnerId = Account.Support_Manager__cSupport_Manager__c;
cases.add(c);
}
}
if(cases.size() > 0)
update cases;
}

 

Thanks

 

Hit the Kudos button (star)  and Mark as solution if it post helps you