+ Start a Discussion
rajmullrajmull 

Triggers:consisting of insert,update,delete on two objects.

hi,

            I have 2 objects  Employee and Department.                         Fields are..................        

 

Employee                                                   department

 

-----------                                                   ---------------

empname:                                              deptname

dept(lookup)                                          no_of_employees

 

No of employees   should be reflected for each insert,update,delete.

 

There are 3 cases in this...

 

1.  If i add employee and department(lookup) in Employee object......No of Employee should be increased...N

2.   if i delete an employee of a particular department...it should less 1 from No of Employee..

3   If i update employee department to another department...it should be reflected on both the departments...ie.-1from           current department...and +1 to the updated department..

 

                                                                          Thank you

Best Answer chosen by Admin (Salesforce Developers) 
sfcksfck

Most simple way: change the lookup to a master/detail, and add a rollup summary. If you do this, though, deleteing a department will delete all its employees - probably not what you want.

 

Next most simple way:  fire a trigger every time an employee is updated, inserted, deleted or undeleted, and have it update all the departments, like this:

 

department__c[] depts = [select id, employees__r from department__c];
for (department__c dept : depts)
{
    dept.number_of_employees__c = dept.employees__r.size();	
}
update depts

Slightly more complex, but more optimized, ways - In the trigger, get the department Id's of all the new/changed/deleted employees and run the above code just on them.