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
ApexDevApexDev 

Apex Trigger to make checkbox true on standard object when field on second standard object is filled

Hi everyone! :) 

I have 2 standard object on Salesforce: Case and Asset. On Case object I created 2 custom checkbox fields: 
- In_House_Service__c
- Field_Service__c
Depends of Preferred_Service_Location__c on Asset, the right checkbox should be true on Case:
- if In-house service on Asset - the In_House_Service__c should be true on Case
- if Field Service on Asset - the Field Service__c should be true on Case

I am super newbie in Apex, I don't know how to write the right code. Maybe do you have any examples, that I can build or base on it?

I will be grateful! Thank you!
AnkaiahAnkaiah (Salesforce Developers) 
Hi Andzela,

What is relationship between asset & case ? which one is parent and which one is child.?

Thanks!!
ApexDevApexDev
Hi Ankaiah! 

The problem is because to each Case we can add multiple records of Devices (Asset). And also one Device (Asset) can be added to multiple Case records. So in this situation I think device is the Child.. 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Andzela,

try with below code.
trigger UpdateAmount on Asset (after insert, after update) { 
  Map<ID, Case> ParentCases = new Map<ID, Case>(); 
  List<Id> listIds = new List<Id>();

  for (Asset childObj : Trigger.new {
  If(childObj.Preferred_Service_Location__c=='In-house service' || childObj.Preferred_Service_Location__c=='Field Service'){
    listIds.add(childObj.Case__c);
	}
  }

  //Populate the map. Also make sure you select the field you want to update, amount
  //The child relationship is more likely called devices__r (not device__r) but check
  //You only need to select the child devices if you are going to do something for example checking whether the device in the trigger is the latest
  ParentCases = new Map<Id, Case>([SELECT id, In_House_Service__c,Field_Service__c,(SELECT ID, Preferred_Service_Location__c FROM Assets__r) FROM Case WHERE ID IN :listIds]);

  for (Asset device: Trigger:new){
     Case myParentcase = ParentCases.get(device.Case__c);
	 If(device.Preferred_Service_Location__c=='In-house service'){
     myParentcase.In_House_Service__c = true;
  }else if(device.Preferred_Service_Location__c=='Field Service'){
  myParentcase.Field_Service__c = true;
  
  }

  update ParentCases.values();
}

Replace the API names as per your org.

If this helps, Please mark it as best answer.

Thanks!!