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?

1 Answer 1

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.

4
  • 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
    Commented Feb 23, 2016 at 3:13
  • Look at my example with the "put" method
    – cropredy
    Commented Feb 23, 2016 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
    Commented Feb 23, 2016 at 4:48
  • 1
    Nope. Get() was added to the answer purely for educational reasons
    – cropredy
    Commented Feb 23, 2016 at 4:50

You must log in to answer this question.

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