How can I set a date field to null using Visualforce JavaScript Remoting?
Try passing a list<string> fieldsToNull
parameter to the @remoteAction
this will allow you to set them all to null in the @remoteAction
with something like s.put('field1',null)
.
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.';
}
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 !