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
SRI RAM ASRI RAM A 

Parent record can only closed when child record status 'completed' or 'delivered'

For example, we have a custom object called "Internal Task" which is related to the Case object through a lookup field.
What I would like to setup is 
A Case can only be closed, if the following is True:
All related Stories are in a status of "Delivered", "completed
How to write trigger for this.
CarlosLimaCarlosLima
Fire a trigger every time it is before update the case, so on the case object search for the related Internal task (one or all), once all of the values of the field in internal task mark as completed you update the case object, otherwise a message will appear.
trigger CaseTrigger on Case (before update)  {
    
    for (Case vCase : trigger.new) {
        if(vCase.InternalCase__.Status__c == 'Delivered')  {
        vCase.addError('Cannot update this records with Open Delivered status');
       
       }
    }
Wilfredo Morillo 20Wilfredo Morillo 20

trigger CaseTrigger on Case (before update)  {
    
    // Get All Cases with related stories with status not delivered.
    //Change the caseid to the lookup field name for case
    List <Case> allCasesList = new list([select id 
                                        from case 
                                        where id in (select caseid 
                                                  from Stories 
                                                  where status != 'Delivered')
                                                  and caseId in :trigger.newMap.keyset()]);


    for (Case c : allCasesList) {
        //If the case has stories with status different than delivered then add the error.
        if(c.stories != null){
        c.addError('Your Error Message');//Change the error to anything you want. 
       
       }
    }
}