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
sravan teja 2sravan teja 2 

Hi , In a trigger i need to update a custom field based on other custom filed

Senario: when a value is inserted on AMOUNT custom field, COUNTER custom filed should be automatically get incresed.  i'm new to salesforce and please guide me.

Object :  Account
Custom fields : amount,counter
 Thanks in advance
Best Answer chosen by sravan teja 2
Deepak Maheshwari 7Deepak Maheshwari 7

Below is the trigger for that:

trigger counterTrigger on Account(before insert, before update)
{
	if(trigger.isInsert)
	{
		for(Account acc : Trigger.New)
		{
			if(acc.Amount__c!=null)
			{
				acc.Counter__c = 1;
			}
			else
			{
				acc.Counter__c = 0;
			}
		}
	}
	
	if(trigger.isUpdate)
	{
		for(Account acc : Trigger.New)
		{
			if(Trigger.oldMap.get(acc.Id).Amount__c != acc.Amount__c)
			{
				acc.Counter__c = acc.Counter__c + 1;
			}
		}
	}
	
}
 

 

All Answers

Deepak Maheshwari 7Deepak Maheshwari 7

Hi Sravan,

 

Please confirm In counter field, the value will be shown as 1,2,3 and so on or the value of Amount will be there in counter field

sravan teja 2sravan teja 2
value will be shown as 1,2,3 and so on
Deepak Maheshwari 7Deepak Maheshwari 7
Please confirm the counter value will be increased when Amount is updated
sravan teja 2sravan teja 2
yes deepak when ever amount is updated the counter should be incresed.
Deepak Maheshwari 7Deepak Maheshwari 7

Below is the trigger for that:

trigger counterTrigger on Account(before insert, before update)
{
	if(trigger.isInsert)
	{
		for(Account acc : Trigger.New)
		{
			if(acc.Amount__c!=null)
			{
				acc.Counter__c = 1;
			}
			else
			{
				acc.Counter__c = 0;
			}
		}
	}
	
	if(trigger.isUpdate)
	{
		for(Account acc : Trigger.New)
		{
			if(Trigger.oldMap.get(acc.Id).Amount__c != acc.Amount__c)
			{
				acc.Counter__c = acc.Counter__c + 1;
			}
		}
	}
	
}
 

 

This was selected as the best answer
sravan teja 2sravan teja 2
thanks deepak and can you please explain code in 2nd IF.
 
Deepak Maheshwari 7Deepak Maheshwari 7

Hi Sravan,

Trigger.oldMap.get(acc.Id).Amount__c giving the previous value of Amount__c and acc.Amount__c giving the current value.

So I am doing comparison.

 

Please mark it as the best answer if this works for you.

 

sravan teja 2sravan teja 2
when previous amount is not equal to present amount counter need to be incresed got the second IF too..
Thanks you so much deepak..