开发者

Programmatically get and set field values

I have two fields I want to fill with the exactly same values; users should fill only one.

I also have a function which 开发者_如何学Pythonchecks 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?


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.


One good way for finding out a field's value, is using field_get_items() which is provided by field API.

field_get_items($entity_type, $entity, $field_name, $langcode = NULL);

Where:

$entity_type: Is something like 'node' or 'user',

$entity: Is the entity which it's field value is needed,

$field_name: machine name of the field,

$langcode: The language that entity is stored in, It is optional and if not provided, field_get_items will find it out automatically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜