1

I've written a trigger that is called when child record is inserted. I want the room(Parent) status to be updated to Occupied when the patient(Child) closure is set to false.

Here's the code that I had work once and now I can't seem to find the error

public static void roomStatusOccupied(List<Patient__c> pList){
        Set<Id> roomIds = new Set<Id>();
        for(Patient__c p:pList){
            if(p.Closure__c==false){
                roomIds.add(p.Rooms__c);
            }
        }
        if(roomIds.size()>0){
            List<Rooms__c> toBeUpdated = new List<Rooms__c>();  
            for (Rooms__c room : [SELECT Id,Status__c FROM Rooms__c WHERE Name IN :roomIds]) {
                room.Status__c='Occupied';
                toBeUpdated.add(room);
            }
            update toBeUpdated;
        }
    }

I'd written a different code to work not just on insert but also update but that doesn't work either. What am i doing wrong ?

1 Answer 1

1

You are querying the rooms by their name instead of their database identifier.

Instead of WHERE Name IN use WHERE Id IN.

An improved version of your snippet, with an early return and a more selective query, would look like this:

public static void roomStatusOccupied (List<Patient__c> pList) {
    Set<Id> roomIds = new Set<Id>();

    for (Patient__c p : pList) {
        if (!p.Closure__c) {
            roomIds.add(p.Rooms__c);
        }
    } 

    // check if rooms are empty and return early if there's nothing to
    // execute below
    if (roomIds.isEmpty()) {
        return;
    }

    List<Rooms__c> rooms = new List<Rooms__c>();  
    
    // fetch rooms and update their status, but only for those rooms that are
    // not occupied already
    for (Rooms__c room : [SELECT Id, Status__c FROM Rooms__c WHERE Name IN :roomIds AND Status__c != 'Occupied']) {
        room.Status__c = 'Occupied';
        rooms.add(room);
    }

    // no need to worry if "rooms" is empty or not.
    // if it is, the system is smart enough to not consume a DML
    update rooms;
}
2
  • Thanks for the advice. This code makes sense and the test class seems to pass it but when manually creating a new patient it doesn't seem to work. There may be an issue somewhere else ? Any further advice is much appreciated Nov 14, 2023 at 11:05
  • You should probably look at the code that calls this roomStatusOccupied method then. Nov 14, 2023 at 12:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .