Saimon48
Saimon48

Reputation: 41

How to set custom field value for node in Drupal 7?

I'm trying to use next code for add a new node from external script:

    define('DRUPAL_ROOT', getcwd());
    include_once './includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    $node = new stdClass();
    $node->title = "Your node title";
    $node->body = "The body text of your node.";
    $node->type = 'rasskazi';
    $node->created = time();
    $node->changed = $node->created;
    $node->status = 1; // Published?
    $node->promote = 0; // Display on front page?
    $node->sticky = 0; // Display top of page?
    $node->format = 1; // Filtered HTML?
    $node->uid = 1; // Content owner uid (author)?
    $node->language = 'en';
    node_submit($node);
    node_save($node);

But how to set custom field value ('sup_id' integer for example)?

Upvotes: 4

Views: 7538

Answers (2)

DCh
DCh

Reputation: 1

Clive is spot on. You can also use the array shorthand syntax, which is better notation IMHO... e.g.

$node->field_sup_id[LANGUAGE_NONE][0]['value'] = "2499";

Upvotes: 0

Clive
Clive

Reputation: 36957

Like this:

$node->field_sup_id[LANGUAGE_NONE] = array(
  0 => array('value' => $the_id)
);

If your field has multiple cardinality you can add extra items like this:

$node->field_sup_id[LANGUAGE_NONE] = array(
  0 => array('value' => $the_id),
  1 => array('value' => $other_id)
);

And you can use the language element of the array to define what language this particular field value pertains to:

$lang = $node->language; // Or 'en', 'fr', etc.
$node->field_sup_id[$lang] = array(
  0 => array('value' => $the_id),
  1 => array('value' => $other_id)
);

Add these before your call to node_save() and the field contents will be added/updated when you do call it.

Upvotes: 7

Related Questions