2

I have a custom object that I want to set a unique key based on on lookup values. When I tried to create a workflow update I was blowing past the size limit so I developed it into a trigger and it seems to be working as intended.

I thought since I am already developing a field update trigger, I might as well add on a default name method so everything is contained into one file as opposed to having workflow and triggers updating the record.

When I introduced this method it returns "null null".

public static void setRecordName(List<Responsible_Party__c> newList)
{
    for(Responsible_Party__c r : newList)
    {
        r.Name = r.Practice__r.Name + ' ' + r.User__r.Name;
    }
}

Where practice is a lookup to another custom object and user is a lookup to the user object.

If I change the values to just use the field:

public static void setRecordName(List<Responsible_Party__c> newList)
{
    for(Responsible_Party__c r : newList)
    {
        r.Name = r.Practice__c + ' ' + r.User__c;
    }
}

I get "a1Gg00000049v9xEAA 005A0000006ykwnIAA". How can I get the names to display and not null?

5

You need to perform a separate query to retrieve names. Salesforce doesn't return values from related object's fields, though it will not give you the error rather it returns null.

Here is an approach:

public static void setRecordName(List<Responsible_Party__c> newList)
{
    Set<Id> Ids = new Set<Id>();
    for(Responsible_Party__c r : newList)
    {
        Ids.add(r.Id);
    }

    Map<Id,Responsible_Party__c> mapRP = 
                            new Map<Id,Responsible_Party__c>(
                                                [SELECT Id, Practice__r.Name, User__r.Name 
                                                 FROM Responsible_Party__c 
                                                 WHERE Id IN:Ids]);

    for(Responsible_Party__c r : newList)
    {       
        //you can perform null check before executing following line.
        r.Name = mapRP.get(r.Id).Practice__r.Name + ' ' + mapRP.get(r.Id).User__r.Name;
    }
}
1

In trigger context you can reach only fields from processed object level. This means no relation fields are available. Although you can get those values in 3 ways - either use SOQL query, formula field or workflow.

You can create formula field on your custom object to display Name value from parent record and use them in your trigger code to set default value for your custom object's Name field.

0

From memory, the field on parent records aren't available in a trigger.

Why don't you just use a workflow with a formula instead?

  • I thought it'd be easier to just code it all together. – Dan Wooding Aug 15 '17 at 4:12

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.