Missing Titles on Drupal 8 ECK Content Listings
UPDATE: I discovered the solution below was only working when the Title base field was enabled for the entity type. If you enable the title field on the entity type it works, but then the title is required to save a new record. I will look for an alternative solution to avoid using the Title field altogether. Also, I’ll look into https://www.drupal.org/project/eck/issues/2785297.
I’ve recently run into an issue with an ECK-created custom entity type. There was no reason for me to use the “Title” field on this particular entity type. Unfortunately, when you don’t have a title field several of the built-in entity listings and displays seem broken. Here’s what the Content List screen looks like, for example:
And here’s what a Views Bulk Operations confirmation screen looks like:
You can see these screens aren’t ideal. We don’t have a way to view the entity in the content list, and we don’t know these entities are in either case.
I thought about enabling the title field and setting it to be a combination of three of the other fields on the entity. I considered using Automatic Entity Label to make light work of this. However, after doing some testing I realized that storing a title is a complete waste of database resources. With a few hundred thousand records theĀ registration_field_data table quickly got fairly large. And, the title isn’t useful to me outside of a few screens like the one shown above, so why store it?
I quickly thought of a solution. Using hook_entity_load() it’s possible to alter entity values (temporarily). It worked well to solve this issue.
Here’s the resulting code and output:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/** * Implements hook_entity_load(). */ function mymodule_entity_load(array $entities, $entity_type_id) { // Dynamically set the label/title for various listings, views, etc. if ($entity_type_id === 'registration') { foreach ($entities as $entity) { $entity->title = $entity->field_prereg_phone_num->value . ' : ' . $entity->field_prereg_dob->value . ' : Phase ' . $entity->field_prereg_phase->value; } } } |
Another benefit of this solution is that I can adjust the logic on the fly and hundreds of thousands of records instantly reflect the change.