0

I would like to update a field in an object, only in case a value was received, otherwise nothing changes in that field. Is that possible? If yes, how?

I can't use the following code because I want to keep the value in the field if my value is null:

public static void myFunc(String val1, String val2){
    myObj.Field1__c = val1 == null ? null : val1;
    myObj.Field2__c = val2 == null ? null : val2;
}

Here is a sample code of what I have now. I have rewritten it to be dynamic but I am asking if it can be written using static fields.

public static void myFunc(String val1, String val2){
    MyObj__c myObj = new myObj__c(id="0rt1234567890XXXX");
    if(val1 =! null){
        myObj.Field1__c = val1;
    }
    if(val2 =! null){
        myObj.Field2__c = val2;
    }
    Database.update(myObj);
}
6
  • I can't see anywhere in your code where you're checking if anything has changed. Can you pleas edit your question with more detail about your requirement, including what you've tried and detail on why that's not working. We also can't tell from your question the context on how this is called, so it's impossible to provide any advice on how you even detect if something has changed.
    – Nick Cook
    Oct 25 at 23:05
  • Is there a reason you're not using Flow for this basic use case? Oct 26 at 13:57
  • @DavidCheng this is a snippet from a much larger code base. How would you do it in a flow? Oct 26 at 22:37
  • @NickCook updated the question a bit. Let me know if anything else is missing. Regarding the context it can be run from a controller, trigger or anything else. Oct 26 at 22:43
  • 1
    @RandallFlagg The purpose of this site isn't to ask a question, get an answer, then change your question, get another answer, change your question, etc. If you have a business requirement, it may take many questions for you to solve your problem. If the current answer answers your original question, mark it as the correct answer. If it doesn't, elaborate on your original question. Please don't continually change your question because your business requirement isn't met. This site is useless if the questions keep changing.
    – Nick Cook
    Nov 1 at 7:16
2

Based on your updated question, isn't it as simple as:

public static void myFunc(val1, val2){
    myObj.Field1__c = val1 == null ? myObj.Field1__c : val1;
    myObj.Field2__c = val2 == null ? myObj.Field2__c : val2;
}

(Ignoring the fact this isn't a valid apex method as your parameters aren't typed)

1
  • Added types of type string but they can be of any type. Regarding the solution I will check and come back with an answer. Oct 27 at 22:10

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