在drupal中以编程方式创建分类法时出错

时间:2014-10-29 05:40:06

标签: php drupal drupal-7 drupal-taxonomy

我在使用以下代码构建分类法voccabulary和术语时遇到以下错误

  

FieldException:尝试创建一个不存在或当前处于非活动状态的字段field_my_custom_vocab002的实例。在field_create_instance()中(C:\ wamp \ www \ pur_theme \ modules \ field \ field.crud.inc的第476行)。

我检查了voccabulary并创建了它,问题只出现在术语

<?php

$new_vocab = (object) array(
    'name' => 'My custom vocabulary002',
    'description' => 'Test',
    'machine_name' => 'my_custom_vocab002',
  );
taxonomy_vocabulary_save($new_vocab);

$vocab = taxonomy_vocabulary_machine_name_load('my_custom_vocab002');

$term1 = (object) array(
   'name' => 'Term 1',
    'description' => 'This is term 1',
   'vid' => $vocab->vid,
);

taxonomy_term_save($term1);

我错在哪里/哪里?

2 个答案:

答案 0 :(得分:0)

我认为这是因为您尝试创建的字词数多于2个基本字段(name和vid)。您还有一个“描述”字段。

请尝试使用此代码:

$term = new stdClass();
$term->name = 'Term 1';
$term->vid = $vocab->vid; 
$term->field_description[LANGUAGE_NONE][0]['value'] = 'This is term 1'; 
taxonomy_term_save($term);

来源:http://www.lightrains.com/blog/programmatically-create-taxonomy-term-drupal

答案 1 :(得分:0)

我发现解决这个问题的唯一方法是在创建词汇表之前创建它正在寻找的字段。我个人用自定义函数做了这个:

function MY_MODULE_create_new_taxonomy($taxonomy_name, $taxonomy_machine_name, $taxonomy_description){

  //Add field you know is going to cause trouble
  $field = array(
    'field_name' => 'field_'.$taxonomy_machine_name,
    'type' => 'text',
    'label' => 'Label'
  );

  field_create_field($field);

  //create the vocab
  $new_vocabulary = new stdClass();
  $new_vocabulary->name = $taxonomy_name;
  $new_vocabulary->machine_name = $taxonomy_machine_name;
  $new_vocabulary->description = t($taxonomy_description);
  $new_vocabulary->module = 'taxonomy';

  taxonomy_vocabulary_save($new_vocabulary);

}