You need to sign in to do that
Don't have an account?
access current record id in trigger
I'm trying to access the current record id on the object on which the trigger is going to work. This will help me set the context, so that I can use that Id to obtain other fields from the object which I need to pass to other Apex clases/methods.I tried calling apex methods which used the currentPage() parameters to obtain the Id. But it gives me the following error. So I'm trying to get the current record information on the trigger itself and pass it onto relevant methods and classes
System.NullPointerException: Attempt to de-reference a null object:
Can anyone show me how I would accomplish this?
Thanks!!!
When a trigger is initiated, you will get an array of records in the Trigger.new and Trigger.old objects.
You can iterate through those and get the Id, plus the other fields on that record.
for example:
trigger testAccountTrigger on Account (after insert, after update){
for(Account a: Trigger.new){
System.debug('id is: ' + a.Id);
System.debug('name is : ' + a.Name);
}
}
trigger OpportunityVFEmail on Opportunity (after insert, after update) { for(Opportunity a: Trigger.new){ System.debug('id is: ' + a.Id); System.debug('name is : ' + a.Name); System.debug('same custom field: ' + a.same__c); if (a.stageName == 'Closed Won') { Contact con1 = [select id, name, email, accountid from Contact where accountid = :a.accountid limit 1]; System.debug('contact id: ' + con1.id); System.debug('contact name: ' + con1.name); System.debug('contact email: ' + con1.email); myOpportunityController b = new myOpportunityController(); b.getSamplevfpdf(a,con1); //Blob pdf = myOpportunityController.getSamplevfpdf(a); // System.debug('Blob content: ' + pdf); // sendPDFEmailClass.sendmyEmail(a, pdf, con1); } } }
I'm able to retrieve the information from the current record. Thanks. But I get an error saying
Error: Invalid Data. Review all error messages below to correct your data. Apex trigger OpportunityVFEmail caused an unexpected exception, contact your administrator: OpportunityVFEmail: execution of AfterUpdate caused by: System.VisualforceException: Getting content from within triggers is currently not supported.: Class.myOpportunityController.getSamplevfpdf: line 21, column 17
It is not letting me pass the parameters to the controller method.
public class myOpportunityController { public Opportunity getOpportunity() { return null; } public void getSamplevfpdf(Opportunity opp, Contact con1) { System.debug('vf opp id: ' + opp.id); System.debug('vf opp name: ' + opp.name); System.debug('vf opp accountid: ' + opp.accountid); // myOpportunityController a = new myOpportunityController(); PageReference samplevfpdf = Page.samplevfpdf; // samplevfpdf.getParameters().put('id',opp.id); samplevfpdf.getParameters().put('id',opp.id); Blob pdf1 = samplevfpdf.getContent(); //String pdfs = pdf1.toString(); sendPDFEmailClass.sendmyEmail(opp, pdf1, con1); // return pdf1; } }