1

I'm using data from JSON to create new nodes on my Drupal 8 website. So, I have a createNode method that create these nodes.

Here is the code I'm using

  protected function createNode($json) {

    foreach ($json as $row) {
      $node = Node::create(array(
        'type' => 'product',
        'langcode' => 'en',
        'uid' => '1',
        'status' => 1,
        'title' => $row['title'],
        'field_code' => $row['code'],
        'field_manufacture' => $row['manufacture'],
        'field_product_type' => $row['type'],
        'field_barcode' => $row['barcode'],
        'field_packages' => $row['packages'],
        'field_pallet' => $row['pallet'],
      ));

      $node->save();
    }

  }

The problem is with field_manufacture and field_product_type, those are entity reference field to taxonomy term. I'm getting term name and I need to match it in vocabulary or add it if doesn't exist.

Any idea how to do that?

2

First, find the taxonomy term id by the term name as given below.

function getTidByName($name = NULL, $vocab_name = NULL) {
  $properties = [];
  if (!empty($name)) {
    $properties['name'] = $name;
  }
  if (!empty($vocab_name)) {
    $properties['vid'] = getVidByName($vocab_name);
  }
  $terms = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadByProperties($properties);
  $term = reset($terms);
  return !empty($term) ? $term->id() : 0;
}

Above function will return the term id and then pass this term id to your field like

// Assigning the entity reference value.
if ($tid > 0) {
  $entity->set('field_example', ['target_id' => $tid]);
}
  • what if term doesn't exists? – mixerowsky Apr 19 '17 at 8:46
  • You can use below code to create the term programmatically. use Drupal\taxonomy\Entity\Term; $term = Term::create(array( 'parent' => array(), 'name' => 'Term1', 'vid' => 'vocab_machine_name', ))->save(); – Amit Sharma Apr 19 '17 at 8:50
  • Also please check for more options drupal8.ovh/en/tutoriels/55/… – Amit Sharma Apr 19 '17 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.