+ Start a Discussion
Kris WebsterKris Webster 

AfterInsert Error PLEASE HELP

I am attempting to upate a field on the Opportunity object with the project that gets created (that is associated to the opportunity) 

So basically the way things work is that when an opportunity is set to closed won a project gets created with a lookup relationship back to the opportunity. There is a field on the Project that automatically gets filled with the opportunity name, however the field on the Opportunity that is supposed to get filled with the project name is not being filled when the project is created. 

I have attempted to write some code to uopdate that field after the project is inserted. My logic seems correct however the field (Pse__Primary__Project__C) is not being uopdated with the project name. 

Here is the code.. 
public override void afterInsert(SObject so)
        pse__proj__c newProj = (pse__proj__c)so;

        list <pse__proj__c> projects = [SELECT ID, Name, pse__Opportunity__c FROM pse__proj__c];
        list <opportunity> opportunities = [SELECT ID, Name, pse__Primary_Project__c FROM Opportunity];

        for (Opportunity opps : opportunities){

        if (newProj.Created_by_Opp__c == true)
            opps.pse__Primary_Project__c = newProj.id;


ANy help would be MUCH appreciated!! THANKS IN ADVANCE! 
Chris EagerChris Eager
If this is running after the project is inserted I don't see you actually doing a DML on the Opportunity to update that field, so that is why it is not updating the Opportunity. Also, I think it would be best to put this in the before context on the Opportunity if you can since it will help to prevent recursion.  
Abdul KhatriAbdul Khatri
Hi Kris,

I am not sure why you want to do this circular reference kind of thing. What I mean you are tagging Opportunity with Project it created and then tagging Project with that Opportunity. So you also need to make sure if any of the update happened on either object, other object also need to be taken care.

As my understanding, just having a lookup on opportunity should be good enough. Any I am suggesting based on the short knowledge and my design understanding.

Keeping this in mind here is the trigger that may help you 
trigger OpportunityTrigger on Opportunity (after update){

	List<Opportunity> opportunityList = new List<Opportunity>();
    for(Opportunity opportunity : trigger.new) {
        if (oldMap.get(opportunity.Id).StageName != opportunity.StageName 
            && opportunity.StageName = 'Closed Won'){
    if(opportunityList.isEmpty()) return;
    List<pse__proj__c> projectToInsertList = new List<pse__proj__c>();
    for(Opportunity opp : opportunityList) {
        pse__proj__c projectToInsert = new pse__proj__c (Name = 'project Name', pse__Opportunity__c = opp.Id);