You are here

public function DeleteEntity::execute in Business Rules 8

Same name and namespace in other branches
  1. 2.x src/Plugin/BusinessRulesAction/DeleteEntity.php \Drupal\business_rules\Plugin\BusinessRulesAction\DeleteEntity::execute()

Execute the action.

Parameters

\Drupal\business_rules\ActionInterface $action: The configured action.

\Drupal\business_rules\Events\BusinessRulesEvent $event: The event that has triggered the action.

Return value

array The render array to be showed on debug block.

Overrides BusinessRulesActionPlugin::execute

File

src/Plugin/BusinessRulesAction/DeleteEntity.php, line 48

Class

DeleteEntity
Class DeleteEntity.

Namespace

Drupal\business_rules\Plugin\BusinessRulesAction

Code

public function execute(ActionInterface $action, BusinessRulesEvent $event) {

  // Get settings.
  $entity_type = $action
    ->getTargetEntityType();
  $bundle = $action
    ->getTargetBundle();
  $field = $action
    ->getSettings('field');
  $value = $action
    ->getSettings('value');
  $value = $this
    ->processVariables($value, $event
    ->getArgument('variables'));

  // Load entities ids to delete.

  /** @var \Drupal\Core\Entity\Query\QueryInterface $query */
  $query = \Drupal::getContainer()
    ->get('entity_type.manager')
    ->getStorage($entity_type)
    ->getQuery()
    ->condition($field, $value);
  $ids = $query
    ->execute();

  // Delete entities.

  /** @var \Drupal\Core\Entity\EntityStorageInterface $entityManager */
  $entityManager = \Drupal::entityTypeManager()
    ->getStorage($entity_type);
  $entities = $entityManager
    ->loadMultiple($ids);
  foreach ($entities as $key => $entity) {
    if ($entity
      ->bundle() != $bundle) {
      unset($entities[$key]);
    }
  }
  $entityManager
    ->delete($entities);
  $result = [
    '#type' => 'markup',
    '#markup' => t('Entity: %entity, Bundle: %bundle, Id(s): (%id) has been deleted.', [
      '%entity' => $entity_type,
      '%bundle' => $bundle,
      '%id' => implode(',', $ids),
    ]),
  ];
  return $result;
}