Is it possible to set the end date relative to the selected start date in a D8 date range field? I have a date range field that I use to specify an accounting period. The end date should now be put to one year minus one day from the selected start date. For example, the start date 2016-07-01 will give the end date 2017-06-30. How is this possible?
The current widgets in core for the Datetime Range module do not allow this.
You would need to create a custom widget for this. Off the top of my head, I would create one that extends
DateRangeWidgetBase() and mostly mirrors what
DateRangeDefaultWidget() does, except to collect a relative period in a plain text field for the end date. Then, add a
massageFormValues() function to turn the relative date into an absolute one, and then call
parent::massageFormValues(). You may also be able to do this with a
#process callback on the end date element, but I forget which of the two runs first during form processing.
And as a side note, if you get this working, it would be a great addition to the drupal.org/project/datetime_extras module if you post it as a patch.– mpdonadio ♦Jun 12, 2018 at 0:16
And just altering the node form and adding a custom submit to populate the end field? Couldn't that work as well?– leymannxJun 12, 2018 at 0:53
1@leymannx The timestamp/datetime/daterange default widgets use HTML5 elements, which complicate matters. You also need to convert to a proper date before the massageFormValues (which tweaks the values for date-only and sets the storage time zone) and validation (which is at both the element and widget level) runs. This is messy in a node form alter. Doing this as a new field Widget is the easiest option.– mpdonadio ♦Jun 12, 2018 at 0:54