class BatchUpdateForm in Entity Usage 8
Same name and namespace in other branches
- 8.2 src/Form/BatchUpdateForm.php \Drupal\entity_usage\Form\BatchUpdateForm
- 8.3 src/Form/BatchUpdateForm.php \Drupal\entity_usage\Form\BatchUpdateForm
Form to launch batch tracking of existing entities.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\entity_usage\Form\BatchUpdateForm
Expanded class hierarchy of BatchUpdateForm
1 string reference to 'BatchUpdateForm'
File
- src/
Form/ BatchUpdateForm.php, line 14
Namespace
Drupal\entity_usage\FormView source
class BatchUpdateForm extends FormBase {
/**
* The EntityTypeManager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* BatchUpdateForm constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The EntityTypeManager service.
*/
public function __construct(EntityTypeManagerInterface $entity_manager) {
$this->entityTypeManager = $entity_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'entity_update_batch_update_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$entity_types = $this->entityTypeManager
->getDefinitions();
$types = [];
foreach ($entity_types as $type => $entity_type) {
// Only look for content entities.
if ($entity_type
->entityClassImplements('\\Drupal\\Core\\Entity\\ContentEntityInterface')) {
$types[$type] = new FormattableMarkup('@label (@machine_name)', [
'@label' => $entity_type
->getLabel(),
'@machine_name' => $type,
]);
}
}
$form['description'] = [
'#markup' => $this
->t("This form allows you to reset and track again all entity usages in your system.<br /> It may be useful if you want to have available the information about the relationships between entities before installing the module.<br /><b>Be aware though that using this operation will delete all tracked statistics and recreate everything again.</b>"),
];
$form['host_entity_types'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Delete and recreate all usage statistics for these entity types:'),
'#options' => $types,
'#default_value' => array_keys($types),
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this
->t('Recreate entity usage statistics'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$host_entity_types = array_filter($form_state
->getValue('host_entity_types'));
// Generate a batch to recreate the statistics for all entities.
// Note that if we force all statistics to be created, there is no need to
// separate them between host / target cases. If all entities are going to
// be re-tracked, tracking all of them as hosts is enough, because there
// could never be a target without host.
$batch = $this
->generateBatch($host_entity_types);
batch_set($batch);
}
/**
* Create a batch to process the entity types in bulk.
*
* @param string[] $types
* An array of entity types ids.
*
* @return array
* The batch array.
*/
public function generateBatch(array $types) {
$operations = [];
foreach ($types as $type) {
$operations[] = [
'Drupal\\entity_usage\\Form\\BatchUpdateForm::updateHostsBatchWorker',
[
$type,
],
];
}
$batch = [
'operations' => $operations,
'finished' => 'Drupal\\entity_usage\\Form\\BatchUpdateForm::batchFinished',
'title' => $this
->t('Updating entity usage statistics.'),
'progress_message' => $this
->t('Processed @current of @total entity types.'),
'error_message' => $this
->t('This batch encountered an error.'),
];
return $batch;
}
/**
* Batch operation worker for recreating statistics for host entities.
*
* @param string $entity_type_id
* The entity type id, for example 'node'.
* @param array $context
* The context array.
*/
public static function updateHostsBatchWorker($entity_type_id, array &$context) {
$entity_storage = \Drupal::entityTypeManager()
->getStorage($entity_type_id);
$entity_type = \Drupal::entityTypeManager()
->getDefinition($entity_type_id);
$entity_type_key = $entity_type
->getKey('id');
if (empty($context['sandbox']['total'])) {
// Delete current usage statistics for these entities.
\Drupal::service('entity_usage.usage')
->bulkDeleteHosts($entity_type_id);
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_id'] = -1;
$context['sandbox']['total'] = (int) $entity_storage
->getQuery()
->accessCheck(FALSE)
->count()
->execute();
}
$entity_ids = $entity_storage
->getQuery()
->condition($entity_type_key, $context['sandbox']['current_id'], '>')
->range(0, 10)
->accessCheck(FALSE)
->sort($entity_type_key)
->execute();
$entities = $entity_storage
->loadMultiple($entity_ids);
foreach ($entities as $entity) {
// Hosts are tracked as if they were new entities.
\Drupal::service('entity_usage.entity_update_manager')
->trackUpdateOnCreation($entity);
$context['sandbox']['progress']++;
$context['sandbox']['current_id'] = $entity
->id();
$context['results'][] = $entity_type_id . ':' . $entity
->id();
}
if ($context['sandbox']['progress'] < $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['total'];
}
else {
$context['finished'] = 1;
}
$context['message'] = t('Updating entity usage for @entity_type: @current of @total', [
'@entity_type' => $entity_type_id,
'@current' => $context['sandbox']['progress'],
'@total' => $context['sandbox']['total'],
]);
}
/**
* Finish callback for our batch processing.
*
* @param bool $success
* Whether the batch completed successfully.
* @param array $results
* The results array.
* @param array $operations
* The operations array.
*/
public static function batchFinished($success, array $results, array $operations) {
if ($success) {
drupal_set_message(t('Recreated entity usage for @count entities.', [
'@count' => count($results),
]));
}
else {
// An error occurred.
// $operations contains the operations that remained unprocessed.
$error_operation = reset($operations);
drupal_set_message(t('An error occurred while processing @operation with arguments : @args', [
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0], TRUE),
]));
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
BatchUpdateForm:: |
protected | property | The EntityTypeManager service. | |
BatchUpdateForm:: |
public static | function | Finish callback for our batch processing. | |
BatchUpdateForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
BatchUpdateForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
BatchUpdateForm:: |
public | function | Create a batch to process the entity types in bulk. | |
BatchUpdateForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
BatchUpdateForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
BatchUpdateForm:: |
public static | function | Batch operation worker for recreating statistics for host entities. | |
BatchUpdateForm:: |
public | function | BatchUpdateForm constructor. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
FormBase:: |
public | function |
Form validation handler. Overrides FormInterface:: |
62 |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |