function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
avimeiravimeir 

Problem with triggers + relationships

Hi,

 

I have an object that creates association of two custom objects: Reservation and Room. I am trying to do something when a new association is created. This is the code I have:

 

trigger handleNewRoomResaAssociation on ReservationRoomAssociation__c (after insert) {
    for (ReservationRoomAssociation__c assoc : Trigger.New)
    {
        System.debug(assoc.Room__r.Name);
        
      
    }

}

 

The debug returns null, as if there is no Room__c object associated. What am I doing wrong?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You probably need to store these in a map keyed by the id so that you can retrieve the appropriate record.  Something like:

 

Map<Id, Room__c> rooms=new Map<Id, Room__c>();

List<Id> roomIds=new List<Id>();

for (ReservationRoomAssociation__c assoc : Trigger.New)
{
   roomIds.add(assoc.Room__c);
}

rooms.putAll([select id, Name from Room__c where id in :roomIds];

for (ReservationRoomAssociation__c assoc : Trigger.new)
{
   Room__c room=rooms.get(assoc.Room__c);
   System.debug(room.Name);
}

 

All Answers

bob_buzzardbob_buzzard

If you need values from related records you have to query those back yourself.  The record in the trigger will only have the ID field populated in assoc.Room__c. 

avimeiravimeir

How do I do this?

 

Been struggling with related fields for 2 days now and I am starting to go crazy :P

 

 

bob_buzzardbob_buzzard

You probably need to store these in a map keyed by the id so that you can retrieve the appropriate record.  Something like:

 

Map<Id, Room__c> rooms=new Map<Id, Room__c>();

List<Id> roomIds=new List<Id>();

for (ReservationRoomAssociation__c assoc : Trigger.New)
{
   roomIds.add(assoc.Room__c);
}

rooms.putAll([select id, Name from Room__c where id in :roomIds];

for (ReservationRoomAssociation__c assoc : Trigger.new)
{
   Room__c room=rooms.get(assoc.Room__c);
   System.debug(room.Name);
}

 

This was selected as the best answer