- You don't need to activate a trigger just writing it is enough.
- You can access the changed new values Through Trigger.new (and Trigger.old for old values) For Trigger documentation refer here
- Maybe a workflow is more suitable to what you are trying to do. And finally don't worry too much from the start about standard of the code (or beauty), it makes difference only when your code gets big anyway.
Apex Trigger - Attempting to send an email after an update
-
04-06-2022 - |
Вопрос
so I have just finished a degree in computing and have just started industry related employment and wow... we really don't seem to learn much at uni, just the bare basics.
Anyway, I am learning Apex and attempting to write my first trigger. The online tutorials are pretty unforgiving and I find that they seem to all miss out what my brain is lacking.
I am writing a trigger to automatically send an email to a specified address, the sending the email part is fine however I want to send in the email what has been changed and read as to whether it anything has been changed. What I have so far is as follows:
trigger Test1 on Account (after update) {
if(Trigger.isUpdate) {
//Commit current transaction, reserver email capacity
Messaging.reserveSingleEmailCapacity(1);
//Create an email message object
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<Messaging.SendEmailResult> results = new list<Messaging.SendEmailResult>();
//hold email address
String[] toAddresses = new String[] {'example@example.com'};
//Assign new address string
mail.setToAddresses(toAddresses);
//specify return ad (assuming as being sent from server)
mail.setReplyTo('pwitherby@gmail.com');
//sender name
mail.setSenderDisplayName('Mr Apex Tester');
//Subject Specification
mail.setSubject('Subjected to Learning');
//And... the content
mail.setPlainTextBody('You have just changed sumek... this really what you want....?')
if (!results.get(0).isSuccess())
System.debug('That didnt really work did it? Reason: ' + results.get(0).getErrors()[0].getMessage());
}
}
So my main questions that I cant find an answer for: Will this work at current? so will this send this email if anything in the schema gets altered/updated? I want to put in the email body what has been altered and what it has been changed to i.e "you have changed " + whatsChanged + " to " + telephoneNumber. How do I listen for changes or is it already doing that? Am I writing this to a decent standard or is it just messy code!
Sorry to waffle, it is my biggest downfall however I struggle to augment my questions without it!
Решение