Ability to enable entity reference purger settings to every reference field that exists

Created on 19 January 2023, almost 2 years ago
Updated 25 April 2024, 7 months ago

Problem/Motivation

When installing the module, you may need to enable the purger third-party setting for each referenced field and then find +250 references. It’s a bummer to have to point-n-click to configure 250 entity reference fields.

Proposed resolution

Here’s some code that can just do it all. It could be turned into an install hook, or as a button on a settings page depending on what you (the maintainers) want the UX to be

/**
 * Add third-party settings for each reference field that enables entity_reference_purger module.
 */
function hook_update_9001(&$sandbox) {
  $count = 0;
  $entity_manager = \Drupal::entityTypeManager();
  $entity_bundle_info = \Drupal::service('entity_type.bundle.info');
  $entity_field_manager = \Drupal::service('entity_field.manager');
  $entity_type_definitions = $entity_manager->getDefinitions();
  /* @var $definition EntityTypeInterface */
  foreach ($entity_type_definitions as $definition) {
    if ($definition instanceof ContentEntityType) {
      $bundles = $entity_bundle_info->getBundleInfo($definition->id());
      foreach ($bundles as $bundle => $label) {
        $fields = $entity_field_manager->getFieldDefinitions($definition->id(), $bundle);
        foreach ($fields as $name => $field) {
          /** @var \Drupal\field\Entity\FieldConfig $field */
          $fieldType = $field->getType();
          if($fieldType === 'entity_reference') {
            $thirdPartySettings = ($field instanceof Drupal\field\Entity\FieldConfig) ? $field->getThirdPartySettings('entity_reference_purger') : NULL;
            if(isset($thirdPartySettings) && empty($thirdPartySettings)) {
              $count++;
              \Drupal::logger('entity_reference_purger')->info('Field: ' . $name . ' Content type: ' . $bundle . ' was added to entity reference purger.');
              $field->setThirdPartySetting('entity_reference_purger','remove_orphaned', TRUE);
              $field->setThirdPartySetting('entity_reference_purger','use_queue', TRUE);
              $field->save();
            }
          }
        }
      }
    }
  }

  \Drupal::logger('entity_reference_purger')->info($count . ' fields were added to the entity reference purger.');
}

✨ Feature request
Status

Active

Version

1.0

Component

Code

Created by

🇪🇸Spain jlblanco

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024