How can I set a date field to null using Visualforce JavaScript Remoting?

Background

I’ve tried to set a Date (and DateTime) field to null using JavaScript Remoting, but I’ve only succeeded in getting an error message or setting the date to 12/31/1969 6:00 PM.

Code

Here’s the JavaScript Function I’m working with:

function UpdateSObjectField($sender, sObjectId, FieldAPIName, FieldValue)
{
    var sObject = {};
    sObject.Id = sObjectId;

    if($sender.hasClass("type-date") || $sender.hasClass("type-datetime")) {
        if(FieldValue != null && FieldValue != "") { FieldValue = Date.parse(FieldValue); }
        else { FieldValue = null; } // -- TRY TO NULL DATE OR DATETIME --
    }

    sObject[FieldAPIName] = FieldValue;
    console.log(sObject);

    MyController.UpdateSObject(sObject, function(result, event){ 
        if(result && result.toLowerCase().indexOf("success") === 0) { 
            $sender.removeClass("updating").addClass("updated"); EnableInput($sender); } 
        else { $("[id$='Errors']").html(result); }
    });
}

On the line 8 with the comment above (else { FieldValue = 0; }), I’m attempting to set the Date to a blank value (null).

Here’s the Controller Method that is called:

@RemoteAction
global static String UpdateSObject(sObject s) {
    if(s != null) {
        try { update s; }
        catch(Exception exc) { 
            system.debug(exc); 
            return exc.getMessage(); 
        }

        return 'Success!';
    }

    return 'An unexpected error occurred while saving.';
}

Attempts

Here’s what I’ve tried setting FieldValue to:

  • null
    • Results in an error: Visualforce Remoting Exception: Unexpected type for MyController.UpdateSObject(SObject).
    • Data sent: "data":[{"Id":"a1F40000000i2W8EAI"}]. It appears the Date isn’t even sent when it’s set to null.
  • 0
    • Results in the date being set to 12/31/1969 6:00 PM
  • undefined
    • Remote Action succeeds, but it doesn’t actually set the date (confirmed by checking the record in the Salesforce interface).
    • Data sent: "data":[{"Id":"a1F40000000i2W8EAI"}].
  • NaN
    • Results in an error: Visualforce Remoting Exception: Unexpected type for MyController.UpdateSObject(SObject).
    • Data sent: "data":[{"Id":"a1F40000000i2W8EAI"}].
  • "NULL"
    • Results in an error: Visualforce Remoting Exception: Unexpected type for MyController.UpdateSObject(SObject).
    • Data sent: "data":[{"Completed_Date__c":"NULL","Id":"a1F40000000i2W8EAI"}].

Question

How can I set a date field to null when sending an sObject parameter using JavaScript remoting?

Answer

Try passing a list<string> fieldsToNull parameter to the @remoteAction this will allow you to set them all to null in the @remoteActionwith something like s.put('field1',null).

Attribution
Source : Link , Question Author : Matt K , Answer Author : Phil B

Leave a Comment