Drupal 7 - 将分类法插入节点对象

标签 drupal drupal-7 drupal-taxonomy

我有一个可以成功创建新节点的脚本。但我在保存之前设置分类法时遇到问题。

我相信在 Drupal 6 中我会使用这种方法。

$cat1_tid = taxonomy_get_term_by_name($data[$i]['cat1']);
$cat2_tid = taxonomy_get_term_by_name($data[$i]['cat2']);
$cat3_tid = taxonomy_get_term_by_name($data[$i]['cat3']);
$node->taxonomy = array($cat1_tid, $cat2_tid, $cat3_tid);

我想在 Drupal 7 中我会这样做(我的字段名称是 Catalog)

$node->taxonomy_catalog['und'][0] = array($term1Obj, $term2Obj);

taxonomy_get_term_by_name 似乎没有返回正确的对象来插入节点对象。

如果有人能提供一些线索,我们将不胜感激。

谢谢

编辑

解决方案:

// Taxonomy
$categories = array($data[$i]['cat1'], $data[$i]['cat2'], $data[$i]['cat3']);
foreach ($categories as $key => $category) {
  if ($term = taxonomy_get_term_by_name($category)) {
    $terms_array = array_keys($term);
    $node->taxonomy_catalog[LANGUAGE_NONE][$key]['tid'] = $terms_array['0'];
  }   
} 

最佳答案

下面是我最近用来将“命令”节点导入站点的一些快速而肮脏的代码。在中间,foreach 循环负责根据需要创建和分配术语。

      $command = new stdClass;
      $command->language = LANGUAGE_NONE;
      $command->uid = 1;
      $command->type = 'drubnub';
      $command->title = $line['0'];
      $command->body[LANGUAGE_NONE]['0']['value'] = $line['1'];
      $command->url[LANGUAGE_NONE]['0']['value'] = trim($line['2']);
      $command->uses[LANGUAGE_NONE]['0']['value'] = $line['3'];
      $tags = explode(',', $line['4']);
      foreach ($tags as $key => $tag) {
        if ($term = taxonomy_get_term_by_name($tag)) {
          $terms_array = array_keys($term);
          $command->field_tags[LANGUAGE_NONE][$key]['tid'] = $terms_array['0'];
        } else {
          $term = new STDClass();
          $term->name = $tag;
          $term->vid = 1;
          if (!empty($term->name)) {
            $test = taxonomy_term_save($term);
            $term = taxonomy_get_term_by_name($tag);
            foreach($term as $term_id){
              $command->product_tags[LANGUAGE_NONE][$key]['tid'] = $term_id->tid;
          }
            $command->field_tags[LANGUAGE_NONE][$key]['tid'] = $tid;
          }
        }
      }
      node_save($command);

关于Drupal 7 - 将分类法插入节点对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4985779/

相关文章:

Drupal 7,使用 ImageField 和 Textarea 创建小部件

Drupal 以编程方式为节点设置术语

drupal-7 - Drupal 7 View 按动态分类术语过滤

forms - 以 Drupal 形式设置单个单选按钮的样式

javascript - Drupal 和 Require.js 表现不佳 - jQuery 的双重加载

drupal-7 - Drupal 7 : Modifying menu HTML output?

php - drupal - 删除图像、内容和标签文本

php - 德鲁帕尔 8 : Custom permission not working properly

javascript - 在 Drupal 7 中执行 $(window).load() 和 $(window).resize()

Drupal 从 Twitter 导入推文作为节点