function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jayati1.392452190341368E12jayati1.392452190341368E12 

Code is not updating the custom object. Please help.

Hi,

I am including the following code to the trigger and it does not update the custom object. Please help me on this :(

if((trigger.isAfter && trigger.isInsert) || (trigger.isAfter && trigger.isUpdate))
    {
    list<Opportunity> opp = new list<Opportunity>();
    opp = [select id,Brand_Name1__c from opportunity where id  =: Trigger.new[0].OpportunityID__c];
       if(opp[0].Brand_Name1__r.Name.contains('sam') )
       {
            Trigger.New[0].Comments__c = '25';
            Trigger.New[0].Agency_Commission__c = 25;
       }
    }
Adnubis LLCAdnubis LLC
You are using an After trigger which can not be used to simply assign values to the objects firing the trigger. Change your trigger to a before trigger and this should work. That being said, I am not sure of the context but I see some other issues with your trigger. 

1. You are only updating the first opp of potentially 200 per trigger. 
2. You were trying to access the field Brand_Name1__r.Name without queryiing for it. In your opportunity Query you need to include that field specifically. 
3. As I said before you need to use a before trigger if you want to adjust the values of the inserting/updating records

I wrote the trigger a bit differently for you but without knowing your full context I can't be sure it will work the way you want it to. Please see below.

if((trigger.isBefore && trigger.isInsert) || (trigger.isBefore && trigger.isUpdate)){
set<Id> oppIds = new set<Id>();
for(ObjectName object : trigger.new){
  oppIds.add(object.OpportunityID__c);
}
    map<Id,Opportunity> oppMap = new map<Id,Opportunity>([select id,Brand_Name1__c,Brand_Name1__r.Name from opportunity where id  in :oppIds]);
    for(ObjectName object : trigger.new){
  Opportunity relatedOpp = oppMap.get(object.OpportunityID__c);
  if(relatedOpp.Brand_Name1__r.Name.contains('sam') ){
            object.Comments__c = '25';
            object.Agency_Commission__c = 25;
       }

}

This trigger will now update your values and work for all records that fired the trigger.