Programmatically get and set field values

Povylas picture Povylas · Mar 27, 2011 · Viewed 21.7k times · Source

I have two fields I want to fill with the exactly same values; users should fill only one.
I also have a function which checks if the second field is empty. Is there any change in how the field values are obtained and set in Drupal 6, and Drupal 7?

EDIT: I am trying to edit module right now.
Yes, I am talking about node fields.
$node array has only ID of terms I added to node. How do I get the term name, knowing its ID?

Answer

psparrow picture psparrow · Mar 28, 2011

Since you tagged this question with cck, I'm going to assume you are working with node fields.

To copy the value of one field (x) to another (y), you can either install the Computed Field module and set it up so that the value of y is computed from the value of x, or you can create a custom module with something similar to the following hooks:

This hook copies all of the data from field x to field y:

function mymodule_node_presave($node) {
    $node->field_y = $node->field_x;
}

This hook only copies the value of the first instance of field x to field y:

function mymodule_node_presave($node) {
    $node->field_y[$node->language][0]['value'] = $node->field_x[$node->language][0]['value'];
}

You might want to do a print_r on $node->field_x and $node->field_y as the structure of your data may be different based on the type of field you are using. If you want to check if either of the fields are empty, you can wrap the assignment statement in a conditional that calls your custom function.