function comment_entity_view_display_presave

Same name in other branches
  1. 9 core/modules/comment/comment.module \comment_entity_view_display_presave()
  2. 10 core/modules/comment/comment.module \comment_entity_view_display_presave()
  3. 11.x core/modules/comment/comment.module \comment_entity_view_display_presave()

Implements hook_ENTITY_TYPE_presave() for entity_view_display entities.

File

core/modules/comment/comment.module, line 791

Code

function comment_entity_view_display_presave(EntityViewDisplayInterface $display) {
    // Act only on comment view displays being disabled.
    if ($display->isNew() || $display->getTargetEntityTypeId() !== 'comment' || $display->status()) {
        return;
    }
    $storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
    if (!$storage->loadUnchanged($display->getOriginalId())
        ->status()) {
        return;
    }
    // Disable the comment field formatter when the used view display is disabled.
    foreach ($storage->loadMultiple() as $id => $view_display) {
        $changed = FALSE;
        
        /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
        foreach ($view_display->getComponents() as $field => $component) {
            if (isset($component['type']) && $component['type'] === 'comment_default') {
                if ($component['settings']['view_mode'] === $display->getMode()) {
                    $view_display->removeComponent($field);
                    
                    /** @var \Drupal\Core\Entity\EntityViewModeInterface $mode */
                    $mode = EntityViewMode::load($display->getTargetEntityTypeId() . '.' . $display->getMode());
                    $arguments = [
                        '@id' => $view_display->id(),
                        '@name' => $field,
                        '@display' => $mode->label(),
                        '@mode' => $display->getMode(),
                    ];
                    \Drupal::logger('system')->warning("View display '@id': Comment field formatter '@name' was disabled because it is using the comment view display '@display' (@mode) that was just disabled.", $arguments);
                    $changed = TRUE;
                }
            }
        }
        if ($changed) {
            $view_display->save();
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.