Activity Forums Salesforce® Discussions Issue with After Trigger And Before Trigger in Salesforce

  • Issue with After Trigger And Before Trigger in Salesforce

    Posted by Vikas Kumar on December 8, 2016 at 2:54 pm

    Hi All,

    this trigger is not working

     

    trigger ClosedOpportunityTriggera on Opportunity (before insert,before update) {
    List<Task> toBeAddedTasks = new List<Task>();
    for(Opportunity A:[SELECT id FROM Opportunity WHERE StageName = 'Closed Won' AND id IN :Trigger.New])
    { toBeAddedTasks.add(new Task(Subject = 'Follow Up Test Task', WhatId = A.Id)); }
    upsert toBeAddedTasks; }

    it is working when i change before insert to after and before update to after

    trigger ClosedOpportunityTriggera on Opportunity (after insert,after update) {
    List<Task> toBeAddedTasks = new List<Task>();
    for(Opportunity A:[SELECT id FROM Opportunity WHERE StageName = 'Closed Won' AND id IN :Trigger.New])
    { toBeAddedTasks.add(new Task(Subject = 'Follow Up Test Task', WhatId = A.Id)); }
    upsert toBeAddedTasks; }

     

    i need to know why it is not working similar in both scenario

    thanks

     

    Kumar replied 7 years, 11 months ago 2 Members · 1 Reply
  • 1 Reply
  • Kumar

    Member
    January 10, 2017 at 11:01 am

    Hi Vikas,

    The reason your code is not working the same in the 'before' trigger is because the new opportunity you have inserted has still not been committed in the database, hence it does not have a Id value for now which you are querying here:

    for(Opportunity A:[SELECT id FROM Opportunity WHERE StageName = ‘Closed Won’ AND id IN :Trigger.New])

    Hope this helps.

     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos