You are here

class NodeField in Entity Field Condition 8

Provides a 'Node Field' condition.

Plugin annotation


@Condition(
  id = "node_field",
  label = @Translation("Node Field"),
  context_definitions = {
    "node" = @ContextDefinition(
      "entity:node",
      required = TRUE,
      label = @Translation("node")
    )
  }
)

Hierarchy

Expanded class hierarchy of NodeField

File

src/Plugin/Condition/NodeField.php, line 28

Namespace

Drupal\entity_field_condition\Plugin\Condition
View source
class NodeField extends ConditionPluginBase implements ContainerFactoryPluginInterface {

  /**
   * Drupal\Core\Entity\EntityTypeManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Drupal\Core\Entity\EntityFieldManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * Drupal\Core\Field\FieldTypePluginManagerInterface definition.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
   */
  protected $fieldTypePluginManager;

  /**
   * Creates a new NodeField instance.
   *
   * @param array $configuration
   *   The plugin configuration, i.e. an array with configuration values keyed
   *   by configuration option name. The special key 'context' may be used to
   *   initialize the defined contexts by setting it to an array of context
   *   values keyed by context names.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager interface.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager interface.
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_plugin_manager
   *   The field type plugin manager interface.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, FieldTypePluginManagerInterface $field_type_plugin_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->fieldTypePluginManager = $field_type_plugin_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('plugin.manager.field.field_type'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['entity_bundle'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Node type'),
      '#options' => $this
        ->getNodeTypes(),
      '#validated' => TRUE,
      '#ajax' => [
        'callback' => [
          $this,
          'fieldsCallback',
        ],
        'wrapper' => 'field-wrapper',
        'event' => 'change',
        'progress' => [
          'type' => 'throbber',
          'message' => $this
            ->t('Loading fields...'),
        ],
      ],
      '#default_value' => $this->configuration['entity_bundle'],
    ];

    // Load fields based on the selected entity_bundle.
    $form['field'] = [
      '#type' => 'select',
      '#prefix' => '<div id="field-wrapper">',
      '#suffix' => '</div>',
      '#title' => $this
        ->t('Field'),
      '#validated' => TRUE,
      '#options' => $this
        ->getNodeFields($this->configuration['entity_bundle']),
      '#default_value' => $this->configuration['field'],
    ];
    $form['value_source'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Value Source'),
      '#options' => [
        'null' => $this
          ->t('Is NULL'),
        'specified' => $this
          ->t('Specified'),
      ],
      '#default_value' => $this->configuration['value_source'],
    ];
    $form['value'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Value to be compared'),
      '#default_value' => $this->configuration['value'],
    ];
    return parent::buildConfigurationForm($form, $form_state);
  }

  /**
   * Return the node types.
   *
   * @return array
   *   Returns the available node types.
   */
  protected function getNodeTypes() {

    // Get all the Node types.
    $node_types = $this->entityTypeManager
      ->getStorage('node_type')
      ->loadMultiple();

    // Options for node types.
    $node_type_options = $this
      ->getEmptyOption();
    foreach ($node_types as $node_type) {

      // Adding the nodes types.
      $node_type_options[$node_type
        ->id()] = $node_type
        ->label();
    }
    return $node_type_options;
  }

  /**
   * Return the empty option for the select elements.
   *
   * @return array
   *   Returns the empty option for the select elements.
   */
  public function getEmptyOption() {
    return [
      '' => $this
        ->t('None'),
    ];
  }

  /**
   * Return the fields for a content type.
   *
   * @param string $node_type
   *   The node type machine name.
   *
   * @return array
   *   Returns the available fields for the content type.
   */
  protected function getNodeFields($node_type) {
    $labels = $this
      ->getEmptyOption();
    if (empty($node_type)) {
      return $labels;
    }

    // Getting the fields for the content type.
    $node_fields = $this->entityFieldManager
      ->getFieldDefinitions('node', $node_type);

    // Getting the field definitions.
    $field_types = $this->fieldTypePluginManager
      ->getDefinitions();
    foreach ($node_fields as $field) {

      // Get the field type label.
      $field_type_label = $field_types[$field
        ->getType()]['label']
        ->getUntranslatedString();
      $labels[$field_type_label][$field
        ->getName()] = $field
        ->getLabel();
    }
    return $labels;
  }

  /**
   * Handles switching the available fields.
   *
   * Handles switching the available fields based on the selected content type
   * (node type).
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   Returns the available fields for the selected content type.
   */
  public function fieldsCallback(array $form, FormStateInterface $form_state) {

    // Getting the node type.
    $node_type = $form_state
      ->getValues()['visibility']['node_field']['entity_bundle'];

    // Adding the content type fields.
    $form['visibility']['node_field']['field']['#options'] = $this
      ->getNodeFields($node_type);
    return $form['visibility']['node_field']['field'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {

    // Get fields values.
    $entity_bundle = $form_state
      ->getValue('entity_bundle');
    $field = $form_state
      ->getValue('field');

    // Check validation.
    if ($entity_bundle && empty($field)) {
      $form_state
        ->setErrorByName('field', $this
        ->t('If you select a node type, you must specify a field.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['entity_bundle'] = $form_state
      ->getValue('entity_bundle');
    $this->configuration['field'] = $form_state
      ->getValue('field');
    $this->configuration['value_source'] = $form_state
      ->getValue('value_source');
    $this->configuration['value'] = $form_state
      ->getValue('value');
    parent::submitConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $configuration = [
      'entity_type_id' => 'node',
      'entity_bundle' => '',
      'field' => '',
      'value_source' => 'null',
      'value' => '',
    ];
    return $configuration + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    if (empty($this->configuration['field']) && !$this
      ->isNegated()) {
      return TRUE;
    }
    $entity_type_id = $this->configuration['entity_type_id'];
    $entity_bundle = $this->configuration['entity_bundle'];
    $field = $this->configuration['field'];

    /** @var \Drupal\node\Entity\Node $entity */
    $entity = $this
      ->getContextValue($entity_type_id);
    if (is_subclass_of($entity, 'Drupal\\Core\\Entity\\ContentEntityBase') && $entity
      ->getEntityTypeId() === $entity_type_id && $entity
      ->getType() === $entity_bundle) {
      $value = $entity
        ->get($field)
        ->getValue();
      $value_to_compare = NULL;

      // Structured data.
      if (is_array($value)) {
        if (!empty($value)) {

          // Loop through each value and compare.
          foreach ($value as $value_item) {

            // Check for target_id to support references.
            if (isset($value_item['target_id'])) {
              $value_to_compare = $value_item['target_id'];
            }
            elseif (isset($value_item['uri'])) {
              $value_to_compare = $value_item['uri'];
            }
            else {
              $value_to_compare = $value_item['value'];
            }

            // Return comparison only if true.
            if ($value_to_compare === $this->configuration['value']) {
              return TRUE;
            }
          }
        }
      }
      else {
        $value_to_compare = $value;
      }

      // Compare if null.
      if ($this->configuration['value_source'] === 'null') {
        return is_null($value_to_compare);
      }

      // Regular comparison.
      return $value_to_compare === $this->configuration['value'];
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function summary() {

    // Entity Type.
    $entity_type_id = $this->configuration['entity_type_id'];
    $entity_type_definition = $this->entityTypeManager
      ->getDefinition($entity_type_id);

    // Entity Bundle.
    $entity_bundle = $this->configuration['entity_bundle'];

    // Field.
    $field = $this->configuration['field'];
    $field_label = '';

    // Get Field label.
    foreach ($this->entityFieldManager
      ->getFieldDefinitions($entity_type_id, $entity_bundle) as $field_definition) {
      if ($field_definition
        ->getName() === $field) {
        $field_label = (string) $field_definition
          ->getLabel();
      }
    }
    return $this
      ->t('@entity_type "@entity_bundle" field "@field" is "@value"', [
      '@entity_type' => $entity_type_definition
        ->getLabel(),
      '@entity_bundle' => $entity_bundle,
      '@field' => $field_label,
      '@value' => $this->configuration['value_source'] === 'null' ? 'is NULL' : $this->configuration['value'],
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConditionPluginBase::$executableManager protected property The condition manager to proxy execute calls through.
ConditionPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ConditionPluginBase::execute public function Executes the plugin. Overrides ExecutableInterface::execute
ConditionPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ConditionPluginBase::isNegated public function Determines whether condition result will be negated. Overrides ConditionInterface::isNegated
ConditionPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ConditionPluginBase::setExecutableManager public function Sets the executable manager class. Overrides ConditionInterface::setExecutableManager
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginAssignmentTrait::t abstract protected function Ensures the t() method is available.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 9
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 4
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
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
ExecutablePluginBase::getConfig public function Gets all configuration values.
ExecutablePluginBase::getConfigDefinition public function Gets the definition of a configuration option.
ExecutablePluginBase::getConfigDefinitions public function Gets an array of definitions of available configuration options.
ExecutablePluginBase::setConfig public function Sets the value of a particular configuration option.
NodeField::$entityFieldManager protected property Drupal\Core\Entity\EntityFieldManagerInterface definition.
NodeField::$entityTypeManager protected property Drupal\Core\Entity\EntityTypeManagerInterface definition.
NodeField::$fieldTypePluginManager protected property Drupal\Core\Field\FieldTypePluginManagerInterface definition.
NodeField::buildConfigurationForm public function Form constructor. Overrides ConditionPluginBase::buildConfigurationForm
NodeField::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
NodeField::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConditionPluginBase::defaultConfiguration
NodeField::evaluate public function Evaluates the condition and returns TRUE or FALSE accordingly. Overrides ConditionInterface::evaluate
NodeField::fieldsCallback public function Handles switching the available fields.
NodeField::getEmptyOption public function Return the empty option for the select elements.
NodeField::getNodeFields protected function Return the fields for a content type.
NodeField::getNodeTypes protected function Return the node types.
NodeField::submitConfigurationForm public function Form submission handler. Overrides ConditionPluginBase::submitConfigurationForm
NodeField::summary public function Provides a human readable summary of the condition's configuration. Overrides ConditionInterface::summary
NodeField::validateConfigurationForm public function Form validation handler. Overrides ConditionPluginBase::validateConfigurationForm
NodeField::__construct public function Creates a new NodeField instance. Overrides ConditionPluginBase::__construct
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
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
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