[SalesForce] Inserting Date Field with JS Remote Objects

Using JS Remote Objects, I'm trying to INSERT a record that has a date field as a required field (an Opportunity). I am getting this value from a user input, which I'm using JQuery.validate to validate that it is in date format. The string can look like either:

12/12/2016 or 2016/12/12

This was rejected as an invalid type. Looking at how to format strings in the SF API docs:

To insert record into Date or Date Time field using Data Loader:

1) "Date" type field accept either one of below format:

yyyy-mm-dd

yyyy-mm-dd hh:mm:ss

yyyy-mm-ddThh:mm:ssZ

yyyy-mm-ddThh:mm:ss.sssZ

I tried inputting the date as 2016-12-12, still didn't work.

How can I, in JS, supply a value that the API will accept?

BTW, I'm just using the basic create JS Remote Object method:

OpportuntyObjectModel.create({
   name:      'oppName',
   CloseDate: '2016-12-12',
   StageName: 'Engagement'
  } 
 )

Best Answer

You can pass javascript date object to the apex date field..

initialise the js date from the date string and pass the js date variable

var dt = new Date('2015-12-12');
var oppDetails = { Name: 'Test Opp', CloseDate: dt, StageName:'New' };

here's the full code I tested in my dev org which worked..

<apex:page >
  <script type="text/javascript">
     function createOpp(){    
        var dt = new Date('2015-12-12');
        var oppDetails = { Name: 'Test Opp', CloseDate: dt, StageName:'New' };
        var opp = new RemoteObjectModel.Opportunity();
        opp.create(oppDetails, function(err) {
            if(err) { 
                console.log(err);
                alert(err.message);
            }
            else {
                console.log(opp.get('Id')); 
                alert('success');
            }
        });
     }
  </script>
  <apex:remoteObjects jsNamespace="RemoteObjectModel">
    <apex:remoteObjectModel name="Opportunity" fields="Id,Name,CloseDate,StageName">
    </apex:remoteObjectModel>
  </apex:remoteObjects>
  <input type="button" onClick="createOpp()" value="Create Opp" />
</apex:page>
Related Topic