0

I have a database field which stores a timestamp. This timestamp is sent to a custom views provider via hook_views_data(). This timestamp field is created as a date field to utilize the date format options from views.

$data['module']['timestamp'] = [
  'title' => t('Timestamp'),
  'help' => t('Timestamp from module'),
  'field' => [
    'id' => 'date',
  ],
  'sort' => [
    'id' => 'date',
  ],
  'filter' => [
    'id' => 'date',
  ],
];

In another views field (but with the same DB field), I would like to get the raw field value and run it through something like:

if (field_value > (time() - 800))

This is a custom module and would prefer not to have any more dependencies. Can this be achieved with hook_views_data() or hook_views_pre_render() or such?

I know there is a contributed module https://www.drupal.org/project/computed_field, but again hoping there is a way in those hooks, or in the view...

The DB table is created with hook_install() and the desired timestamp field output after check would be markup. Happy if it is just sent as markup to the views field.


I've figured how to access the field values with hook_views_pre_render() as such:

function hook_views_pre_render(&$view) {
  $result = $view->result;
  foreach ($result as $key => $row) {
    kpr($result[$key]->field_name);
    if ($result[$key]->timestamp > (time() - 800)) {
      // Can I do anything here?
    }
    else {
      //
    }
  }
}

Unfortunately, that is not the most important piece of the puzzle. And it is not possible to just add $data['module']['key'] to my hook_views_data() as this requires the unique DB field to exist.

In my use case, I'd be happy if I could rewrite the original timestamp field and append this markup to it.

  • If I do $result[$key]->timestamp = $result[$key]->timestamp . $myAddedData; inside my if statement, it does indeed rewrite the value (though doesn't seem the right way), but I'm hoping I can have this as a field in views. – Prestosaurus Mar 6 at 5:51
1

Take a look at this, it shows how you can create custom fields that you can use within views https://www.webomelette.com/creating-custom-views-field-drupal-8

I've followed this recently and seems to work well

  • This has worked well. Having the public function query() empty was the trick so that views ignored there is no DB field. Maybe add that to your answer? Just a note, to kpr() in public function render(ResultRow $values) I had to return kpr($values); to have my kpr() sent to display. This seems like a valid approach to me. – Prestosaurus Mar 6 at 18:41

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.