Fix my first trigger!

I recently had a request from one of the Salesforce Administrators in my company to ‘fix’ a trigger he had stumbled upon that wasn’t doing what it was supposed to.

The requirement for the trigger was to update the ‘Last Meeting Date’ custom field added to the User standard object when a Meeting (custom object) record was created.

The initial state of the trigger is below and I was asked to fix it.

trigger updateLastMeetingDate on Meeting__c (After Insert) {

//Get a list of all Meetings that the trigger will run on
    List<Meeting__c> meetings = new List<Meeting__c>(); 
        meetings = Trigger.new;
    
//Get a list of all users
    List<User> UsersToUpdate = new List<User>(); 

//Run through each Meeting that the trigger is running against and get it's Owner's User Record ID, 
//then update the date on that record
    For(Meeting__c m:meetings){
        User U = [SELECT ID, Name, Last_Meeting_Date__c FROM User where ID=:m.OwnerID ];
        U.Last_Meeting_Date__c = Date.today();
    }   
    
    Update UsersToUpdate;
    
}

I have been showing this to my Apex students and one of them made a very elegant simple trigger. I’m adding spaces here just in case you want to try it before seeing his solution!

 

 

 

 

 

The Solution:

trigger updateLastMeetingDate on Meeting__c (After Insert) {
	Set<user> owners= new Set<user>();
	for(meeting__c m:trigger.new){
		owners.add(new user(id=m.ownerId,Last_Meeting_Date__c=Date.Today()));	
	}
	update owners;
}