Issues with the title for a custom entity

I have a custom content entity in which I have defined all the fields in the annotation (and it shouldn’t need to be altered through the UI in any way that I can think of).

In the annotation I have the standard keys defined:

 *   entity_keys = {
 *     "id" = "MY_ID_FIELD",
 *     "label" = "MY_LABEL_FIELD",
 *     "uuid" = "uuid"
 *   },

MY_LABEL_FIELD is a field used for the “title” but I also need it presented in the content. In the entity class, I have it defined as I would need it displayed in the content:

  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => 3,
   ))

Without any theme overrides, in the page content, MY_LABEL_FIELD renders as expected (and as defined in the annotation) with some basic field wrappers.

<div class="field ...">
  <div class="field--label ..."> [the field's label...] </div>
  <div class="field--item ..."> [the field's value...] </div>
</div>

But…

It renders the same way in the title block, with the field wrappers, in addition it is wrapped in <h1> tags by page-title.html.twig

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21PageTitle.php/8.2.x

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21page-title.html.twig/8.2.x

And…

It renders as [the field's label...] [the field's value...] inside the HTML <head><title> tags.

https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_html/8.2.x

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21html.html.twig/8.2.x

And…

I need to use the title value in my page template (page.html.twig). There is a title value available in $variables['page']['#title'] in
https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_page/8.2.x but this title value is the same as HTML above, it is [the field's label...] [the field's value...]

In all 3 places, I simply want [the field's value...] – without the label, without the wrappers. The only place I do want the label and wrappers is inside the content.

One solution is to implement a couple of HOOK_preprocess functions. Another is to implement a title callback.

This issue has been discussed here a number of times:

I tried implementing a title callback…

In my implementation of EntityRouteProviderInterface

$route = (new Route('/MY_PATH/{MY_ENTITY}'))
  ->addDefaults([
    '_entity_view' => 'MY_ENTITY',
    '_title_callback' => 'DrupalMY_MODULEControllerMY_CONTROLLER::titleCallback',
  ])
  ->setRequirement('_entity_access', 'MY_ENTITY.view');
$route_collection->add('entity.MY_ENTITY.canonical', $route);

And in a controller

public function titleCallback() {
  $entity = Drupal::routeMatch()->getParameter('MY_ENTITY');
  return $entity ? $entity->label() : 'SOME VALUE FOR FALSE';
}

And in my entity class, I implemented the label() method (override the parent class)

/**
  * {@inheritdoc}
  */
public function label() {
  return $this->get('MY_LABEL_FIELD')->value;
}

But I couldn’t get this titleCallback() to ever get called. I started poking around a bit… I found that if I removed the “label” definition from the entity annotation, then the titleCallback() worked fine.

So this…

*   entity_keys = {
*     "id" = "MY_ID_FIELD",
*     "label" = "MY_LABEL_FIELD",
*     "uuid" = "uuid"
*   },

became…

*   entity_keys = {
*     "id" = "MY_ID_FIELD",
*     "uuid" = "uuid"
*   },

Then everything seemed OK. MY_LABEL_FIELD was rendered with wrappers in the body and just the value was used in the page title block, the HLML <head><title> and was a simple string available in $variables['page']['#title'].

I moved on to other things.

I continued working on my module. This entity will hold nearly a million records and I started working on methods for loading all that data. After getting to a nice place with several hundred thousand records, I was doing some tests and getting some weird results, in particular entity reference autocomplete widgets pointing to this entity would just display a spinner (with only a few records it seemed fine). At first I thought it was a database issue with so many records, but eventually I discovered that if I put the “label” definition back into my annotation, all was fine again – except of course the title was being rendered with label and field wrappers.

I am guessing that the “label” definition is pretty important. I know it’s not required, as my module would work without it. Also, a basic example https://www.drupal.org/docs/8/api/entity-api/create-a-custom-content-entity doesn’t show it defined.

So I am not sure where to turn next:

Thoughts?

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Issues with the title for a custom entity

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.