+ Start a Discussion
megsumamegsuma 

Apex Triggers, Picklists and Updating

Hi all,

 

 I have a bit of a problem that probably shouldn't be a problem...I'm trying to do something that should be alot easier than it has been so far:

 

 I have a field being populated by a formula and the field is either a 1 or a 0 depending on the outcome of the formula. All I want is for a picklist to change value when the field's value changes.

 

Here is my trigger:

 

trigger CompanyGoalUpdate on Company_Goal__c (after insert, after update) {
	Company_Goal__c cmp = [SELECT Upcoming_Goal__c, Use_on_Company__c, LastModifiedDate FROM Company_Goal__c WHERE Id =: trigger.new[0].Id];
	
	if(cmp.Upcoming_Goal__c == 1)
		cmp.Use_on_Company__c = 'Use';
	else
		cmp.Use_on_Company__c = 'Do Not Use';
	
	DateTime RightNow = System.now();
	
	if(cmp.LastModifiedDate < RightNow.addMinutes(-30))
		update cmp;
}

 

Any thoughts?

 

Best Answer chosen by Admin (Salesforce Developers) 
jhenningjhenning

megsuma:

 

I recommend using a BEFORE trigger. Try this code:

 

 

trigger CompanyGoalUpdate on Company_Goal__c (before insert, before update) {
	for(Company_Goal__c cmp:Trigger.New){
		if(cmp.Upcoming_Goal__c == 1)
			cmp.Use_on_Company__c = 'Use';
		else
			cmp.Use_on_Company__c = 'Do Not Use';
	}
}

 

 

All Answers

jhenningjhenning

megsuma:

 

I recommend using a BEFORE trigger. Try this code:

 

 

trigger CompanyGoalUpdate on Company_Goal__c (before insert, before update) {
	for(Company_Goal__c cmp:Trigger.New){
		if(cmp.Upcoming_Goal__c == 1)
			cmp.Use_on_Company__c = 'Use';
		else
			cmp.Use_on_Company__c = 'Do Not Use';
	}
}

 

 

This was selected as the best answer
megsumamegsuma

Perfect! Thank you very much, your advice was just what I was looking for.

jhenningjhenning

great! Just click the "accept as a solution" button to share this with others. Thanks!