1

I am trying to instantiate a sObject in my controller. The information that I am populating about it comes from my AJAX. Including the name of the field that I want to populate + its value.

So with that said the method that the AJAX is calling looks like this:

public static String updateInputField(Id objectkId, String objectFieldName, Integer objectFieldValue) {
        String errorMsg = 'testerror';
        Stock__c objectToUpdate = new Stock__c(Id=objecttId, objectFieldName=objectFieldValue);

return errorMsg;
}

However I get this error when trying to compile the code: Invalid field stockFieldName for SObject Stock__c

Any ideas why this is not working?

3

The solution to this is to use sObject method put.

public static String updateInputField(Id objectkId, String objectFieldName, Integer objectFieldValue) {
    String errorMsg = 'testerror';
    Stock__c objectToUpdate = new Stock__c(Id=objecttId);
    objectToUpdate.put(objectFieldname,objectFieldValue);  // dynamic DML

    return errorMsg;
 }

There is a corresponding sObject.get()method for getting fieldvalues by fieldname.

  • Thanks for the reply. I looked up the get(FieldName) method on salesforce and read through the examples but don't quite get it. How is it going to help me? – Arthlete Feb 23 '16 at 3:13
  • Look at my example with the "put" method – cropredy Feb 23 '16 at 4:46
  • Okay I see how to populate the objectToUpdate with the put. But do I need the get() and where? I am already passing the objectFieldName through ajax right? – Arthlete Feb 23 '16 at 4:48
  • 1
    Nope. Get() was added to the answer purely for educational reasons – cropredy Feb 23 '16 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.