Get the Object Id

When I have to use an Id which is the best way to put it in a variable?

okkay hard coding an ID is bad.

Actually i’m doing:

 user u=[Select id,name from user where name=.. limit 1 ];;

But make this query for me is also a bad solution.

If you after change the name of the user(the same for other resources or objects) ,
get id won’t work again.
This is a problem for me ever, i have this doubt everytime i’m getting an id from an object,resource..

the best solution is use custom setting?

Thanks to all for the reply.

you are very kind!


If you specifically know which user to associate and using a query to retrieve the user Id then there are multiple places like custom labels/ custom settings where you can save the Id’s and use a map/ string and pull the ID value

say for eg. When you have to assign a region to a particular salesrep and the rep is not constant,all you do is:

Create a custom setting ( my choice) and save North america and put the user id as the Salesforce user id of the rep.

Lookup on how to create a custom setting and manage data.

If at all you feel custom settings are hard to get at the first go try custom labels. This is one way you can minimize hard coding.

enter image description here

In your apex class you can do :

String user_Id = Label.North_america_Rep_ID;

In the VF page you can do the same as

This is how you make use of custom settings

step 1: Go to Setup--> Develope --> custom setting --> New

Once you hit new this is similar to creating a new custom object in salesforce.

step2: Name the custom setting and set

Settting Type : List
Visibility : Public
save the new custom setting

Step3: create a new custom field and choose "text" and hit next and save.

Step4: Once save is compelete go back to the custom setting and then click on manage.
Step5: You should be able to see 2 fields 1) Name 2) custom field you created

Think of this as a dictionary

Name     My custom Field
user1    005user1id
user2    005user2id
user3    005user3id

Once you have set up your custom setting you can use the custom setting in your apex as below

map<string,string> Custom_setting_map = new map<string,string>();

//Get all the values from the custom setting.
for(customsetting custom: customsettingname.getall().values()){

and then for the user1 you can do

    string user_id = '';
//get current user's username and check if the custom setting has the username in the key.
     user_id = custom_setting_map.get(;

Source : Link , Question Author : Enry , Answer Author : Rao

Leave a Comment