Update and create term

PHOTO EMBED

Thu Jan 18 2024 16:22:30 GMT+0000 (Coordinated Universal Time)

Saved by @saida

<?php

use \Drupal\taxonomy\Entity\Term;

$vocabulariNew = ["ambit_laboral", "ambit_social", "ambit_educations"];
$path =  dirname(__FILE__) . '/data/all_terms.csv';

$newCsvData = [];
$rowFe = [];
$i = 0;

//delete todos los términos 
function _l($m, $level = 'INFO') {
  echo "$level | $m \n";
}

function _delete_terms($vid) {
  _l("Delete terms form vocabulari $vid");
  $tids = Drupal::entityQuery('taxonomy_term')
    ->accessCheck(FALSE)
    ->condition('vid', $vid)
    ->execute();

  if (empty($tids)) {
    return;
  }

  $term_storage = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term');
  $entities = $term_storage->loadMultiple($tids);

  $term_storage->delete($entities);
}

// foreach($vocabulariNew as $vid){
//   _delete_terms($vid);
// }

$csv_data = [];

$handle = fopen($path, "r");
if ($handle  !== FALSE) {

  while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $i++;
    if($i == 1){
      continue;
    }

    $csv_data[] = $row;
   

    }
    fclose($handle);


    foreach ($csv_data as $row) {

      $terms = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadTree($row[0]);
      $term_name = $row[2];
      $term_exists = false;
      $term_id = null;

      foreach ($terms as $term) {
        if ($term->name == $term_name) {
          $term_exists = true;
          $term_id = $term->tid;
          break;
        }
      }

      if (!$term_exists) {
        $term = Term::create([
          'name' => $row[2],
          'vid' => $row[0],
          'language' => 'es',
        ]);
        $term->addTranslation("ca", [
                  'name' => $row[1]
                ]);
        $term->save();
       $term_id = $term->id();
       }


      if ($term_exists && $term_id) {
        $term = Term::load($term_id);
        if($term->hasTranslation('ca')){
          $translation = $term->getTranslation('ca');
          $translation->set('name', $row[1]);
          $translation->save();
        }else{

          $term->addTranslation("ca", [
            'name' => $row[1]
          ]);
          
        }
        
        $term->save();
      }


    }

  }
content_copyCOPY