以编程方式创建节点时,node_save()失败

时间:2018-09-21 14:50:26

标签: drupal-7 nodes taxonomy drupal-taxonomy taxonomy-terms

我正在尝试像这样以编程方式创建节点,

$newNode = (object) NULL;
$newNode->type = 'job';
$newNode->title = $data['JobTitle'];
$newNode->uid = $user->uid;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;
$newNode->tid = 0;

$newNode->summary['und'][0]['value'] = $data['JobSummary'];
$newNode->body['und'][0]['value'] = $data['JobDescription'];
$newNode->field_employment_type['und'] = strtolower($data['JobType']);
$newNode->field_job_reference['und'][0]['value'] = $data['JobReference'];
$newNode->field_salary['und'][0]['value'] = "";
$newNode->field_salary_from['und'][0]['value'] = $data['SalaryFrom'];
$newNode->field_salary_to['und'][0]['value'] = $data['SalaryTo'];
$newNode->field_salary_override['und'][0]['value'] = $data['Salary'];
$newNode->field_application_email['und'][0]['value'] = $data['ApplicationEmail'];
$newNode->field_job_category['und'][2] = 2;
$newNode->field_job_category['und'][4] = 4;

//die(print_r($newNode));
// save node
node_save($newNode);

在这里,我可能有4种分类法可供选择(它们的ID在括号中指示)广告素材(2),技术(3),市场营销(4),客户服务(6)。

在node_save上,我收到以下错误消息,

  

500 Internal Server Error:发生错误(23000):   SQLSTATE [23000]:违反完整性约束:1048列“ tid”   不能为空

如何克服这个问题,我本以为将field_job_category设置为分类法的ID就足够了?

2 个答案:

答案 0 :(得分:0)

删除$newNode->tid = 0;并准备对象:

$newNode = new stdClass();
$newNode->type = 'job';

node_object_prepare($node);

$newNode->title = $data['JobTitle'];
$newNode->uid = $user->uid;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;

$newNode->summary['und'][0]['value'] = $data['JobSummary'];
$newNode->body['und'][0]['value'] = $data['JobDescription'];
$newNode->field_employment_type['und'] = strtolower($data['JobType']);
$newNode->field_job_reference['und'][0]['value'] = $data['JobReference'];
$newNode->field_salary['und'][0]['value'] = "";
$newNode->field_salary_from['und'][0]['value'] = $data['SalaryFrom'];
$newNode->field_salary_to['und'][0]['value'] = $data['SalaryTo'];
$newNode->field_salary_override['und'][0]['value'] = $data['Salary'];
$newNode->field_application_email['und'][0]['value'] = $data['ApplicationEmail'];
$newNode->field_job_category['und'][]['tid'] = 2; // right syntax
$newNode->field_job_category['und'][]['tid']= 4;  // right syntax

//die(print_r($newNode));
// save node
node_save($newNode);

答案 1 :(得分:0)

如果您只想关联一个术语ID:

$newNode->field_category[LANGUAGE_NONE][0]['tid'] = <actual term id>

如果要关联多个术语ID: 遍历您的术语ID数组,并增加索引。像这样:

$newNode->field_category[LANGUAGE_NONE][0]['tid'] = <actual term id>
$newNode->field_category[LANGUAGE_NONE][1]['tid'] = <actual term id>
$newNode->field_category[LANGUAGE_NONE][2]['tid'] = <actual term id>

请注意上面的索引值。

而且,我通常为新节点设置以下属性集: