18

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?

  • 2
    A shining example of a well structured and placed question! +1! – Andrew Fawcett Oct 24 '13 at 17:33
  • 1
    Hm, what if you passed another parameter to the remoteAction list<string> for all the applicable date fields. Then it could null those fields in the remoteAction. – Phil B Oct 24 '13 at 18:36
  • 1
    Interesting idea.. Do you mean defining the Remote Action method like this: UpdateSObject(sObject s, List<String> FieldsToNull)? – Matt K Oct 24 '13 at 18:53
  • @MatthewKeefe awesome! glad to help – Phil B Oct 24 '13 at 19:20
11

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).

  • 2
    This is how the SOAP API handles nulls, seems to be a well tested pattern. – ca_peterson Oct 24 '13 at 20:55
5

For reference, here's what I ended up with:

JavaScript

function UpdateSObjectField($sender, sObjectId, FieldAPIName, FieldValue)
{
    MarkAsUpdating($sender);

    var sObject = {};
    var FieldsToNull = [];
    sObject.Id = sObjectId;

    if(FieldValue == null || FieldValue == "" || FieldValue == undefined) {
        FieldsToNull.push(FieldAPIName);
    }
    else {
        if($sender.hasClass("type-date") || $sender.hasClass("type-datetime")) {
            FieldValue = Date.parse(FieldValue); }

        sObject[FieldAPIName] = FieldValue;
    }

    MyController.UpdateSObject(sObject, FieldsToNull, function(result, event){ 
        if(result && result.toLowerCase().indexOf("success") === 0) { 
            MarkAsUpdated($sender); } 
        else { 
            MarkAsError($sender); j$("[id$='Errors']").html(result); }

        EnableInput($sender);
    });
}

Controller Method

@RemoteAction
global static String UpdateSObject(sObject s, List<String> FieldsToNull)
{
    if(s != null) 
    {
        if(FieldsToNull != null && !FieldsToNull.isEmpty()) {
            for(String FieldApiName : FieldsToNull) { 
                s.put(FieldApiName, null); } }

        try { update s; }
        catch(Exception exc) { return exc.getMessage(); }

        return 'Success!';
    }

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

If you're going to be doing more than a few of these, be sure to take a look at the remotetk on github. It's got remoting queries, update, create, etc.

AND there's built in logic for dealing with the dates and other casting issues, error handling, etc.

Lots of opportunities to get away with NO CONTROLLER !

0

You can nullify a date field, by setting it's value to 0. However, like you mentioned it doesn't work with datetime fields.

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.