0

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' => '\Drupal\MY_MODULE\Controller\MY_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?

1 Answer 1

0

OK I found the solution to my problem (why it took me so long is another issue - but of course, it was found in a controller).

Posting as an answer instead of an update (as the question is so long, I think it might get lost).

The "offending" code is in EntityViewController (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Controller%21EntityViewController.php/8.2.x).

public function buildTitle(array $page) {
  $entity_type = $page['#entity_type'];
  $entity = $page['#' . $entity_type];
  // If the entity's label is rendered using a field formatter, set the
  // rendered title field formatter as the page title instead of the default
  // plain text title. This allows attributes set on the field to propagate
  // correctly (e.g. RDFa, in-place editing).
  if ($entity instanceof FieldableEntityInterface) {
    $label_field = $entity->getEntityType()->getKey('label');
    if (isset($page[$label_field])) {
      $page['#title'] = $this->renderer->render($page[$label_field]);   <---------HERE
    }
  }
  return $page;
}

I imagine that is fine in most use cases, but not in mine. And plus 1 for Drupal devs not losing the documentation on this. https://www.drupal.org/node/2498849

So I need my own controller (node module has an example as well, see NodeViewController) in which I can implement the function buildTitle(array $page) and leave the title as the default plain text.

In my implementation of EntityRouteProviderInterface, the canonical route is defined:

$route = (new Route('/path/{my_entity}'))
  ->addDefaults([
    '_controller' => '\Drupal\my_enitity\Controller\MyEntityViewController::view',
    '_title_callback' => '\Drupal\my_entity\Controller\MyEntityViewController::title',
  ])
  ->setRequirement('my_entity', '\d+')
  ->setRequirement('_entity_access', 'my_entity.view');
$route_collection->add('entity.my_entity.canonical', $route);

And this is the content of the file with my controller

namespace Drupal\my_module\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Controller\EntityViewController;

/**
 * Defines a controller to render a single my_entity.
 */
class MyEntityViewController extends EntityViewController {

  /**
   * {@inheritdoc}
   */
  public function buildTitle(array $page) {
    // the parent implementation of this method overrides the default plain text title
    // and sets the title as the fully rendered field (as defined by the field template)
    // we want the default plain text, so we just need to return $page as is.
    return $page;
  }

  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $my_entity, $view_mode = 'full', $langcode = NULL) {
    // this needs to be implemented to change the name of the first paramater to our entity name 
    // but we can return the parent's output
    $build = parent::view($my_entity, $view_mode, $langcode);  
    return $build;
  }

 /**
   * The _title_callback for the page that renders a single my_entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $my_entity
   *   The current my_entity.
   *
   * @return string
   *   The page title.
   */
  public function title(EntityInterface $my_entity) {
    // this copies how node implements its title callback.
    return $this->entityManager->getTranslationFromContext($my_entity)->label();
  }  

}
2
  • Yep, the default 'title' of an entity is the label. In your twig file, you can also print {{ label }}. This also works in node templates, as does {{ node.label }}
    – Kevin
    Jun 17, 2017 at 14:52
  • It's actually the rendered label $page['#title'] = $this->renderer->render($page[$label_field]) and I didn't want that, I just wanted the plain text label. I am using the same field in the content body which I do want with the rendering, so it's sort of a special case.
    – rjl
    Jun 17, 2017 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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