Scenario -
The object is Calculator object with the following fields -
field1__c and field2__c are where we have to put the data to calculate. (Make it number type field).
Operator is for type of operation. Make this field picklist type with the values as + - * and /.
Result to show the result of the operation. Make this field number type.
Decimal places can be added as per requirement.
Apex Trigger on Calculator object -
trigger letsCalculate on Calculator__c (before Insert, before update) {
for(Calculator__c operation : trigger.new){
if(trigger.isInsert || trigger.isUpdate){
//Division
if(operation.operator__c == '/'){
operation.Result__c = operation.field1__c / operation.field2__c;
system.debug('@@@@@operation.Result__c1is@@@@@'+operation.Result__c);
}
//Multiplication
else if(operation.operator__c == '*'){
operation.Result__c = operation.field1__c * operation.field2__c;
system.debug('@@@@@operation.Result__c2is@@@@@'+operation.Result__c);
}
//Substract
else if(operation.operator__c == '-'){
operation.Result__c = operation.field1__c - operation.field2__c;
system.debug('@@@@@operation.Result__c3is@@@@@'+operation.Result__c);
}
//Addition
else if(operation.operator__c == '+'){
operation.Result__c = operation.field1__c + operation.field2__c;
system.debug('@@@@@operation.Result__c4is@@@@@'+operation.Result__c);
}
}
}
}
Comments
Post a Comment