1

i want to create 1 taxonomy vocabulary and 1 taxonomy term using drupal's hook_enable. but when i enable the custom module, it create only the taxonomy vocabulary. And if i disable and enable the module, the taxonomy term will be created without problem. the code is as below:

 $sql = "SELECT vid FROM {taxonomy_vocabulary} WHERE machine_name='article_type'";


$vid = db_query($sql)->fetchField();
    if (!$vid) {
      drupal_set_message(t("Created article type vocabulary"));
      // No vocabulary exists, we'll create one.
      $vocab = (object) array(
          'name' => 'article type',
          'description' => t('Automatically created by the custom_block module'),
          'machine_name' => 'article_type',
          'multiple' => '0',
          'required' => '0',
          'hierarchy' => '1',
          'relations' => '0',
          'module' => 'custom_block',
      );
      taxonomy_vocabulary_save($vocab);
      $vid = $vocab->vid

}

  $terms = (object) array (
          'name' => 'News',
          'vid' => $vid,
          'vocabulary_machine_name' => 'article_type',);

 $term_name = $terms -> name;


  $tid = db_query("SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid and name = :name", array(
    ':vid' => $vid,
    ':name' => $term_name,
  ))->fetchField();


if ($vid && !$tid) {

    taxonomy_term_save($terms);
}

}

PS:i've figured it out! it's a stupid mistake. i did not get the vid after saving the vocabulary to the database. i just need to add $vid = $vocab->vid after taxonomy_term_save.

3
  • Please add your answer and then later market it as solved. :)
    – cayerdis
    Nov 20, 2013 at 4:57
  • Sorry i'm new to this. but there seems no option to mark it as solved.
    – JIA
    Nov 20, 2013 at 15:34
  • You have to wait two days to be that available when you answer your own question ;) no worries. I was a newbie too. Welcome to Drupal Answer :D
    – cayerdis
    Nov 20, 2013 at 17:10

1 Answer 1

2

$vid remains FALSE throughout the entire first run. You need to set it after the vocabulary object is saved:

...
taxonomy_vocabulary_save($vocab);
// Add this next line
$vid = $vocab->vid;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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