2

On my article content type, I enabled "Display author and date information" but am unable to change the date format.

I'm using Druapl 8.0.0-beta14 with a sub-theme based on Classy. The field's value is already computed by the time the twig template and hook_preprocess_field get to it but was able to chase down the setting of the date format to the defaultSettings method in TimestampFormatter.php using a debugger.

    public static function defaultSettings() {
      return array(
        'date_format' => 'medium',
        'custom_date_format' => '',
        'timezone' => '',
      ) + parent::defaultSettings();
    }

So far, I haven't found a place in the admin UI or yaml files (or a hook, which I know I probably shouldn't be doing too much of in D8) where the date format can be changed. Interestingly enough, this "field" on the node seems to be some sort of pseudo-field, because the value is actually the timestamp on the revision_timestamp field in the node_revision table.

That said, how can I change the date format for this "field"?

  • I would suggest you open a core issue and add ->setDisplayConfigurable('view', TRUE); to the created field definition in Node::baseFieldDefinitions(). With that, it will show up in the manage display screen and becomes easy to configure. Not sure why this isn't done at the moment. – Berdir Sep 10 '15 at 10:55
1

One way to do this is using a preprocess hook in your .theme file. There you can do pretty much anything with that variable.

Here an example:

function [theme_name]_preprocess_node(&$variables) {
  if ($variables['display_submitted']) {

    // Getting the node creation timestamp from the node object.
    $date = $variables['node']->getCreatedTime();

    // Here you can use drupal's format_date() function, or some custom php date formatting.
    $variables['date'] = format_date($date, 'medium');
  }
}

In an earlier beta, before being able to alter the 'date' variable, I had to first pass the string through the create() method of the SafeString class like this:

$variables['date'] = \Drupal\Core\Render\SafeString::create('your dangerous new date string')

This might not be necessary anymore, concidering all the recent fuss around the safe string functions. Edit: I still need to do that in beta15.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.