0

I am trying to set a custom field of an custom object from apex

object.put('field__c','value');
object.field__c = 'value';

Both of these lines do not set the value. However is I log the result of put it does show the old value of 'field__c'. Any suggestions as to where to look for a solution ?

5
  • If this is a custom field it should have the suffix __c
    – Mark Keats
    Apr 15, 2015 at 9:44
  • Thanks for the comment. In the actual code the field has the __c suffix this was just to illustrate the code. ( I will add it here as well) Apr 15, 2015 at 9:46
  • 1
    Could you show the full code with System.debug please ? Maybe something else is wrong
    – MMT
    Apr 15, 2015 at 9:53
  • Where is this code? A before trigger, after trigger, controller? Are you doing an insert/update after it?
    – BarCotter
    Apr 15, 2015 at 9:54
  • The code is in a controller. Adding an update call solved the problem. Apr 15, 2015 at 10:22

2 Answers 2

1

The put() method on SObject will set the new value, but return the previous value of the field.

Sets the value for the specified field and returns the previous value for the field. Apex Documentation

So if you put a log on the result of put() it would return the previous value.

MyObject__c.MyField__c = 'Hello';
System.debug(MyObject__c.put('MyField__c', 'World'); // Returns 'Hello'
System.debug(MyObject__c.MyField__c); // Returns 'World'
1
  • This does work but after that when I go to the page of the object the field is still on the old value Apr 15, 2015 at 9:59
0

After some research I have found out what the problem was.
The object variable was created from a query. After setting the field calling

update object;

saves the value to the field

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .