You are here

function opigno_learning_path_update_9003 in Opigno Learning path 3.x

Replace the LP duration field with the taxonomy terms reference.

File

./opigno_learning_path.install, line 362
Install, update and uninstall functions for the module.

Code

function opigno_learning_path_update_9003() {

  // Create duration terms from current duration values.
  $durations = _opigno_learning_path_duration_terms_create();

  // Remove the old "duration" field.
  $instance = FieldConfig::loadByName('group', 'learning_path', 'field_learning_path_duration');
  if (!empty($instance)) {
    $instance
      ->delete();
  }
  if ($storage = FieldStorageConfig::loadByName('group', 'field_learning_path_duration')) {
    $storage
      ->delete();
  }

  // Add taxonomy duration field.
  $config_path = drupal_get_path('module', 'opigno_learning_path') . '/config/optional';
  $storage = new FileStorage($config_path);
  $data = $storage
    ->read('field.storage.group.field_learning_path_duration');
  if (!FieldStorageConfig::loadByName($data['entity_type'], $data['field_name'])) {
    FieldStorageConfig::create($data)
      ->save();
  }
  $data = $storage
    ->read('field.field.group.learning_path.field_learning_path_duration');
  if (!FieldConfig::loadByName($data['entity_type'], $data['bundle'], $data['field_name'])) {
    FieldConfig::create($data)
      ->save();
  }

  // Set the new field value.
  if (!$durations) {
    return;
  }
  drupal_flush_all_caches();
  foreach ($durations as $item) {
    $tid = $item['tid'];

    /** @var \Drupal\group\Entity\GroupInterface $lp */
    foreach ($item['lps'] as $lp) {
      if (!$lp
        ->hasField('field_learning_path_duration')) {
        continue;
      }

      // For some reason $lp->set('field_learning_path_duration', $tid) doesn't
      // work properly.
      $lp->field_learning_path_duration->target_id = $tid;
      try {
        $lp
          ->save();
      } catch (EntityStorageException $e) {
        watchdog_exception('opigno_learning_path_exception', $e);
      }
    }
  }
}