Replace Group action with Group quick form action.

This commit is contained in:
Michael Stenta 2023-09-30 15:02:01 -04:00
parent 5296d002e4
commit 9678bd6038
10 changed files with 88 additions and 380 deletions

View File

@ -1,12 +0,0 @@
langcode: en
status: true
dependencies:
module:
- asset
- farm_group
- farm_observation
id: asset_group_action
label: 'Group asset'
type: asset
plugin: 'asset_group_action'
configuration: { }

View File

@ -1,3 +0,0 @@
action.configuration.asset_group_action:
type: action_configuration_default
label: 'Configuration for the asset group action'

View File

@ -0,0 +1,16 @@
<?php
/**
* @file
* Post update hooks for the farm_group module.
*/
use Drupal\system\Entity\Action;
/**
* Uninstall system.action.asset_group_action.
*/
function farm_group_post_update_uninstall_asset_group_action(&$sandbox) {
$config = Action::load('asset_group_action');
$config->delete();
}

View File

@ -1,259 +0,0 @@
<?php
namespace Drupal\farm_group\Form;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\Core\Url;
use Drupal\log\Entity\Log;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Provides an asset group confirmation form.
*/
class AssetGroupActionForm extends ConfirmFormBase {
/**
* The tempstore factory.
*
* @var \Drupal\Core\TempStore\SharedTempStore
*/
protected $tempStore;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $user;
/**
* The entity type.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The assets to group.
*
* @var \Drupal\Core\Entity\EntityInterface[]
*/
protected $entities;
/**
* Constructs an AssetGroupActionForm form object.
*
* @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
* The tempstore factory.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Session\AccountInterface $user
* The current user.
*/
public function __construct(PrivateTempStoreFactory $temp_store_factory, EntityTypeManagerInterface $entity_type_manager, AccountInterface $user) {
$this->tempStore = $temp_store_factory->get('asset_group_confirm');
$this->entityTypeManager = $entity_type_manager;
$this->user = $user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('tempstore.private'),
$container->get('entity_type.manager'),
$container->get('current_user')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'asset_group_action_confirm_form';
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->formatPlural(count($this->entities), 'Are you sure you want to group this @item?', 'Are you sure you want to group these @items?', [
'@item' => $this->entityType->getSingularLabel(),
'@items' => $this->entityType->getPluralLabel(),
]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
if ($this->entityType->hasLinkTemplate('collection')) {
return new Url('entity.' . $this->entityType->id() . '.collection');
}
else {
return new Url('<front>');
}
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return '';
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Group');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$this->entityType = $this->entityTypeManager->getDefinition('asset');
$this->entities = $this->tempStore->get($this->user->id());
if (empty($this->entityType) || empty($this->entities)) {
return new RedirectResponse($this->getCancelUrl()
->setAbsolute()
->toString());
}
$form['date'] = [
'#type' => 'datetime',
'#title' => $this->t('Date'),
'#default_value' => new DrupalDateTime('midnight', $this->user->getTimeZone()),
'#required' => TRUE,
];
$form['group'] = [
'#type' => 'entity_autocomplete',
'#title' => $this->t('Group'),
'#description' => $this->t('The groups to assign the asset to. Leave blank to un-assign an asset from groups.'),
'#target_type' => 'asset',
'#selection_handler' => 'views',
'#selection_settings' => [
'view' => [
'view_name' => 'farm_group_reference',
'display_name' => 'entity_reference',
],
'match_operator' => 'CONTAINS',
'match_limit' => 10,
],
'#tags' => TRUE,
'#validate_reference' => FALSE,
'#maxlength' => 1024,
];
$form['done'] = [
'#type' => 'checkbox',
'#title' => $this->t('This membership change has taken place (mark the log as done)'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Filter out entities the user doesn't have access to.
$inaccessible_entities = [];
$accessible_entities = [];
foreach ($this->entities as $entity) {
if (!$entity->access('update', $this->currentUser())) {
$inaccessible_entities[] = $entity;
continue;
}
$accessible_entities[] = $entity;
}
// Create an observation log to group the assets.
if ($form_state->getValue('confirm') && !empty($accessible_entities)) {
// Load group assets.
$groups = [];
$group_ids = array_column($form_state->getValue('group', []) ?? [], 'target_id');
if (!empty($group_ids)) {
$groups = $this->entityTypeManager->getStorage('asset')->loadMultiple($group_ids);
}
$done = (bool) $form_state->getValue('done', FALSE);
// Generate a name for the log.
// @phpstan-ignore-next-line
$asset_names = farm_log_asset_names_summary($accessible_entities);
// @phpstan-ignore-next-line
$group_names = farm_log_asset_names_summary($groups);
$log_name = $this->t('Clear group membership of @assets', ['@assets' => Markup::create($asset_names)]);
if (!empty($group_names)) {
$log_name = $this->t('Group @assets into @groups', ['@assets' => Markup::create($asset_names), '@groups' => Markup::create($group_names)]);
}
// Create the log.
$log = Log::create([
'name' => $log_name,
'type' => 'observation',
'timestamp' => $form_state->getValue('date')->getTimestamp(),
'asset' => $accessible_entities,
'is_group_assignment' => TRUE,
'group' => $groups,
]);
// Mark as done.
if ($done !== FALSE) {
$log->get('status')->first()->applyTransitionById('done');
}
// Validate the log before saving.
$violations = $log->validate();
if ($violations->count() > 0) {
$this->messenger()->addWarning(
$this->t('Could not group assets: @bundle @entity_type validation failed.',
[
'@bundle' => $log->getBundleLabel(),
'@entity_type' => $log->getEntityType()->getSingularLabel(),
],
),
);
$this->tempStore->delete($this->currentUser()->id());
$form_state->setRedirectUrl($this->getCancelUrl());
return;
}
$log->save();
$this->messenger()->addMessage($this->t('Log created: <a href=":uri">%log_label</a>', [':uri' => $log->toUrl()->toString(), '%log_label' => $log->label()]));
}
// Add warning message for inaccessible entities.
if (!empty($inaccessible_entities)) {
$inaccessible_count = count($inaccessible_entities);
$this->messenger()->addWarning($this->formatPlural($inaccessible_count, 'Could not group @count @item because you do not have the necessary permissions.', 'Could not group @count @items because you do not have the necessary permissions.', [
'@item' => $this->entityType->getSingularLabel(),
'@items' => $this->entityType->getPluralLabel(),
]));
}
$this->tempStore->delete($this->currentUser()->id());
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View File

@ -1,106 +0,0 @@
<?php
namespace Drupal\farm_group\Plugin\Action;
use Drupal\Core\Action\Plugin\Action\EntityActionBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Action that groups assets with an observation log.
*
* @Action(
* id = "asset_group_action",
* label = @Translation("Assign assets to a group with an observation log."),
* type = "asset",
* confirm_form_route_name = "farm_group.asset_group_action_form"
* )
*/
class AssetGroup extends EntityActionBase {
/**
* The tempstore object.
*
* @var \Drupal\Core\TempStore\SharedTempStore
*/
protected $tempStore;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructs a new AssetGroup object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @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.
* @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
* The tempstore factory.
* @param \Drupal\Core\Session\AccountInterface $current_user
* Current user.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, PrivateTempStoreFactory $temp_store_factory, AccountInterface $current_user) {
$this->currentUser = $current_user;
$this->tempStore = $temp_store_factory->get('asset_group_confirm');
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_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('tempstore.private'),
$container->get('current_user')
);
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
// Add dependency on farm_observation for observation logs.
$dependencies['module'][] = 'farm_observation';
return $dependencies;
}
/**
* {@inheritdoc}
*/
public function executeMultiple(array $entities) {
/** @var \Drupal\Core\Entity\EntityInterface[] $entities */
$this->tempStore->set($this->currentUser->id(), $entities);
}
/**
* {@inheritdoc}
*/
public function execute($object = NULL) {
$this->executeMultiple([$object]);
}
/**
* {@inheritdoc}
*/
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
return $object->access('update', $account, $return_as_object);
}
}

View File

@ -0,0 +1,11 @@
langcode: en
status: true
dependencies:
module:
- asset
- farm_quick_group
id: quick_group
label: 'Assign group membership'
type: asset
plugin: quick_group
configuration: { }

View File

@ -0,0 +1,4 @@
# Schema for actions.
action.configuration.quick_group:
type: action_configuration_default
label: 'Configuration for the quick group action'

View File

@ -0,0 +1,27 @@
<?php
/**
* @file
* Post update hooks for the farm_quick_group module.
*/
use Drupal\system\Entity\Action;
/**
* Install system.action.quick_group.
*/
function farm_quick_group_post_update_install_quick_group_action(&$sandbox) {
$config = Action::create([
'id' => 'quick_group',
'label' => 'Assign group membership',
'type' => 'asset',
'plugin' => 'quick_group',
'dependencies' => [
'module' => [
'asset',
'farm_quick_group',
],
],
]);
$config->save();
}

View File

@ -0,0 +1,26 @@
<?php
namespace Drupal\farm_quick_group\Plugin\Action;
use Drupal\farm_quick\Plugin\Action\QuickFormActionBase;
/**
* Action for recording group membership assignment.
*
* @Action(
* id = "quick_group",
* label = @Translation("Assign group membership"),
* type = "asset",
* confirm_form_route_name = "farm.quick.group"
* )
*/
class Group extends QuickFormActionBase {
/**
* {@inheritdoc}
*/
public function getQuickFormId(): string {
return 'group';
}
}

View File

@ -14,6 +14,7 @@ use Drupal\farm_quick\Plugin\QuickForm\QuickFormBase;
use Drupal\farm_quick\Plugin\QuickForm\QuickFormInterface;
use Drupal\farm_quick\Traits\QuickFormElementsTrait;
use Drupal\farm_quick\Traits\QuickLogTrait;
use Drupal\farm_quick\Traits\QuickPrepopulateTrait;
use Drupal\farm_quick\Traits\QuickStringTrait;
use Psr\Container\ContainerInterface;
@ -34,6 +35,7 @@ class Group extends QuickFormBase implements QuickFormInterface {
use QuickLogTrait;
use QuickFormElementsTrait;
use QuickPrepopulateTrait;
use QuickStringTrait;
/**
@ -112,6 +114,7 @@ class Group extends QuickFormBase implements QuickFormInterface {
];
// Assets.
$prepopulated_assets = $this->getPrepopulatedEntities('asset', $form_state);
$form['asset'] = [
'#type' => 'entity_autocomplete',
'#title' => $this->t('Assets'),
@ -126,6 +129,7 @@ class Group extends QuickFormBase implements QuickFormInterface {
'#maxlength' => 1024,
'#tags' => TRUE,
'#required' => TRUE,
'#default_value' => $prepopulated_assets,
];
// Groups.