2

I have 3objects Suivi_TDM__c, Opportunity and Simulation__c. Suivi_TDM__c is related to opportunity via lookup relationship via field Ref_PC__c found on object Suivi_TDM__c. Opportunity is related to Simulation__c via lookup relationship via field Simulation_Offre__c found on object Opportunity.

Now I want to change the lookup field Simulation_Offre__c on opportunity and replace it with the ID_Simulation__c found in suivi_TDM And then, update the new Simulation_Offre__c of suivi_TDM to Active.

Can you check if the code below is good.

List<Suivi_TDM__c> SuiviTDMList = [SELECT Id, ID_Simulation__c FROM Suivi_TDM__c 
                            WHERE Id =: oppIdSet];

if(!SuiviTDMList.isEmpty()){

    for(Suivi_TDM__c suivi_TDM : SuiviTDMList ){  

       //change Simulation_Offre__c of an opportunity with that of suivi_TDM
        suivi_TDM.Ref_PC__r.Simulation_Offre__c = suivi_TDM.ID_Simulation__c;
        Database.update(suivi_TDM,true);
        // change the status of the new Simulation_Offre__c to 'Active'
        suivi_TDM.Ref_PC__r.Simulation_Offre__r.Statut__c = 'Active';
        system.debug('opp new  values'+ suivi_TDM.Ref_PC__r.Simulation_Offre__r.Statut__c );

    }

}
}
1
  • What do you expect if there are two Suivi_TDM__c with one parent opportunity? Which ID_Simulation__c use? Aug 1 '16 at 1:52
1

You can't update object through relashionship. You can create temporary list of object and then update it:

List<Suivi_TDM__c> SuiviTDMList = [SELECT Id, ID_Simulation__c, Ref_PC__c 
    FROM Suivi_TDM__c WHERE Id =: oppIdSet];

map<id,opportunity> oppToUpdateMap = new map<id,opportunity> ();
map<id,simulation__c> simToUpdateMap = new map<id,simulation__c> ();

for (Suivi_TDM__c suivi_TDM :SuiviTDMList) {
    if (Null != suivi_TDM.Ref_PC__c) {
        oppToUpdateMap.put(suivi_TDM.Ref_PC__c, 
            new opportunity( id = suivi_TDM.Ref_PC__c, Simulation_Offre__c = suivi_TDM.ID_Simulation__c));

        if (Null != suivi_TDM.Ref_PC__r.Simulation_Offre__c) {
            simToUpdateMap.put(suivi_TDM.Ref_PC__r.Simulation_Offre__c, 
                new simulation__c( id = suivi_TDM.Ref_PC__r.Simulation_Offre__c, Statut__c = 'Active'));
        }
    }
}

update oppToUpdateMap.values();
update simToUpdateMap.values();

Unfortunately it's not clear what to do if there are two Suivi_TDM__c with one parent opportunity. Map will update latest opportunity only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.