BUTFF program overview

Drupal 8 REST-api: Formatting your date-range values (in PATCH)

However simple it seems, It took me way too long to figure out how to properly format the json value for a daterange field in a PATCH request.
The resulting errors from doing it wrong are not very verbose.

The js Date-class has the .toISOString() method but passing that to Drupal it does not validate and gives a 500 error.

1
NetworkError 500 Internal Server Error
Once I found that the problem was in the datefield, It still took some tweaking to get it right.
Passing the wrong format gives this mystic, althought somewhat more usefull 422 error:
1
NetworkError 422 Unprocessable Entity
At least when looking at the response we can know the cause:

1
2
3
{"message":"Unprocessable Entity: validation failed.\nfield_start_and_end: <em class=\"placeholder\"
>Start and End<\/em>: this field cannot hold more than 1 values.\nfield_start_and_end.0.end_value:
This value should not be null.\nfield_start_and_end.1.value: This value should not be null.\n"}

So anyway, to get my daterange field ('field_start_and_end') populated and valid this is the code that worked for me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var start = [somedateobject]; // i.e. new Date();
var end = [otherdateobject];
var start_end_values = [ { "value" : toDrupalISO(start) , "end_value" : toDrupalISO(end) } ];
 
function toDrupalISO(d){ //this returns the correct format: i.e. 2017-09-06T18:34:00
 
  //helper function to add leading 0 when val is below 10.
  function zero(num){ return ("0" + num).slice(-2) };
 
  //return the full String
  var dateStr = d.getFullYear() + "-" + zero(d.getMonth()+1) + "-" + zero(d.getDate()) + "T" + zero(d.getHours()) + ":" +. zero(d.getMinutes()) + ":00";
  return dateStr;
 
}

So to summarize. It looks like this:

1
2
3
4
5
6
7
8
var fields = {
  "field_start_and_end" : [
    {
      "value" : "2017-09-06T18:34:00",
      "end_value" : "2017-09-06T20:34:00",
    }
  ],
}