+ Start a Discussion

Issue in apex trigger when using userinfo method.

Issue in apex trigger while retrieving the information from user object.


string uid = userinfo.getUserId();


User[] user = [select name from User where u.Id = uid];



for this i am getting an exception in apex trigger as:


Too many SOQL queries: 21

I tried using sets but how do we get total collection of userInfo to iterate in for loop and add ids of users to set .

please let me know if any soln.




Can you post your code?





userinfo.getUserid() gets the current user's id not ids that you pass in.

If you are simply trying to get the name of the current users name you can use userinfo.getUserName()


Please provide a better description of what you are trying to do with this trigger.




Here i am retrieving a custom field. not just the name of the user.

Below is the query:


String userid= userinfo.getUserId();


User[] userType = [select u.custom__c from User u where u.Id=:userid limit 1];


the exception is:


Apex script unhandled trigger exception by user/organization: 00540000001RUm8/00D300000001EBY

caused by: System.Exception: Too many SOQL queries: 21



You are running into a governance limit.


Triggers have a governance limit of 20 SOQL statements per transaction across all triggers. 


You could use UserInfo.getUserType() to get the current usertype without using a SOQL statement.


I would recommend reviewing the governor limits in the Apex Dev Guide.


Good luck.




Here is my code....


Now, how can we avoid governor limit for this....

I have tried applying Limit and also making use of set ...



trigger Test on Lead (before insert,before update)
    Lead [] lead_new = Trigger.new;
    Lead [] lead_old = Trigger.old;    
    Set<Id> newLead = new Set<Id>();
    public id id1;
    public id id2;
    private User varuser;
    id1 = userinfo.getProfileId();
    id2 = userinfo.getUserId();
   varuser =[Select IsActive , Name from User where Id= :id2];
   System.debug('UserName ' + varuser.name);

    for (Integer k = 0; k <lead_new.size(); k++)
      // Updation Takes place..