Find your content:

Search form

You are here

Less verbose dynamic +=?

 
Share

I'm trying to do something like this:

sObject.Custom_Field__c += myNumericVar;

But I'm using dynamic SOQL, so I can't hard-code the name of the fields. The following code works, but it's really verbose and hard to read. Is there a cleaner, easier-to-read way to do it?

sObject.put (fieldName, (Decimal) sObject.get(fieldName) + myNumericVar);

Attribution to: Benj

Possible Suggestion/Solution #1

I don't believe so.

Dynamic APEX has it's limitations around how it encapsulates the ORM.


Attribution to: jordan.baucke

Possible Suggestion/Solution #2

I think you must be requiring TYPE cast in above code i.e.

sObject.put (fieldName, ((Decimal)sObject.get(fieldName)) + myNumericVar);

The above code is good if you are using it in loop, as it saves script lines, all the above operation is done in 1 script line only. To make it more developer friendly and readable, one can change it to:

Decimal fldVal = (Decimal)sObject.get(fieldName);         
// Doing addition to save one script line 
sObject.put (fieldName, fldVal + myNumericVar);

Attribution to: Abhinav Gupta
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4036

My Block Status

My Block Content