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
Harvey2016Harvey2016 

Logic doesn't work for some reason.

 I was working on a practice scenario when if Hello field on Opportunity is empty before inserting and updating. the field should filled with world. Below is my code. Can someone tell me where I did wrong 

 
public class OppHelloWorld
 {
 public void addHelloWorld(List<opportunity> opps)
 {
 for (Opportunity o:opps)
 {
 if (o.Hello__c != 'World')
 {
 o.Hello__c = 'World';
 }
 }
 }
 }
Below is the Trigger Code:
 
trigger HelloWorld on Opportunity (Before Insert, Before update) {

List <Opportunity> Opps = new List<Opportunity>();
OppHelloWorld OHW = New OppHelloWorld();
OHW.addHelloWorld(Opps);
}


 
Best Answer chosen by Harvey2016
Ch. Szandor KnappCh. Szandor Knapp
trigger HelloWorld on Opportunity (Before Insert, Before update) {

OppHelloWorld OHW = New OppHelloWorld();
OHW.addHelloWorld(Trigger.new);
}

In your example, you create a new instance of a List of Opportunities and feed it into your helper. Since it is empty, your code doesn't really run on any Opp. 

Trigger.new is a a special kind of Trigger Context Variable containing the list of newly inserted or updated lists. Please refer to https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htm

Also, there's a Trailhead on Trigger in Apex: https://trailhead.salesforce.com/en/modules/apex_triggers

All Answers

Ch. Szandor KnappCh. Szandor Knapp
trigger HelloWorld on Opportunity (Before Insert, Before update) {

OppHelloWorld OHW = New OppHelloWorld();
OHW.addHelloWorld(Trigger.new);
}

In your example, you create a new instance of a List of Opportunities and feed it into your helper. Since it is empty, your code doesn't really run on any Opp. 

Trigger.new is a a special kind of Trigger Context Variable containing the list of newly inserted or updated lists. Please refer to https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htm

Also, there's a Trailhead on Trigger in Apex: https://trailhead.salesforce.com/en/modules/apex_triggers

This was selected as the best answer
Harvey2016Harvey2016
Make sense. Thanks Pal.