Allow node/entity to display title/label field as normal

Created on 28 May 2020, over 4 years ago
Updated 20 September 2023, about 1 year ago

After this module is enabled on all of my nodes in standard view (URL /node/xxx) the title is not displayed.

I can move the title field in Manage display section of all content types to another position, but when I view the node (/node/xxx) the title is not show in none of the positions. Page title is show but I do not need the page title on my nodes and can disable the page title. But the node title is needed on different positions.

Same behavior with Bartik theme (core). How can we repair this?

✨ Feature request
Status

Needs work

Version

2.0

Component

Code

Created by

🇦🇹Austria drupalfan2

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇦🇹Austria drupalfan2

    The Manage display still does not work. No title is show on node page (node/xxx).

    The patch #24 is not working!

    Actually the submodule manage_display_fix_title does only contain 1 file:
    manage_display_fix_title.info.yml

    A file manage_display_fix_title.module is missing!

    The Manage display module is unusable! I had to remove it. It does not work.

  • 🇳🇱Netherlands Martijn de Wit 🇳🇱 The Netherlands

    I would opt in for option 3 from #4

    Funny fact: If you enable Field Layout (core) module, option 3 is working out of the box.

  • 🇳🇱Netherlands Martijn de Wit 🇳🇱 The Netherlands
  • 🇳🇱Netherlands firfin

    @Martijn de Wit comment 29 Enabling Field Layout from core does not fix this for me. Any other settings needed that you know of?

    @Moser comment #24 patch does not apply to 3.0 version for me, any chance to get a patch for this version?

    For now I just made my own module with this code in it, thanks.

  • 🇺🇸United States thejimbirch Cape Cod, Massachusetts

    I have a pretty vanilla install I am working on. After enabling the 3.0 branch of this module, and enabling field_layout, the title field appears on my node.

  • First commit to issue fork.
  • 🇺🇸United States sim_1

    I don't know how to change the target to the 3.x branch, but I update the MR to use the solution from #23 with some minor tweaks. I don't think the solution is perfect, but I'm also just still trying to wrap my head around it so it's such a relief that it at least gets the title on the page. My main issue is that I don't understand why the "label" render array value goes away when this module is enabled. It breaks assumptions that are made in core node templates, as well as contrib themes. But again, I'm just relieved something works!!

  • 🇺🇸United States sim_1
  • 🇫🇷France Guillaume Aveline

    I had the same issue.
    After taking a look at `EntityViewController::buildTitle()`, I saw at the end:

            // Prevent output of the label field in the main content.
            $page[$label_field]['#access'] = FALSE;
    

    So I made this hook

    function MY_MODULE_preprocess_node(&$variables) {
      $variables['content']['title']['#access'] = true;
    }
    

    And it seams to do the job, at least for me.
    I Hope I'm not breaking something, :)

  • 🇳🇱Netherlands gbr

    #29, enable Field Layout (core) module.
    Did work for me.

    Thanks!

  • I got it to work using hook_node_view as outlined in #23.
    The trick is simply to move 'title' into something named differently, like "_title"

  • Status changed to Needs review 2 months ago
  • 🇨🇭Switzerland redzeuf Geneva

    Here is a patch implementing the solution suggested by "la vague illuminee" in comment #36.
    I did a bench of test with taxonomy, media and node entities and it works.

    It allows to display the "title" field where you defined it from within the "manage display" admin page.

  • 🇨🇭Switzerland redzeuf Geneva

    Here is a patch implementing the solution suggested by "la vague illuminee" in comment #36.
    I did a bench of test with taxonomy, media and node entities and it works.

    It allows to display the "title" field where you defined it from within the "manage display" admin page.

  • 🇮🇹Italy senzaesclusiva

    I can confirm the good result of patch #39.
    Previously, in order to show the title set by Manage Display, I had to enable the Field Layout (Experimental) and Layout Discovery modules, but I did not like this solution as Field Layout is strongly discouraged.
    I hope that this module, or at least the part about managing the title order display, can be implemented in Drupal, because the title does not always have to be the first part of a piece of content.

  • 🇭🇺Hungary danyg Budapest

    Also I can confirm, I was able to render the title by adding the {{ content.title }} by using the patch #39.
    Of course, the Title field was enabled on Manage Display.

  • 🇭🇺Hungary danyg Budapest
  • 🇳🇱Netherlands Martijn de Wit 🇳🇱 The Netherlands

    How about using: ✨ Add a Title Formatter Active

  • 🇫🇷France Julien Tekrane

    The patch #39 allows to render content.title but breaks the previously existing label variable.

    Source :
    https://git.drupalcode.org/project/drupal/-/blob/10.3.x/core/modules/nod...

    if (isset($variables['elements']['title']) && (!$skip_custom_preprocessing || !$node->getFieldDefinition('title')->isDisplayConfigurable('view'))) {
        $variables['label'] = $variables['elements']['title'];
        unset($variables['elements']['title']);
      }
    

    Needs to find a working solution for existing content

  • 🇮🇹Italy senzaesclusiva

    Damn, having started from scratch I didn't realise this abnormal behaviour

  • 🇫🇷France Julien Tekrane

    As workaround I used extra_field → module and created a custom fake field :

    my_module/src/Plugin/ExtraField/Display/TitleExtraField.php

    <?php
    
    declare(strict_types=1);
    
    namespace Drupal\my_module\Plugin\ExtraField\Display;
    
    use Drupal\Core\Entity\ContentEntityInterface;
    use Drupal\extra_field_plus\Plugin\ExtraFieldPlusDisplayBase;
    use Drupal\Core\Link;
    use Drupal\Core\Url;
    use Drupal\Core\Template\Attribute;
    
    /**
     * Title Extra field Display.
     *
     * @ExtraFieldDisplay(
     *   id = "extra_title",
     *   label = @Translation("Extra Field: Title"),
     *   bundles = {
     *     "node.*"
     *   },
     *   visible = false
     * )
     */
    class TitleExtraField extends ExtraFieldPlusDisplayBase {
    
      /**
       * {@inheritdoc}
       */
      public function view(ContentEntityInterface $entity) {
        $settings = $this->getEntityExtraFieldSettings();
    
        // Prepare an empty render array.
        $render = [];
    
        // Convert attributes string to an array.
        $attributes = [];
        if (!empty($settings['attributes'])) {
          $attributes = $this->parseAttributes($settings['attributes']);
        }
    
        // Get the selected wrapper.
        $wrapper = $settings['wrapper'] ?? 'span';
    
        if ($settings['link_to_entity']) {
          // Create the URL for the entity.
          $url = Url::fromRoute('entity.node.canonical', ['node' => $entity->id()], ['absolute' => TRUE]);
    
          // Create a Link object.
          $link = Link::fromTextAndUrl($entity->label(), $url);
    
          // Convert the Link object to a render array.
          $render = $link->toRenderable();
    
          // Assign the parsed attributes to the link's '#attributes' key.
          if (!empty($attributes)) {
            $render['#attributes'] = $attributes;
          }
    
          // Add the wrapper element.
          $render['#prefix'] = '<' . $wrapper . '>';
          $render['#suffix'] = '</' . $wrapper . '>';
        }
        else {
          // If not linking, just render the label with attributes and wrapper.
          $render = [
            '#markup' => $entity->label(),
            '#prefix' => '<' . $wrapper . '>',
            '#suffix' => '</' . $wrapper . '>',
            '#attributes' => $attributes,
          ];
        }
    
        return $render;
      }
    
      /**
       * Helper function to parse attribute string into an array.
       *
       * @param string $attribute_string
       *   The attribute string (e.g., 'class="example" id="item"').
       *
       * @return array
       *   The attributes as an associative array.
       */
      protected function parseAttributes(string $attribute_string): array {
        $attributes = [];
    
        // Split the string into key-value pairs.
        preg_match_all('/(\w+)=["\']([^"\']+)["\']/', $attribute_string, $matches, PREG_SET_ORDER);
    
        foreach ($matches as $match) {
          $attributes[$match[1]] = $match[2];
        }
    
        return $attributes;
      }
    
      /**
       * {@inheritdoc}
       */
      protected static function extraFieldSettingsForm(): array {
        $form = parent::extraFieldSettingsForm();
    
        $form['attributes'] = [
          '#type' => 'textfield',
          '#title' => t('Attributes'),
        ];
    
        $form['link_to_entity'] = [
          '#type' => 'checkbox',
          '#title' => t('Link to the entity'),
        ];
    
        // Add a select element for the wrapper options.
        $form['wrapper'] = [
          '#type' => 'select',
          '#title' => t('Wrapper Element'),
          '#options' => [
            'span' => t('Span'),
            'div' => t('Div'),
            'h1' => t('H1'),
            'h2' => t('H2'),
            'h3' => t('H3'),
            'h4' => t('H4'),
            'h5' => t('H5'),
          ],
          '#default_value' => 'span',
        ];
    
        return $form;
      }
    
      /**
       * {@inheritdoc}
       */
      protected static function defaultExtraFieldSettings(): array {
        $values = parent::defaultExtraFieldSettings();
    
        $values += [
          'attributes' => '',
          'link_to_entity' => FALSE,
          'wrapper' => 'span', // Default to span
        ];
    
        return $values;
      }
    
      /**
       * {@inheritdoc}
       */
      protected static function settingsSummary(string $field_id, string $entity_type_id, string $bundle, string $view_mode = 'default'): array {
        return [
          t('Attributes: @attributes', [
            '@attributes' => self::getExtraFieldSetting($field_id, 'attributes', $entity_type_id, $bundle, $view_mode),
          ]),
          t('Link to the entity: @link', [
            '@link' => self::getExtraFieldSetting($field_id, 'link_to_entity', $entity_type_id, $bundle, $view_mode) ? t('Yes') : t('No'),
          ]),
          t('Wrapper: @wrapper', [
            '@wrapper' => self::getExtraFieldSetting($field_id, 'wrapper', $entity_type_id, $bundle, $view_mode),
          ]),
        ];
      }
    
    }
    
  • 🇬🇧United Kingdom adamps

    Needs rebasing onto 3.x please

  • 🇺🇦Ukraine AstonVictor

    astonvictor → changed the visibility of the branch 8.x-1.x to hidden.

  • 🇺🇦Ukraine AstonVictor

    Changed the target branch to 3.x and fixed merge conflicts.

  • 🇬🇧United Kingdom adamps

    Great thanks, that is now a lot clearer. There is now something that I can review and understand. I made some comments in the MR.

    There are some main changes I believe we need. See #4 where I describe a possible solution.

    1) The problem exists not only for nodes, it can be for other entities too. So the fix should be at the entity level not the node level.

    2) Currently this patch forces a new behaviour. It's not backward-compatible for existing sites, and not everyone will agree to have the title in two places (the block and the ordinary field display). So we need to have a config setting as I suggested.

    3) This is a big new feature so it needs at a test please. It can be quite a simple test.

Production build 0.71.5 2024