I have 3 objects:

1)User(field: UserTextField__c )

2)Project__c is the parent of object__c

3)object__c is child of user(fields: project__c(lookup), user__c)

In object__c for single user having single record (multiple records restricted) only. I want to display project__r.name of user on his user object custom field(UserTextField__c ).

I tried with the following code: It is displaying id of the project__c in user's field(UserTextField__c).

I tried with the obj.project__r.name but it is giving empty value.

trigger UpdateFieldOnUser on Object__c (before insert, before update) {
    //id of user to update the field 
    list<id> userids= new list<id>();
    if(trigger.isinsert || trigger.isUpdate){
        for(Object__c obj: trigger.new)
            user usr=[select id, UserTextField__c from user where id =:userids];
            usr.UserTextField__c= obj.project__c; 
            update usr;


You have a query in a for loop! But in fact, you do not even need to query for the User records. Just remove that query entirely. You do, however, need to query the records related by LookupField__c. This is bulkification 101:

  • Collect Id values
  • Query for records outside your loop and map by Id

That typically looks like:

Set<Id> parentIds = new Set<Id>();
for (Object__c record : trigger.new)
Map<Id, Parent__c> parentRecords = new Map<Id, Parent__c>([
    SELECT Name FROM Parent__c WHERE Id IN :parentIds

Then you would change your original loop to:

Map<Id, User> relatedUsers = new Map<Id, User>();
for (Object__c record : trigger.new)
    Parent__c parentRecord = parentRecords.get(record.Lookup__c);
    // because you already queried and mapped the records, no query required inside loop

    if (parentRecord != null && record.User__c != null)
        relatedUsers.put(record.User__c, new User(
            Id=record.User__c, UserTextField__c=parentRecord.Name
update relatedUsers.values();
// perform DML outside loops as well

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.