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');
        }        
    }
}

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

2 Answers 2

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');
        }        
    }
}
0
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');
        }        
    }
}
5
  • 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
    Commented May 17, 2016 at 6:09
  • I think addAll won't work here. Incompatible argument types.
    – Mr.Frodo
    Commented May 17, 2016 at 6:10
  • @Ratan thanks for pointing out. I just overlooked that :) updated
    – Himanshu
    Commented May 17, 2016 at 6:12
  • @Himanshu great now looks good..
    – Ratan Paul
    Commented May 17, 2016 at 6:12
  • i guess your answer covers mine.so removing it :)
    – Mr.Frodo
    Commented May 17, 2016 at 6:13

You must log in to answer this question.

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