1

Requirement - Checkbox in User NoOwner__c. If it is checked and I am going to update account Owner then it needs to throw an error else needs to save record.

I am getting error Invalid initial value type List<User> for Set<Id>. Can someone please help me to sort this issue or any other way to write trigger for it,as I am new to trigger I have written my own way.


trigger updateOwnerID on Account (after update) {
    set<id> OwnerIds=new Set<id>();
    for (Account acc:trigger.new){
        OwnerIds.add(acc.ownerid);
    }   
    set<id> userids=new set<id>([select id from user where id in :OwnerIds and NoOwner__c=true]);
    for(Account acc:trigger.new){
        if(userids.contains(acc.ownerid)){
            acc.adderror('You cannot asign this user');
        }        
    }
}

  • I think issue is in your query. SOQL returns List<User> and you are saving it Set<Id>. – Mr.Frodo May 17 '16 at 5:46
2

you can not assign a value to the set with query. Try the code below :

trigger updateOwnerID on Account (after update) {
    set<id> OwnerIds=new Set<id>();
    for (Account acc:trigger.new){
        OwnerIds.add(acc.ownerid);
    }   
    map<id,User> userids=new map<id,User>([select id from user where id in :OwnerIds and NoOwner__c=true]);
    for(Account acc:trigger.new){
        if(userids.containsKey(acc.ownerid)){
            acc.adderror('You cannot asign this user');
        }        
    }
}
2

SOQL query return List of sObjects instead of set so you need to modify your code in following way

trigger updateOwnerID on Account (after update) {
    set<id> OwnerIds=new Set<id>();
    for (Account acc:trigger.new){
        OwnerIds.add(acc.ownerid);
    }   

    //Get list of users in a list and then add to set.
    set<id> userids=new set<id>();
    for(User objUser : [select id from user where id in :OwnerIds and NoOwner__c=true]){

    userids.add(objUser.id);
    }
    for(Account acc:trigger.new){
        if(userids.contains(acc.ownerid)){
            acc.adderror('You cannot asign this user');
        }        
    }
}
  • Just wanted to clarify Himanshu.. Can we do this set<id> userids=new set<id>(); userids.addAll(usersList); means can we add the list of user into set of Ids ? – Ratan Paul May 17 '16 at 6:09
  • I think addAll won't work here. Incompatible argument types. – Mr.Frodo May 17 '16 at 6:10
  • @Ratan thanks for pointing out. I just overlooked that :) updated – Himanshu May 17 '16 at 6:12
  • @Himanshu great now looks good.. – Ratan Paul May 17 '16 at 6:12
  • i guess your answer covers mine.so removing it :) – Mr.Frodo May 17 '16 at 6:13

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.