if(User.FirstName != NULL && User.MiddleName != NULL && User.LastName != NULL) {

User usr = [SELECT FirstName,MiddleName,LastName FROM User WHERE 

System.debug('from if   FirstName  '+usr.FirstName);
System.debug('from if   MiddleName  '+usr.MiddleName);
System.debug('from if   LastName  '+usr.LastName);

Even, if FirstName & MiddleName are NULL, execution enters if loop. Why does this happen?

  • 2
    Please provide more context code. Do you have a variable named User? – Adrian Larson May 20 '19 at 4:44
  • I assume that User.FirstName automatically takes in current users FirstName. so i haven't declared it prior in my code. Is this right ?? – AshwinK9 May 20 '19 at 4:47

Visualforce has a global variable $User, there is no equivalent in apex.

In your code, Object.FieldName will return API name of field on the object with type Schema.SObjectType, you have to query User in an Object or list before the IF loop and use that for comparison.

  • Query approach worked. Thanks. – AshwinK9 May 20 '19 at 5:29

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.