Default Value Of Today’s Date On Timestamp In Drupal 8

PROBLEM
One of the stupidest things in Drupal 8 is the Timestamp field. If only I knew what I know now. All well, we’re stuck with it.

Its default value cannot be set to today’s date. When saving the field as null in the field settings, going to a new node, the default value is when you saved the field. Ours was two years ago since that’s when I started working on this site. So default dates for our Timestamp field were like “09/04/2018 02:43:02 PM”.

Not good. How do you make the default date the date of the new node (like today’s date and time)?

SOLUTION
I first installed a patch on a ticket on drupal.org (patch #14) which allowed the field setting to be null. Since the Timestamp field sucks, it doesn’t give you the option of today’s date like the Date field does. So, I had to add to our custom module the way to do that.

// see if we need to worry about the publication date
if (isset($form["field_publication_date"])) {
	// if it's a new form
	if ($form_id == "node_" . $your_content_type . "_form") {
		// set the default value to a new date time (which by default is "now")
		$form["field_publication_date"]["widget"][0]["value"]["#default_value"] = new DrupalDateTime();
	}

	// end if we have a field_publication_date
}

This code can go inside a preprocess like hook_form_alter. You also don’t need to do it the way that I did with the $form_id. There might be a new node hook somewhere that you could add this to maybe. Obviously, the field_publication_date should be changed to whatever your Timestamp field machine name is called.

Leave a Reply

Your email address will not be published. Required fields are marked *