Maverick
Maverick

Reputation: 2760

how to get value and set value of cck custom field

I know it might be a silly question to ask, but I have a field say a and b, now how to get the value and set the value for a and b. Right now my code is like this..

$n = node_load($node->id);
$n->title;

I am getting the node title, I want to know how to get and set the value for a and b please, and if i set the value of a and b will itt be saved using

node_save($n);

??

Upvotes: 0

Views: 1544

Answers (2)

Clive
Clive

Reputation: 36957

It depends a bit which version you're using and on the particular field types you're using, but something like this:

// Drupal 6
$n = node_load($node->id);
$n->title = 'A title';
$n->field_my_field_a[0]['value'] = 'A value';
$n->field_my_field_b[0]['value'] = 'B value';
node_save($n);

// Drupal 7
$n = node_load($node->id);
$n->title = 'A title';
$n->field_my_field_a[LANGUAGE_NONE][0]['value'] = 'A value';
$n->field_my_field_b[LANGUAGE_NONE][0]['value'] = 'B value';
node_save($n);

In both cases the field data will be saved along with the node when you call node_save().

It's worth noting that the 0 index in both cases refers to the first item in a field. If a field has multiple values you can just keep adding to the array. The value key might need to change depending on the type of data that the field holds (for example a filefield will hold the fid (file id) of the file it holds so adjust accordingly.

Also LANGUAGE_NONE might need to be replaced by the required language code if you're using the Drupal 7 version.

Upvotes: 2

danielson317
danielson317

Reputation: 3288

Your question is a little confusing because you never explain what a and be are. But to access a cck field generally looks like this:

$node = node_load($nid);
$field_value = $node->field_name[0]['value'];

If it's a multiple select have values in offsets past zero. You can set the value using that same method:

$node = node_load($nid);
$node->field_name[0]['value'] = $field_value;
node_save($node);

Upvotes: 0

Related Questions