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
salesforce1#salesforce1# 

addition of two fields using apex trigger?

Hi

 

I am new to development.

 

I have a  custom object  Add, contains three fields num1, num2, result.

 

i want to write a trigger for addition of num1 and num2.

 

when i enter num1 and num2 the result field will be automatically displyed.

 

Regards

 

Best Answer chosen by Admin (Salesforce Developers) 
HariDineshHariDinesh

Hi,

 

You can achieve this using Formula field which exacty suite for your requirment.

 

But if still you want to do this using trigger, find below code.

 

Trigger addtrigger on customobject__C(before insert, before update)
{
  if(Trigger.isBefore) 
  {
    if (Trigger.isInsert || Trigger.isUpdate)
     {
       for(customobject__c cob : trigger.new)
         {
            cob.result = cob.num1+cob.num2; 
           }
       }
    }
}

 Here replace Customobject__c with your custom onject name.

All Answers

Kishan TrambadiyaKishan Trambadiya

First make the class and add the calculation logic then make a trigger on your save or submit button. And then call that class in the trigger by using appropriate parameter.

HariDineshHariDinesh

Hi,

 

You can achieve this using Formula field which exacty suite for your requirment.

 

But if still you want to do this using trigger, find below code.

 

Trigger addtrigger on customobject__C(before insert, before update)
{
  if(Trigger.isBefore) 
  {
    if (Trigger.isInsert || Trigger.isUpdate)
     {
       for(customobject__c cob : trigger.new)
         {
            cob.result = cob.num1+cob.num2; 
           }
       }
    }
}

 Here replace Customobject__c with your custom onject name.

This was selected as the best answer
salesforce1#salesforce1#

Hi Dinesh,

 

Thankyou for your valuable infomation.

 

Regards