[SalesForce] Salesforce Variable does not exist: String

Hey guys so I am trying to write an APEX function that checks if the users company name or department is blank then displaying two different types of strings depending if they are blank or not. However I am trying to define a variable and it keeps giving me this error:

Variable does not exist: String

This is the code for the APEX class:

public class bbGetInfoController {
public String getName() {
    return 'bbGetInfoController';
}

public String getDetails() {
    String result = null;
    if(String.isBlank(User.CompanyName) || String.isBlank(User.Department)) {
        result = 'You either have no company or department set!';
            } else {
                result = 'You work at {!$User.CompanyName} in the {!$User.Department} department.';
            }
    return result;
}

}

Best Answer

You're trying to call:

String.isBlank(SObjectField)

Which is not a valid function. You need to query your user first, then reference that instance:

public String getDetails() {
    User currrentUser = [SELECT CompanyName, Department FROM User WHERE Id = :UserInfo.getUserId()];
    if(String.isBlank(currentUser.CompanyName) || String.isBlank(currentUser.Department)) {
        result = 'You either have no company or department set!';
    } else {
        result = 'You work at '+currentUser.CompanyName+' in the '+currentUser.Department+' department.';
    }
    return result;
}

Fields can referenced as tokens using Object.Field, where Object is any object you can access (User, Account, etc), and Field is the API name of the field. This lets you reference fields dynamically.

See the SOBjectField class for more details on how field tokens work.

Note that {!mergefields} doesn't work in Apex Code, except in some limited instances (notably, using dynamic components with expressions). You generally want to use the + operator to concatenate strings.