You are here

function map_widget_update_8101 in Map Widget 8

Untangles recursively nested map data.

File

./map_widget.install, line 13
Install, update and uninstall functions for the map_widget module.

Code

function map_widget_update_8101() {
  $form_displays = \Drupal::entityTypeManager()
    ->getStorage('entity_form_display')
    ->loadMultiple(NULL);
  $update_definitions = [];
  foreach ($form_displays as $display) {
    if (!$display instanceof EntityFormDisplay) {
      throw new UnexpectedValueException('Loaded display not an instance of EntityFormDisplay');
    }

    // Map fields are only base fields.

    /** @var \Drupal\Core\Field\FieldDefinitionInterface[] $definitions */
    $definitions = \Drupal::service('entity_field.manager')
      ->getBaseFieldDefinitions($display
      ->getTargetEntityTypeId());
    $components = $display
      ->getComponents();
    foreach ($components as $field_name => $component) {
      if ($component['type'] === 'map_assoc_widget') {
        $update_definitions[] = $definitions[$field_name];
      }
    }
    foreach ($update_definitions as $field_definition) {
      $storage = \Drupal::entityTypeManager()
        ->getStorage($field_definition
        ->getTargetEntityTypeId());
      $field_name = $field_definition
        ->getName();
      $query = $storage
        ->getQuery();
      $affected_ids = $query
        ->exists($field_name)
        ->execute();
      foreach ($affected_ids as $id) {
        $entity = $storage
          ->load($id);
        $munged_maps = $entity
          ->get($field_name)
          ->getValue();
        $fixed_maps = _map_widget_map_fixer($munged_maps);
        $entity
          ->get($field_name)
          ->setValue($fixed_maps);
        $entity
          ->save();
      }
    }
  }
}