Score:0

Custom datetime field is treated as a string in Views when filtering

cn flag

I have added a datetime field using BaseFieldDefinition::create() to my custom entity:

BaseFieldDefinition::create('datetime')
         ->setLabel(t('Target date'))
         ->setCardinality(1)
         ->setRequired(TRUE)
         ->setSetting('datetime_type', 'datetime')
         ->setDisplayConfigurable('form', FALSE)
         ->setDisplayOptions('form', [
           'type' => 'datetime_default',
           'weight' => 10,
         ])
         ->setDisplayConfigurable('view', TRUE);

When I create a view of my custom entity and add a filter on this Target date field, I expect to see the date filter options:

  • is equal to
  • is greater than
  • is greater than or equal to

Instead, I see the string filter options:

  • is equal to
  • contains any word
  • contains all words

I assume there's something I need to set to let Views know that my custom datetime should be treated as a datetime and not a string, but I can't it.

How do I get the date filter options instead of the string filter options?

MrD avatar
cn flag
MrD
May be wrong data type. Try with data type datetime_iso8601, created.
MrD avatar
cn flag
MrD
Or on your class extend EntityViewsData, you have to define filter id of field is date.
cn flag
@MrD For the data type, do you mean `::create('datetime')` should be `datetime_iso8601` (tried, invalid) or `created` (stores data as a UNIX timestamp instead of as a Drupal datetime string, which is not what I want because I need to save the timezone info as well).
Score:1
cn flag

Normally Drupal generates the views data for entities automatically, but not yet in this case. So the solution is to extend EntityViewsData and add it yourself until this issue is resolved Base fields miss out on Views data (datetime.module).

You find an example here: Provide a documentation on how to provide views integration for base fields

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.