class WorkflowItem in Workflow 8
Plugin implementation of the 'workflow' field type.
Plugin annotation
@FieldType(
id = "workflow",
label = @Translation("Workflow state"),
description = @Translation("This field stores Workflow values for a certain Workflow type from a list of allowed 'value => label' pairs, i.e. 'Publishing': 1 => unpublished, 2 => draft, 3 => published."),
category = @Translation("Workflow"),
default_widget = "workflow_default",
default_formatter = "list_default",
constraints = {
"WorkflowField" = {}
},
)
Hierarchy
- class \Drupal\Core\TypedData\TypedData implements PluginInspectionInterface, TypedDataInterface uses DependencySerializationTrait, StringTranslationTrait, TypedDataTrait
- class \Drupal\Core\TypedData\Plugin\DataType\Map implements \Drupal\Core\TypedData\Plugin\DataType\IteratorAggregate, ComplexDataInterface
- class \Drupal\Core\Field\FieldItemBase implements FieldItemInterface
- class \Drupal\options\Plugin\Field\FieldType\ListItemBase implements OptionsProviderInterface uses AllowedTagsXssTrait
- class \Drupal\workflow\Plugin\Field\FieldType\WorkflowItem uses MessengerTrait
- class \Drupal\options\Plugin\Field\FieldType\ListItemBase implements OptionsProviderInterface uses AllowedTagsXssTrait
- class \Drupal\Core\Field\FieldItemBase implements FieldItemInterface
- class \Drupal\Core\TypedData\Plugin\DataType\Map implements \Drupal\Core\TypedData\Plugin\DataType\IteratorAggregate, ComplexDataInterface
Expanded class hierarchy of WorkflowItem
File
- src/
Plugin/ Field/ FieldType/ WorkflowItem.php, line 31
Namespace
Drupal\workflow\Plugin\Field\FieldTypeView source
class WorkflowItem extends ListItemBase {
use MessengerTrait;
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = [
'columns' => [
'value' => [
'description' => 'The {workflow_states}.sid that this entity is currently in.',
'type' => 'varchar',
'length' => 128,
],
],
'indexes' => [
'value' => [
'value',
],
],
];
return $schema;
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
/**
* Property definitions of the contained properties.
*
* @see FileItem::getPropertyDefinitions()
*
* @var array
*/
static $propertyDefinitions;
$definition['settings']['target_type'] = 'workflow_transition';
// Definitions vary by entity type and bundle, so key them accordingly.
$key = $definition['settings']['target_type'] . ':';
$key .= isset($definition['settings']['target_bundle']) ? $definition['settings']['target_bundle'] : '';
if (!isset($propertyDefinitions[$key])) {
$propertyDefinitions[$key]['value'] = DataDefinition::create('string')
->setLabel(t('Workflow state'))
->addConstraint('Length', [
'max' => 128,
])
->setRequired(TRUE);
//workflow_debug(__FILE__, __FUNCTION__, __LINE__); // @todo D8: test this snippet.
/*
$propertyDefinitions[$key]['workflow_transition'] = DataDefinition::create('any')
// $properties['workflow_transition'] = DataDefinition::create('WorkflowTransition')
->setLabel(t('Transition'))
->setDescription(t('The computed WorkflowItem object.'))
->setComputed(TRUE)
->setClass('\Drupal\workflow\Entity\WorkflowTransition')
->setSetting('date source', 'value');
$propertyDefinitions[$key]['display'] = array(
'type' => 'boolean',
'label' => t('Flag to control whether this file should be displayed when viewing content.'),
);
$propertyDefinitions[$key]['description'] = array(
'type' => 'string',
'label' => t('A description of the file.'),
);
$propertyDefinitions[$key]['display'] = array(
'type' => 'boolean',
'label' => t('Flag to control whether this file should be displayed when viewing content.'),
);
$propertyDefinitions[$key]['description'] = array(
'type' => 'string',
'label' => t('A description of the file.'),
);
*/
}
return $propertyDefinitions[$key];
}
/**
* {@inheritdoc}
*/
public function getEntity() {
$entity = parent::getEntity();
// For Workflow on CommentForm, get the CommentedEntity.
if ($entity
->getEntityTypeId() == 'comment') {
/** @var \Drupal\comment\CommentInterface $entity */
$entity = $entity
->getCommentedEntity();
}
return $entity;
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$is_empty = empty($this->value);
return $is_empty;
}
/**
* {@inheritdoc}
*/
public function onChange($property_name, $notify = TRUE) {
//workflow_debug(__FILE__, __FUNCTION__, __LINE__); // @todo D8: test this snippet.
// @todo D8: use this function onChange for adding a line in table workflow_transition_*
// Enforce that the computed date is recalculated.
//if ($property_name == 'value') {
// $this->date = NULL;
//}
parent::onChange($property_name, $notify);
}
/**
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return [
'workflow_type' => '',
] + parent::defaultStorageSettings();
}
/**
* Implements hook_field_settings_form() -> ConfigFieldItemInterface::settingsForm().
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$element = [];
// Create list of all Workflow types. Include an initial empty value.
// Validate each workflow, and generate a message if not complete.
$workflows = workflow_get_workflow_names(FALSE);
// @todo D8: add this to WorkflowFieldConstraintValidator.
// Set message, if no 'validated' workflows exist.
if (count($workflows) == 1) {
$this
->messenger()
->addWarning($this
->t('You must <a href=":create">create at least one workflow</a>
before content can be assigned to a workflow.', [
':create' => Url::fromRoute('entity.workflow_type.collection')
->toString(),
]));
}
// Validate via annotation WorkflowFieldConstraint. Show a message for each error.
$violation_list = $this
->validate();
/** @var \Symfony\Component\Validator\ConstraintViolation $violation */
foreach ($violation_list
->getIterator() as $violation) {
switch ($violation
->getPropertyPath()) {
case 'fieldnameOnComment':
// @todo D8: CommentForm & constraints on storageSettingsForm().
// A 'comment' field name MUST be equal to content field name.
// @todo Fix fields on a non-relevant entity_type.
$this
->messenger()
->addError($violation
->getMessage());
$workflows = [];
break;
default:
break;
}
}
// @todo D8: CommentForm & constraints on storageSettingsForm.
// Set the required workflow_type on 'comment' fields.
// N.B. the following must BELOW the (count($workflows) == 1) snippet.
/** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $field_storage */
$field_storage = $this
->getFieldDefinition()
->getFieldStorageDefinition();
if (!$this
->getSetting('workflow_type') && $field_storage
->getTargetEntityTypeId() == 'comment') {
$field_name = $field_storage
->get('field_name');
$workflows = [];
foreach (_workflow_info_fields($entity = NULL, $entity_type = '', $entity_bundle = '', $field_name) as $key => $info) {
if ($info
->getName() == $field_name && $info
->getTargetEntityTypeId() !== 'comment') {
$wid = $info
->getSetting('workflow_type');
$workflow = Workflow::load($wid);
$workflows[$wid] = $workflow
->label();
}
}
}
// Let the user choose between the available workflow types.
$wid = $this
->getSetting('workflow_type');
$url = Url::fromRoute('entity.workflow_type.collection')
->toString();
$element['workflow_type'] = [
'#type' => 'select',
'#title' => $this
->t('Workflow type'),
'#options' => $workflows,
'#default_value' => $wid,
'#required' => TRUE,
'#disabled' => $has_data,
'#description' => $this
->t('Choose the Workflow type. Maintain workflows
<a href=":url">here</a>.', [
':url' => $url,
]),
];
// Get a string representation to show all options.
/*
* Overwrite ListItemBase::storageSettingsForm().
*/
if ($wid) {
$allowed_values = WorkflowState::loadMultiple([], $wid);
// $allowed_values_function = $this->getSetting('allowed_values_function');
$element['allowed_values'] = [
'#type' => 'textarea',
'#title' => $this
->t('Allowed values for the selected Workflow type'),
'#default_value' => $wid ? $this
->allowedValuesString($allowed_values) : [],
'#rows' => count($allowed_values),
'#access' => $wid ? TRUE : FALSE,
// User can see the data,
'#disabled' => TRUE,
// .. but cannot change them.
'#element_validate' => [
[
get_class($this),
'validateAllowedValues',
],
],
'#field_has_data' => $has_data,
'#field_name' => $this
->getFieldDefinition()
->getName(),
'#entity_type' => $this
->getEntity() ? $this
->getEntity()
->getEntityTypeId() : '',
'#allowed_values' => $allowed_values,
'#description' => $this
->allowedValuesDescription(),
];
}
return $element;
}
/**
* {@inheritdoc}
*/
protected function allowedValuesDescription() {
return '';
}
/**
* Generates a string representation of an array of 'allowed values'.
*
* This string format is suitable for edition in a textarea.
*
* @param \Drupal\Core\Entity\EntityInterface[] $states
* An array of WorkflowStates, where array keys are values and array values are
* labels.
*
* @return string
* The string representation of the $states array:
* - Values are separated by a carriage return.
* - Each value is in the format "value|label" or "value".
*/
protected function allowedValuesString($states) {
$lines = [];
$wid = $this
->getSetting('workflow_type');
$previous_wid = -1;
/** @var \Drupal\workflow\Entity\WorkflowState $state */
foreach ($states as $key => $state) {
// Only show enabled states.
if ($state
->isActive()) {
// Show a Workflow name between Workflows, if more then 1 in the list.
if (!$wid && $previous_wid != $state
->getWorkflowId()) {
$previous_wid = $state
->getWorkflowId();
$lines[] = $state
->getWorkflow()
->label() . "'s states: ";
}
$label = $this
->t('@label', [
'@label' => $state
->label(),
]);
$lines[] = " {$key}|{$label}";
}
}
return implode("\n", $lines);
}
/**
* Implementation of TypedDataInterface.
*
* @see folder \workflow\src\Plugin\Validation\Constraint
*/
/**
* Implementation of OptionsProviderInterface.
*
* An array of settable options for the object that may be used in an
* Options widget, usually when new data should be entered. It may either be
* a flat array of option labels keyed by values, or a two-dimensional array
* of option groups (array of flat option arrays, keyed by option group
* label). Note that labels should NOT be sanitized.
*/
/**
* {@inheritdoc}
*/
public function getPossibleValues(AccountInterface $account = NULL) {
// Flatten options first, because SettableOptions may have 'group' arrays.
$flatten_options = OptGroup::flattenOptions($this
->getPossibleOptions($account));
return array_keys($flatten_options);
}
/**
* {@inheritdoc}
*/
public function getPossibleOptions(AccountInterface $account = NULL) {
$allowed_options = [];
// When we are initially on the Storage settings form, no wid is set, yet.
if (!($wid = $this
->getSetting('workflow_type'))) {
return $allowed_options;
}
// Create an empty State. This triggers to show all possible states for the Workflow.
if ($workflow = Workflow::load($wid)) {
// There is no entity, E.g., on the Rules action "Set a data value".
$user = workflow_current_user($account);
// @todo #2287057: OK?
/** @var \Drupal\workflow\Entity\WorkflowState $state */
$state = WorkflowState::create([
'wid' => $wid,
'id' => '',
]);
$allowed_options = $state
->getOptions(NULL, '', $user, FALSE);
}
return $allowed_options;
}
/**
* {@inheritdoc}
*/
public function getSettableValues(AccountInterface $account = NULL) {
// Flatten options first, because SettableOptions may have 'group' arrays.
$flatten_options = OptGroup::flattenOptions($this
->getSettableOptions($account));
return array_keys($flatten_options);
}
/**
* {@inheritdoc}
*/
public function getSettableOptions(AccountInterface $account = NULL) {
// Use the 'allowed_values_function' to calculate the options.
$allowed_options = [];
// When we are initially on the Storage settings form, no wid is set, yet.
if (!($wid = $this
->getSetting('workflow_type'))) {
return $allowed_options;
}
// On Field settings page, no entity is set.
if (!($entity = $this
->getEntity())) {
return $allowed_options;
}
$definition = $this
->getFieldDefinition()
->getFieldStorageDefinition();
$field_name = $definition
->getName();
$user = workflow_current_user($account);
// @todo #2287057: OK?
// Get the allowed new states for the entity's current state.
/** @var \Drupal\workflow\Entity\WorkflowState $state */
$sid = workflow_node_current_state($entity, $field_name);
$state = WorkflowState::load($sid);
$allowed_options = $state ? $state
->getOptions($entity, $field_name, $user, FALSE) : [];
return $allowed_options;
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
AllowedTagsXssTrait:: |
public | function | Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss(). | |
AllowedTagsXssTrait:: |
public | function | Returns a human-readable list of allowed tags for display in help texts. | |
AllowedTagsXssTrait:: |
public | function | Filters an HTML string to prevent XSS vulnerabilities. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FieldItemBase:: |
public static | function |
Calculates dependencies for field items. Overrides FieldItemInterface:: |
2 |
FieldItemBase:: |
public static | function |
Calculates dependencies for field items on the storage level. Overrides FieldItemInterface:: |
1 |
FieldItemBase:: |
public static | function |
Defines the field-level settings for this plugin. Overrides FieldItemInterface:: |
7 |
FieldItemBase:: |
public | function |
Defines custom delete behavior for field values. Overrides FieldItemInterface:: |
2 |
FieldItemBase:: |
public | function |
Defines custom revision delete behavior for field values. Overrides FieldItemInterface:: |
|
FieldItemBase:: |
public | function |
Returns a form for the field-level settings. Overrides FieldItemInterface:: |
7 |
FieldItemBase:: |
public static | function |
Returns a settings array in the field type's canonical representation. Overrides FieldItemInterface:: |
1 |
FieldItemBase:: |
public static | function |
Returns a settings array that can be stored as a configuration value. Overrides FieldItemInterface:: |
1 |
FieldItemBase:: |
public | function |
Gets the field definition. Overrides FieldItemInterface:: |
|
FieldItemBase:: |
public | function |
Gets the langcode of the field values held in the object. Overrides FieldItemInterface:: |
|
FieldItemBase:: |
protected | function | Returns the value of a field setting. | |
FieldItemBase:: |
protected | function | Returns the array of field settings. | |
FieldItemBase:: |
public static | function |
Returns the name of the main property, if any. Overrides FieldItemInterface:: |
8 |
FieldItemBase:: |
public static | function |
Informs the plugin that a dependency of the field will be deleted. Overrides FieldItemInterface:: |
1 |
FieldItemBase:: |
public | function |
Defines custom post-save behavior for field values. Overrides FieldItemInterface:: |
2 |
FieldItemBase:: |
public | function |
Defines custom presave behavior for field values. Overrides FieldItemInterface:: |
7 |
FieldItemBase:: |
public | function |
Sets the data value. Overrides Map:: |
4 |
FieldItemBase:: |
public | function |
Returns a renderable array for a single field item. Overrides FieldItemInterface:: |
|
FieldItemBase:: |
protected | function |
Different to the parent Map class, we avoid creating property objects as
far as possible in order to optimize performance. Thus we just update
$this->values if no property object has been created yet. Overrides Map:: |
|
FieldItemBase:: |
public | function |
Constructs a TypedData object given its definition and context. Overrides TypedData:: |
1 |
FieldItemBase:: |
public | function |
Magic method: Gets a property value. Overrides FieldItemInterface:: |
2 |
FieldItemBase:: |
public | function |
Magic method: Determines whether a property is set. Overrides FieldItemInterface:: |
|
FieldItemBase:: |
public | function |
Magic method: Sets a property value. Overrides FieldItemInterface:: |
1 |
FieldItemBase:: |
public | function |
Magic method: Unsets a property. Overrides FieldItemInterface:: |
|
ListItemBase:: |
protected static | function | Converts a value to the correct type. | 3 |
ListItemBase:: |
protected static | function | Extracts the allowed values array from the allowed_values element. | 1 |
ListItemBase:: |
public static | function |
Generates placeholder field values. Overrides FieldItemBase:: |
|
ListItemBase:: |
protected static | function | Simplifies allowed values to a key-value array from the structured array. | 1 |
ListItemBase:: |
public static | function |
Returns a settings array in the field type's canonical representation. Overrides FieldItemBase:: |
|
ListItemBase:: |
public static | function |
Returns a settings array that can be stored as a configuration value. Overrides FieldItemBase:: |
|
ListItemBase:: |
protected static | function | Creates a structured array of allowed values from a key-value array. | |
ListItemBase:: |
protected static | function | Checks whether a candidate allowed value is valid. | 3 |
ListItemBase:: |
public static | function | #element_validate callback for options field allowed values. | |
Map:: |
protected | property |
The data definition. Overrides TypedData:: |
|
Map:: |
protected | property | The array of properties. | |
Map:: |
protected | property | An array of values for the contained properties. | |
Map:: |
public | function |
Applies the default value. Overrides TypedData:: |
4 |
Map:: |
public | function |
Gets a property object. Overrides ComplexDataInterface:: |
|
Map:: |
public | function | ||
Map:: |
public | function |
Gets an array of property objects. Overrides ComplexDataInterface:: |
|
Map:: |
public | function |
Returns a string representation of the data. Overrides TypedData:: |
|
Map:: |
public | function |
Gets the data value. Overrides TypedData:: |
1 |
Map:: |
public | function |
Sets a property value. Overrides ComplexDataInterface:: |
|
Map:: |
public | function |
Returns an array of all property values. Overrides ComplexDataInterface:: |
1 |
Map:: |
public | function | Magic method: Implements a deep clone. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
TypedData:: |
protected | property | The property name. | |
TypedData:: |
protected | property | The parent typed data object. | |
TypedData:: |
public static | function |
Constructs a TypedData object given its definition and context. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Gets a list of validation constraints. Overrides TypedDataInterface:: |
9 |
TypedData:: |
public | function |
Gets the data definition. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Returns the name of a property or item. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Returns the parent data structure; i.e. either complex data or a list. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
|
TypedData:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
TypedData:: |
public | function |
Returns the property path of the data. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Returns the root of the typed data tree. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Sets the context of a property or item via a context aware parent. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Validates the currently set data value. Overrides TypedDataInterface:: |
|
TypedDataTrait:: |
protected | property | The typed data manager used for creating the data types. | |
TypedDataTrait:: |
public | function | Gets the typed data manager. | 2 |
TypedDataTrait:: |
public | function | Sets the typed data manager. | 2 |
WorkflowItem:: |
protected | function |
Provides the field type specific allowed values form element #description. Overrides ListItemBase:: |
|
WorkflowItem:: |
protected | function |
Generates a string representation of an array of 'allowed values'. Overrides ListItemBase:: |
|
WorkflowItem:: |
public static | function |
Defines the storage-level settings for this plugin. Overrides ListItemBase:: |
|
WorkflowItem:: |
public | function |
Gets the entity that field belongs to. Overrides FieldItemBase:: |
|
WorkflowItem:: |
public | function |
Returns an array of possible values with labels for display. Overrides ListItemBase:: |
|
WorkflowItem:: |
public | function |
Returns an array of possible values. Overrides ListItemBase:: |
|
WorkflowItem:: |
public | function |
Returns an array of settable values with labels for display. Overrides ListItemBase:: |
|
WorkflowItem:: |
public | function |
Returns an array of settable values. Overrides ListItemBase:: |
|
WorkflowItem:: |
public | function |
Determines whether the data structure is empty. Overrides ListItemBase:: |
|
WorkflowItem:: |
public | function |
React to changes to a child property or item. Overrides Map:: |
|
WorkflowItem:: |
public static | function |
Defines field item properties. Overrides FieldItemInterface:: |
|
WorkflowItem:: |
public static | function |
Returns the schema for the field. Overrides FieldItemInterface:: |
|
WorkflowItem:: |
public | function |
Implements hook_field_settings_form() -> ConfigFieldItemInterface::settingsForm(). Overrides ListItemBase:: |