You are here

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

Expanded class hierarchy of WorkflowItem

File

src/Plugin/Field/FieldType/WorkflowItem.php, line 31

Namespace

Drupal\workflow\Plugin\Field\FieldType
View 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

Namesort descending Modifiers Type Description Overrides
AllowedTagsXssTrait::allowedTags public function Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss().
AllowedTagsXssTrait::displayAllowedTags public function Returns a human-readable list of allowed tags for display in help texts.
AllowedTagsXssTrait::fieldFilterXss public function Filters an HTML string to prevent XSS vulnerabilities.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FieldItemBase::calculateDependencies public static function Calculates dependencies for field items. Overrides FieldItemInterface::calculateDependencies 2
FieldItemBase::calculateStorageDependencies public static function Calculates dependencies for field items on the storage level. Overrides FieldItemInterface::calculateStorageDependencies 1
FieldItemBase::defaultFieldSettings public static function Defines the field-level settings for this plugin. Overrides FieldItemInterface::defaultFieldSettings 7
FieldItemBase::delete public function Defines custom delete behavior for field values. Overrides FieldItemInterface::delete 2
FieldItemBase::deleteRevision public function Defines custom revision delete behavior for field values. Overrides FieldItemInterface::deleteRevision
FieldItemBase::fieldSettingsForm public function Returns a form for the field-level settings. Overrides FieldItemInterface::fieldSettingsForm 7
FieldItemBase::fieldSettingsFromConfigData public static function Returns a settings array in the field type's canonical representation. Overrides FieldItemInterface::fieldSettingsFromConfigData 1
FieldItemBase::fieldSettingsToConfigData public static function Returns a settings array that can be stored as a configuration value. Overrides FieldItemInterface::fieldSettingsToConfigData 1
FieldItemBase::getFieldDefinition public function Gets the field definition. Overrides FieldItemInterface::getFieldDefinition
FieldItemBase::getLangcode public function Gets the langcode of the field values held in the object. Overrides FieldItemInterface::getLangcode
FieldItemBase::getSetting protected function Returns the value of a field setting.
FieldItemBase::getSettings protected function Returns the array of field settings.
FieldItemBase::mainPropertyName public static function Returns the name of the main property, if any. Overrides FieldItemInterface::mainPropertyName 8
FieldItemBase::onDependencyRemoval public static function Informs the plugin that a dependency of the field will be deleted. Overrides FieldItemInterface::onDependencyRemoval 1
FieldItemBase::postSave public function Defines custom post-save behavior for field values. Overrides FieldItemInterface::postSave 2
FieldItemBase::preSave public function Defines custom presave behavior for field values. Overrides FieldItemInterface::preSave 7
FieldItemBase::setValue public function Sets the data value. Overrides Map::setValue 4
FieldItemBase::view public function Returns a renderable array for a single field item. Overrides FieldItemInterface::view
FieldItemBase::writePropertyValue 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::writePropertyValue
FieldItemBase::__construct public function Constructs a TypedData object given its definition and context. Overrides TypedData::__construct 1
FieldItemBase::__get public function Magic method: Gets a property value. Overrides FieldItemInterface::__get 2
FieldItemBase::__isset public function Magic method: Determines whether a property is set. Overrides FieldItemInterface::__isset
FieldItemBase::__set public function Magic method: Sets a property value. Overrides FieldItemInterface::__set 1
FieldItemBase::__unset public function Magic method: Unsets a property. Overrides FieldItemInterface::__unset
ListItemBase::castAllowedValue protected static function Converts a value to the correct type. 3
ListItemBase::extractAllowedValues protected static function Extracts the allowed values array from the allowed_values element. 1
ListItemBase::generateSampleValue public static function Generates placeholder field values. Overrides FieldItemBase::generateSampleValue
ListItemBase::simplifyAllowedValues protected static function Simplifies allowed values to a key-value array from the structured array. 1
ListItemBase::storageSettingsFromConfigData public static function Returns a settings array in the field type's canonical representation. Overrides FieldItemBase::storageSettingsFromConfigData
ListItemBase::storageSettingsToConfigData public static function Returns a settings array that can be stored as a configuration value. Overrides FieldItemBase::storageSettingsToConfigData
ListItemBase::structureAllowedValues protected static function Creates a structured array of allowed values from a key-value array.
ListItemBase::validateAllowedValue protected static function Checks whether a candidate allowed value is valid. 3
ListItemBase::validateAllowedValues public static function #element_validate callback for options field allowed values.
Map::$definition protected property The data definition. Overrides TypedData::$definition
Map::$properties protected property The array of properties.
Map::$values protected property An array of values for the contained properties.
Map::applyDefaultValue public function Applies the default value. Overrides TypedData::applyDefaultValue 4
Map::get public function Gets a property object. Overrides ComplexDataInterface::get
Map::getIterator public function
Map::getProperties public function Gets an array of property objects. Overrides ComplexDataInterface::getProperties
Map::getString public function Returns a string representation of the data. Overrides TypedData::getString
Map::getValue public function Gets the data value. Overrides TypedData::getValue 1
Map::set public function Sets a property value. Overrides ComplexDataInterface::set
Map::toArray public function Returns an array of all property values. Overrides ComplexDataInterface::toArray 1
Map::__clone public function Magic method: Implements a deep clone.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TypedData::$name protected property The property name.
TypedData::$parent protected property The parent typed data object.
TypedData::createInstance public static function Constructs a TypedData object given its definition and context. Overrides TypedDataInterface::createInstance
TypedData::getConstraints public function Gets a list of validation constraints. Overrides TypedDataInterface::getConstraints 9
TypedData::getDataDefinition public function Gets the data definition. Overrides TypedDataInterface::getDataDefinition
TypedData::getName public function Returns the name of a property or item. Overrides TypedDataInterface::getName
TypedData::getParent public function Returns the parent data structure; i.e. either complex data or a list. Overrides TypedDataInterface::getParent
TypedData::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
TypedData::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
TypedData::getPropertyPath public function Returns the property path of the data. Overrides TypedDataInterface::getPropertyPath
TypedData::getRoot public function Returns the root of the typed data tree. Overrides TypedDataInterface::getRoot
TypedData::setContext public function Sets the context of a property or item via a context aware parent. Overrides TypedDataInterface::setContext
TypedData::validate public function Validates the currently set data value. Overrides TypedDataInterface::validate
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2
WorkflowItem::allowedValuesDescription protected function Provides the field type specific allowed values form element #description. Overrides ListItemBase::allowedValuesDescription
WorkflowItem::allowedValuesString protected function Generates a string representation of an array of 'allowed values'. Overrides ListItemBase::allowedValuesString
WorkflowItem::defaultStorageSettings public static function Defines the storage-level settings for this plugin. Overrides ListItemBase::defaultStorageSettings
WorkflowItem::getEntity public function Gets the entity that field belongs to. Overrides FieldItemBase::getEntity
WorkflowItem::getPossibleOptions public function Returns an array of possible values with labels for display. Overrides ListItemBase::getPossibleOptions
WorkflowItem::getPossibleValues public function Returns an array of possible values. Overrides ListItemBase::getPossibleValues
WorkflowItem::getSettableOptions public function Returns an array of settable values with labels for display. Overrides ListItemBase::getSettableOptions
WorkflowItem::getSettableValues public function Returns an array of settable values. Overrides ListItemBase::getSettableValues
WorkflowItem::isEmpty public function Determines whether the data structure is empty. Overrides ListItemBase::isEmpty
WorkflowItem::onChange public function React to changes to a child property or item. Overrides Map::onChange
WorkflowItem::propertyDefinitions public static function Defines field item properties. Overrides FieldItemInterface::propertyDefinitions
WorkflowItem::schema public static function Returns the schema for the field. Overrides FieldItemInterface::schema
WorkflowItem::storageSettingsForm public function Implements hook_field_settings_form() -> ConfigFieldItemInterface::settingsForm(). Overrides ListItemBase::storageSettingsForm