+ Start a Discussion
NishanNishan 

Custom relationship query

 

Hi Everyone,

                       I have the following code.

 

 

 

trigger InsertInfo on Inventory__c (before Update)
 {
    
    for(Inventory__c inv : trigger.new)
      {
         Inventory__c oldValue = Trigger.oldMap.get(inv.ID);
         { 
            
           if( inv.Remaining_Stock__c < oldValue.Remaining_Stock__c)
            { 
              
              Date date1 = Date.Today();
              String abc = String.valueOf(date1);
              Decimal numofgifts = oldValue.Remaining_Stock__c - inv.Remaining_Stock__c ;
              Integer integerValue = numofgifts.intvalue();
              String fe = inv.Field_Executive__r.Name;  // THIS IS WHERE MY PROBLEM IS
              String pqr = String.valueOf(integerValue);
                  inv.Issued_Dates__c   = inv.Issued_Dates__c + '\n' + abc +'\t\t'+ fe +'\t\t'+ pqr;
                  
            }
                 
         }
      }
  }
  

 Issued_Dates is a textbox. But instead of fe Name it displays null. Any idea where I am wrong ?

 

Thanks in advance

 

                              

 

          

Best Answer chosen by Admin (Salesforce Developers) 
souvik9086souvik9086

Hello,

 

You cannot get the value of

 

inv.Field_Executive__r.Name;

in this way.

 

You have to query the Inventory__c object to get its name. It cannot be fetched directly like this. LIKE

[select Field_Executive__r.Name from Inventory__c where id =: inv.id];

 

Then use that in the assignment

All Answers

souvik9086souvik9086

Hello,

 

You cannot get the value of

 

inv.Field_Executive__r.Name;

in this way.

 

You have to query the Inventory__c object to get its name. It cannot be fetched directly like this. LIKE

[select Field_Executive__r.Name from Inventory__c where id =: inv.id];

 

Then use that in the assignment

This was selected as the best answer
Dhaval PanchalDhaval Panchal
This is because you cannot access relationship fields in trigger directly (Field_Executive__r.name). You need to query this field otherwise it will not give any error but returns null value.
NishanNishan

I modified my code like this, but still not working

 

Id id1 = inv.Field_Executive__r.Id;
              List<Field_Executive__c> fe = [SELECT Id, Name
                                                 FROM Field_Executive__c WHERE Id =:id1];
              String fename = fe[0].Name;

souvik9086souvik9086

Do it like this

 

Id id1 = inv.Field_Executive__c;
              List<Field_Executive__c> fe = [SELECT Id, Name
                                                 FROM Field_Executive__c WHERE Id =:id1];
              String fename = fe[0].Name;

 

If the post is helpful please throw KUDOS