field2attr
Component ID
1885372
Component name
field2attr
Component type
module
Maintenance status
Development status
Component security advisory coverage
not-covered
Component created
Component changed
Component body
This module let you write less code to access field values.
Basic usage:
Let's say we have a node type called product, and has 3 fields.
field_color // simple textfield
field_image // image
field_type // single select term
In our module file:
// Implements hook_field2attr_node().
function mymodule_field2attr_node() {
return array(
'product' => array('color', 'image', 'type'),
);
}
There are 2 attributes will attach to the node object for each field:
$node->_ATTR; // The single first field item value.
$node->_ATTR_items; // Same as field_get_items().
Now we can acces this fields like:
$node->_color; // The text value.
$node->_image; // The image file uri.
$node->_type // The term id.
// With $node->_ATTR_items we got the field items array, same as field_get_items.
// php not allow field_get_items()[0] syntax, but now we can use $node->_ATTR_items[0]['safe_value'].
$node->_color_items; // Same as field_get_items('node', $node, 'field_color');
Custom field item element key:
With $node->_image can get the image file uri, but some how we want just the image file id, change the hook function to:
// Implements hook_field2attr_node().
function mymodule_field2attr_node() {
return array(
'product' => array('color', 'image'=>'#fid', 'type'),
);
}
$node->_image; // A int fid.
The '#' prefix means the field item key.
Without '#', means a callback function.
// Implements hook_field2attr_node().
function mymodule_field2attr_node() {
return array(
'product' => array('color', 'image'=>'#fid', 'type'=>'mymodule_term_filed_load'),
);
}
function mymodule_term_filed_load($field_item) {
return taxonomy_term_load($field_item['tid']);
}
$node->_type; // A full term object.
