Skip to content
Snippets Groups Projects

For Issue #3198011

Open somersoft requested to merge issue/rules-3198011:3198011-field-item-list into 8.x-3.x
2 files
+ 150
0
Compare changes
  • Side-by-side
  • Inline
Files
2
+ 95
0
<?php
namespace Drupal\rules\Plugin\RulesAction;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\rules\Core\RulesActionBase;
/**
* Provides an 'Add to field item list' action.
*
* @RulesAction(
* id = "rules_field_list_item_add",
* label = @Translation("Add to field item list"),
* category = @Translation("Data"),
* context_definitions = {
* "list" = @ContextDefinition("list",
* label = @Translation("List"),
* description = @Translation("The field item list, to which an item is to be added."),
* assignment_restriction = "selector"
* ),
* "item" = @ContextDefinition("any",
* label = @Translation("Item"),
* description = @Translation("Item to add.")
* ),
* "unique" = @ContextDefinition("boolean",
* label = @Translation("Enforce uniqueness"),
* description = @Translation("Only add the item to the list if it is not yet contained."),
* default_value = FALSE,
* required = FALSE
* ),
* "position" = @ContextDefinition("string",
* label = @Translation("Insert position"),
* description = @Translation("Position to insert the item."),
* default_value = "end",
* required = FALSE
* ),
* }
* )
*
* @todo Add access callback information from Drupal 7?
*/
class FieldItemListAdd extends RulesActionBase {
/**
* Add an item to a list.
*
* @param \Drupal\Core\Field\FieldItemListInterface $list
* A list to which an item is added.
* @param \Drupal\Core\Entity\EntityInterface $item
* An item being added to the list.
* @param bool $unique
* (optional) Whether or not we can add duplicate items.
* @param string $position
* (optional) Determines if item will be added at beginning or end.
* Allowed values:
* - "start": Add to beginning of the list.
* - "end": Add to end of the list.
*/
protected function doExecute(FieldItemListInterface $list, EntityInterface $item, $unique = FALSE, $position = 'end') {
if ($list->isEmpty()) {
$list->appendItem($item);
}
else {
if ($unique) {
// Optionally, only add the list item if it is not yet contained.
$id = $item->id();
$filtered_list = clone $list;
$filtered_list->filter(function ($list_item) use ($id) {
return $list_item->get($list_item->mainPropertyName())
->getValue() == $id;
});
if ($filtered_list->isEmpty()) {
if ($position === 'start') {
array_unshift($list, $item);
}
else {
$list->appendItem($item);
}
}
}
else {
if ($position === 'start') {
array_unshift($list, $item);
}
else {
$list->appendItem($item);
}
}
}
$this->setContextValue('list', $list);
}
}
Loading