0

I am trying to create a node programatically like so,

$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);

Here I have potentially 4 taxonomies to pick from (their id indicated in brackets) Creative (2), Technical (3), Marketing (4), Client Services (6).

On node_save I am getting the following error,

500 Internal Server Error : An error occurred (23000): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'tid' cannot be null

How do I overcome this this I would have thought setting the field_job_category to the id of the taxonomy would be enough?

  • Try to create your node using Entity API, take a look at the second example in this article Create a Node in Code . Note From the article fewer lines of code, better clarity, and less trouble from language/translation issues – berramou Sep 22 '18 at 2:13
1

If you have one tid by node use:

$tid = 0;    
$newNode->taxonomy[0]->tid = $tid;

if the node can have more than one term use:

$tids = [0, 3, 4, 5];
$i = 0;
foreach ($tids as $tid) {
  $newNode->taxonomy[$i]->tid = $tid;
  $i++;
}
  • If my taxonomy is a custom field called job category would I do, $newNode->field_job_category[$i] = $tid – Udders Sep 21 '18 at 15:09
  • Yes, if you use a multilangual site use this: $newNode->field_job_category[$newNode->language][$i]['tid'] = $tid; – MiharbKH Sep 21 '18 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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