function CommentHooks::entityViewDisplayPresave

Implements hook_ENTITY_TYPE_presave() for entity_view_display entities.

File

core/modules/comment/src/Hook/CommentHooks.php, line 483

Class

CommentHooks
Hook implementations for comment.

Namespace

Drupal\comment\Hook

Code

public function entityViewDisplayPresave(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 $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.