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
Yuvaraj mayilsamy 9Yuvaraj mayilsamy 9 

Trigger to update master record's field when child record is inserted.

Hi, 

I have two objects employee__c and department__c where employee__c is the child object for department__c. My requirement is if a child record is added then the description__c field in master record should get updated. Below  is my code but it is showing Error: Compile Error: IN operator must be used with an iterable expression at line 3 column 36. Any help is appreciated.
 
trigger descriptionupdate on Employee__c (after insert) {
map<id, employee__c> myid = new map<id, employee__C>([select id, department__r.id from employee__c where id in:trigger.new]);
list<department__c> depstoupdate = [select name, description__c from department__C where id in:myid];
for(department__c d : depstoupdate){
d.description__c = 'The last employee added to this department is on ' +system.today();
}
update depstoupdate;
}

 
Ramesh y 10Ramesh y 10
try below code, but you can achieve same requirement using process builder instead of writting a trigger.

trigger descriptionupdate on Employee__c (after insert)
{

Set<ID> deptIDset= new Set<ID>();
for(Employee__c ec:Trigger.New)
{
  if(ec.department__c!=null)
  deptIDset.add(department__c);
}
List<Department__c> updateDeptList= new List<Department__c>();
for(Department__c dc:[select id, description__c from Department__c where id in:deptIDset)
{
dc.description__c='The last employee added to this department is on ' +system.today();
updateDeptList.add(dc);
}

if(updateDeptList.size()>0)
update updateDeptList;

}

please mark it best answer if it works.

thanks
R
Yuvaraj mayilsamy 9Yuvaraj mayilsamy 9
Hi Ramesh,

 Thanks for your time. The code shows no error. But after adding employee i still see the description field of department as blank only.

Yuvaraj
Yuvaraj mayilsamy 9Yuvaraj mayilsamy 9
Hi Ramesh,

 Achieved this using simple query.
 
trigger updatedescription on Employee__c (after insert) {
   
    set<id> myids = new set<id>();
    for(employee__c e : trigger.new){
       myids.add(e.department__C);
         }
    list<department__C> deps = [select description__c from department__C where id in : myids];
    for(department__C d : deps){
        d.description__C ='The last added employee is on ' +system.today();
    }
    update deps;

}