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

Created on 19 January 2023, over 1 year ago
Updated 25 April 2024, 2 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.69.0 2024