You are here

class SetFieldValue in Business Rules 8

Same name and namespace in other branches
  1. 2.x src/Plugin/BusinessRulesAction/SetFieldValue.php \Drupal\business_rules\Plugin\BusinessRulesAction\SetFieldValue

Class SetFieldValue.

@package Drupal\business_rules\Plugin\BusinessRulesAction

Plugin annotation


@BusinessRulesAction(
  id = "set_field_value",
  label = @Translation("Set field value"),
  group = @Translation("Entity"),
  description = @Translation("Set a value to an Entity field. Used only 'Before saving entity' rule."),
  isContextDependent = TRUE,
  hasTargetEntity = TRUE,
  hasTargetBundle = TRUE,
  hasTargetField = TRUE,
  reactsOnIds = {"entity_presave"}
)

Hierarchy

Expanded class hierarchy of SetFieldValue

File

src/Plugin/BusinessRulesAction/SetFieldValue.php, line 30

Namespace

Drupal\business_rules\Plugin\BusinessRulesAction
View source
class SetFieldValue extends BusinessRulesActionPlugin {

  /**
   * {@inheritdoc}
   */
  public function getSettingsForm(array &$form, FormStateInterface $form_state, ItemInterface $item) {
    $settings['value'] = [
      '#type' => 'textarea',
      '#title' => t('Value'),
      '#required' => TRUE,
      '#default_value' => $item
        ->getSettings('value'),
      '#description' => t('The value to be set on the field.
        <br>For a multi-valor field (cardinality > 1) type one value per line starting by pipeline (|) as the example:
        <br>|Value 1
        <br>|Value 2
        <br>|Value 3'),
    ];
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function execute(ActionInterface $action, BusinessRulesEvent $event) {

    /** @var \Drupal\Core\Entity\Entity $entity */
    $variables = $event
      ->getArgument('variables');
    $field = $action
      ->getSettings('field');
    $raw_value = $action
      ->getSettings('value');
    $value = $this
      ->processVariables($raw_value, $variables);
    $entity = $event
      ->getArgument('entity');
    $cardinality = $entity->{$field}
      ->getFieldDefinition()
      ->getFieldStorageDefinition()
      ->getCardinality();

    // Set value to multi-valor field.
    if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED || $cardinality > 1) {
      $arr = explode(chr(10) . '|', $value);
      if (substr($arr[0], 0, 1) == '|') {
        $arr[0] = substr($arr[0], 1, strlen($arr[0]) - 1);
      }
      foreach ($arr as $key => $value) {
        if (substr($value, strlen($value) - 1, 1) == "\r") {
          $arr[$key] = substr($value, 0, strlen($value) - 1);
        }
        $arr[$key . '000000'] = $this
          ->processVariables($arr[$key], $variables);
        unset($arr[$key]);
      }

      // Put all values at the array root.
      foreach ($arr as $key => $item) {
        if (is_array($item)) {
          unset($arr[$key]);
          foreach ($item as $new_key => $new_item) {
            $arr[$key + $new_key] = $new_item;
          }
        }
      }
      ksort($arr);
      $value = $arr;
    }
    $entity->{$field}
      ->setValue($value);
    $result = [
      '#type' => 'markup',
      '#markup' => t('Entity %entity updated. Field: %field, value: %value', [
        '%entity' => $entity
          ->getEntityTypeId(),
        '%field' => $field,
        '%value' => is_array($value) ? implode(',', $value) : $value,
      ]),
    ];
    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function processVariables($content, VariablesSet $variables) {
    if ($variables
      ->count()) {
      foreach ($variables
        ->getVariables() as $variable) {
        if (is_string($variable
          ->getValue()) || is_numeric($variable
          ->getValue())) {
          $content = str_replace('{{' . $variable
            ->getId() . '}}', $variable
            ->getValue(), $content);
        }
        elseif (is_array($variable
          ->getValue())) {
          if (preg_match_all(self::VARIABLE_REGEX, $content)) {
            if ($content == '{{' . $variable
              ->getId() . '}}') {
              $content = $variable
                ->getValue();
            }
          }
        }
      }
    }
    return $content;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BusinessRulesItemPluginBase::$processor protected property The business rules processor.
BusinessRulesItemPluginBase::$util protected property The business rules util.
BusinessRulesItemPluginBase::buildForm public function Form constructor. Overrides BusinessRulesItemPluginInterface::buildForm 11
BusinessRulesItemPluginBase::getDescription public function Provide a description of the item. Overrides BusinessRulesItemPluginInterface::getDescription
BusinessRulesItemPluginBase::getEditUrl public function Get the redirect url for the item edit-form route. Overrides BusinessRulesItemPluginInterface::getEditUrl
BusinessRulesItemPluginBase::getGroup public function Provide the group of the item. Overrides BusinessRulesItemPluginInterface::getGroup
BusinessRulesItemPluginBase::getRedirectUrl public function Get the redirect url for the item collection route. Overrides BusinessRulesItemPluginInterface::getRedirectUrl
BusinessRulesItemPluginBase::getVariables public function Return a variable set with all used variables on the item. Overrides BusinessRulesItemPluginInterface::getVariables 9
BusinessRulesItemPluginBase::pregMatch public function Extract the variables from the plugin settings. Overrides BusinessRulesItemPluginInterface::pregMatch
BusinessRulesItemPluginBase::processSettings public function Process the item settings before it's saved. Overrides BusinessRulesItemPluginInterface::processSettings 19
BusinessRulesItemPluginBase::processTokenArraySetting private function Helper function to process tokens if the setting is an array.
BusinessRulesItemPluginBase::processTokens public function Process the tokens on the settings property for the item. Overrides BusinessRulesItemPluginInterface::processTokens
BusinessRulesItemPluginBase::validateForm public function Plugin form validator. Overrides BusinessRulesItemPluginInterface::validateForm 11
BusinessRulesItemPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct 11
BusinessRulesItemPluginInterface::VARIABLE_REGEX constant
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.
SetFieldValue::execute public function Execute the action. Overrides BusinessRulesActionPlugin::execute
SetFieldValue::getSettingsForm public function Return the form array. Overrides BusinessRulesItemPluginBase::getSettingsForm
SetFieldValue::processVariables public function Process the item replacing the variables by it's values. Overrides BusinessRulesItemPluginBase::processVariables