Skip to content

Instantly share code, notes, and snippets.

@megclaypool
Last active May 20, 2023 06:00
Show Gist options
  • Select an option

  • Save megclaypool/b2142374e8ce56a3a1eafa6e9693db3b to your computer and use it in GitHub Desktop.

Select an option

Save megclaypool/b2142374e8ce56a3a1eafa6e9693db3b to your computer and use it in GitHub Desktop.
[Drupal create and delete taxonomy and terms programmatically (PHP)]
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\taxonomy\Entity\Term;

/**
 * Implements hook_install().
 */
function radicati_social_install() {
  $vocId = "social_sharing_options";
  $vocName = "Social Sharing Options";
  $vocDescription = "Used for Social Sharing block";
  
  $options = [
    ["Copy to Clipboard", "copy"],
    ["Facebook", "facebook"],
    ["LinkedIn", "linkedin"],
    ["Twitter", "twitter"],
  ];
  
  // Create the vocabulary if it doesn't exist
  $vocabulary = Vocabulary::load($vocId);
  if (!$vocabulary) {
    $vocabulary = Vocabulary::create([
      "vid" => $vocId,
      "description" => $vocDescription,
      "name" => $vocName,
    ]);
    $status = $vocabulary->save();
  
    // Attach a field to the vocabulary.
    FieldStorageConfig::create([
      "field_name" => "field_sharing_slug",
      "entity_type" => "taxonomy_term",
      "type" => "string",
      "settings" => [
        "max_length" => 255,
        "is_ascii" => false,
        "case_sensitive" => false,
      ],
      "module" => "core",
      "locked" => false,
      "module" => "core",
      "cardinality" => 1,
    ])->save();
  
    FieldConfig::create([
      "field_name" => "field_sharing_slug",
      "entity_type" => "taxonomy_term",
      "bundle" => $vocId,
      "label" => "Sharing Slug",
      "required" => true,
    ])->save();
  }
  
  // Create the taxonomy terms
  foreach ($options as $option) {
    $name = $option[0];
    $slug = $option[1];
    $term_exists = \Drupal::entityTypeManager()
      ->getStorage("taxonomy_term")
      ->loadByProperties(["name" => $name, "vid" => $vocId]);
  
    if (!$term_exists) {
      $term = Term::create([
        "vid" => $vocId,
        "name" => $name,
        "field_sharing_slug" => $slug,
      ]);
      $term->save();
    }
  }
}

**
 * Implements hook_uninstall().
 */
function radicati_social_uninstall() {
  // Delete the Social Sharing Options taxonomy terms
  $tids = \Drupal::entityQuery('taxonomy_term')->condition('vid', 'social_sharing_options')->execute();
  if ($tids) {
    $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
    $entities = $controller->loadMultiple($tids);
    $controller->delete($entities);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment