trigger CaseOwner on Case (before insert,before update) {
    for (Case CaseRecord : Trigger.New) {
     if (CaseRecord.Owner != null) {
       List<user> findDivision = [select id from user
                                    where name = :CaseRecord.Owner];

I know this may be a silly question. I am getting above compile error for the above code snippet. All i am trying is to get ID by matching name field from user with case record owner field and since case record owner is picklist, i am getting this error. Can someone help in this?


It's not a picklist, it's a lookup field. A lookup field holds an ID, and also has an "sobject" component. You're trying to reference the SObject Name (Owner is a Name type of object), but you really wanted the ID, which is referenced as OwnerId. "sobject" references are always initially null in a trigger, unless you query for them. Finally, you should not query in a loop, as you'll hit governor limits.

Here's a modified version:

Map<id, user> users = new map<id, user>();
for(Case record: Trigger.new) {
users.putAll([SELECT Division FROM User WHERE Id = :users.keySet()]);
for(Case record: Trigger.new) {
  if(users.get(record.ownerid) != null) {
    record.Owner_Division__c = users.get(record.ownerid).division;

Note that, because of assignment rules, the value in OwnerId may not be correct in a before trigger, or even an after trigger, so you may want to instead call a future method, use a workflow rule or process, or possibly even a formula field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.