public function WorkflowDefaultFormatter::viewElements in Workflow 8
N.B. A large part of this function is taken from CommentDefaultFormatter.
Overrides FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ WorkflowDefaultFormatter.php, line 112
Class
- WorkflowDefaultFormatter
- Provides a default workflow formatter.
Namespace
Drupal\workflow\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$output = [];
$field_name = $this->fieldDefinition
->getName();
$entity = $items
->getEntity();
$entity_type = $entity
->getEntityTypeId();
// @todo Perhaps global user is not always the correct user.
// E.g., on ScheduledTransition->execute()? But this function is mostly used in UI.
$user = $this->currentUser;
// @todo #2287057: OK?
$current_sid = WorkflowManager::getCurrentStateId($entity, $field_name);
// First compose the current value with the normal formatter from list.module.
$elements = workflow_state_formatter($entity, $field_name, $current_sid);
/** @var \Drupal\workflow\Entity\WorkflowState $current_state */
$current_state = WorkflowState::load($current_sid);
// The state must not be deleted, or corrupted.
if (!$current_state) {
return $elements;
}
// Check permission, so that even with state change rights,
// the form can be suppressed from the entity view (#1893724).
$type_id = $current_state
->getWorkflowId();
if (!$this->currentUser
->hasPermission("access {$type_id} workflow_transition form")) {
return $elements;
}
// Workflows are added to the search results and search index by
// workflow_node_update_index() instead of by this formatter, so don't
// return anything if the view mode is search_index or search_result.
if (in_array($this->viewMode, [
'search_result',
'search_index',
])) {
return $elements;
}
if ($entity_type == 'comment') {
// No Workflow form allowed on a comment display.
// (Also, this avoids a lot of error messages.)
return $elements;
}
// Only build form if user has possible target state(s).
if (!$current_state
->showWidget($entity, $field_name, $user, FALSE)) {
return $elements;
}
// Remove the default formatter. We are now building the widget.
$elements = [];
// BEGIN Copy from CommentDefaultFormatter.
$elements['#cache']['contexts'][] = 'user.permissions';
// Add the WorkflowTransitionForm to the page.
$output['workflows'] = WorkflowManager::getWorkflowTransitionForm($entity, $field_name, []);
// Only show the add workflow form if the user has permission.
$elements['#cache']['contexts'][] = 'user.roles';
// Do not show the form for the print view mode.
$elements[] = $output + [
'#workflow_type' => $this
->getFieldSetting('workflow_type'),
'#workflow_display_mode' => $this
->getFieldSetting('default_mode'),
'workflows' => [],
];
// END Copy from CommentDefaultFormatter.
return $elements;
}