FieldUpdateActionBase.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Drupal\Core\Field;
  3. use Drupal\Core\Action\ActionBase;
  4. use Drupal\Core\Session\AccountInterface;
  5. /**
  6. * Provides a base for action plugins that update one or more fields.
  7. *
  8. * Example implementation:
  9. *
  10. * @code
  11. * class PromoteAndMakeSticky extends FieldUpdateActionBase {
  12. *
  13. * protected function getFieldsToUpdate() {
  14. * return [
  15. * 'status' => NODE_PROMOTED,
  16. * 'sticky' => NODE_STICKY,
  17. * ];
  18. * }
  19. *
  20. * }
  21. * @endcode
  22. *
  23. * @see \Drupal\node\Plugin\Action\PublishNode
  24. */
  25. abstract class FieldUpdateActionBase extends ActionBase {
  26. /**
  27. * Gets an array of values to be set.
  28. *
  29. * @return array
  30. * Array of values with field names as keys.
  31. */
  32. abstract protected function getFieldsToUpdate();
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function execute($entity = NULL) {
  37. foreach ($this->getFieldsToUpdate() as $field => $value) {
  38. $entity->$field = $value;
  39. }
  40. $entity->save();
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
  46. /** @var \Drupal\Core\Access\AccessResultInterface $result */
  47. $result = $object->access('update', $account, TRUE);
  48. foreach ($this->getFieldsToUpdate() as $field => $value) {
  49. $result->andIf($object->{$field}->access('edit', $account, TRUE));
  50. }
  51. return $return_as_object ? $result : $result->isAllowed();
  52. }
  53. }