2

I have a Drupal 7 node with custom fields. I have no problem setting values to the single text fields but I'm not sure how to set my select list field to one of the allowed keys of the field.

This is the code I've tried to assign the select list to the 'pending' key.

$node->field_referee_status['und'][0]['tid'] = 'pending';

Node creation code:

// CREATE NODE
$node = new stdClass;
$node->type = 'referee';
$node->title = 'Referee report for xx';
$node->uid = $user->uid;
$node->status = FALSE;
$node->field_referee_status['und'][0]['tid'] = 'pending';
$node->field_referee_id['und'][0]['value'] = 'test';
$node->field_testff['und'][0]['value'] = "testworked";
node_object_prepare($node);
node_save($node);

Question: Does anyone know the correct way to assign the key value to a custom select list field when creating Drupal nodes programmatically?

1

With a select list, you need to store the key value of the custom field.

I just noticed that you're storing taxonomy term reference value, which means you should be storing the term ID and not the actual text value of pending.

Theres a handy function which allows you to grab the TID based on a term name:

$term = taxonomy_get_term_by_name('pending');
$node->field_referee_status[LANGUAGE_NONE][0]['tid'] = $term->tid;

See the docs here.

EDIT

To save into a normal textfield select list:

$node->field_referee_status[LANGUAGE_NONE][0]['value'] = 'pending';
  • 2
    taxonomy_get_term_by_name() returns the term object not the term id. – Елин Й. Feb 23 '16 at 7:21
  • apologies, hadn't had my morning coffee when I wrote the answer heh – Alex Kirsten Feb 23 '16 at 7:24
  • Just to clarify - Does taxonomy_get_term_by_name() work on any select list? – sephiith Feb 23 '16 at 7:26
  • Um, well the function takes any argument you give it, regardless of where it comes from? So you need to make sure that the keys in the select list options contain valid taxonomy term names in this case – Alex Kirsten Feb 23 '16 at 7:30
  • 2
    Then, it should be value instead of tid – Елин Й. Feb 23 '16 at 7:57

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.