0

I want to create a standard vocabulary (no extra fields) in Drupal 8.7.5 programatically, using hook_update_N. I've never used this function before. So I'm a complete newbie.

I've modified a simple delete script I was shown, but something tells me it can't possibly be this simple.

Here's my starting point:

<?php

use Drupal\taxonomy\Entity\Vocabulary;

/**
 * create vocabulary testname.
 */
function ent_create_update_8105(&$sandbox) {
  $vid = 'testname';
  $vocabulary = Vocabulary::load($vid);
  if (!$vocabulary) {
    $vocabulary->create();
  }
}

I assume that, once the script is created correctly, I simply run drush entup.

1
  • 2
    I assume that, once the script is created correctly, I simply run drush entup. entup was removed, run drush updb to perform updates.
    – Clive
    Aug 23, 2019 at 15:41

1 Answer 1

2

Using the following code, you should be able to create a new vocabulary.

use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Create the testname vocabulary.
 */
function ent_create_update_8105(&$sandbox) {
  $vid = 'testname';

  if (!$vocabulary = Vocabulary::load($vid)) {
    $vocabulary = Vocabulary::create([
      'vid' => $vid,
      'description' => '',
      'name' => 'The vocabulary name',
    ]);

    $vocabulary->save();
  }
}

The correct hook to use to create or change entities is not hook_update_N(), though, but hook_post_update_NAME().

The hook must be added to the ent.post_update.php file, not the ent.install file. For the rest, the code is pretty much similar.

/**
 * Create the testname vocabulary.
 */
function ent_post_update_create_vocabulary(&$sandbox) {
  $vid = 'testname';

  if (!$vocabulary = Vocabulary::load($vid)) {
    $vocabulary = Vocabulary::create([
      'vid' => $vid,
      'description' => '',
      'name' => 'The vocabulary name',
    ]);

    $vocabulary->save();
  }
}
0

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.