Accessing CCK field data (single, multiple, or shared) from another module
Last modified: May 3, 2009 - 13:24
note- this is taken from KarenS's post to the development list
To access data stored by CCK within another module, you need to determine which table it's stored in.
To find the right table for a field for a SQL query, use the CCK API, like this:
<?php
$db_info = content_database_info($field);
$table = $db_info['table'];
?>That will always return the right table for the requested field.
$field needs to be the complete field array, not just the field name, so if you only have the field name, you would do:
<?php
$field = content_fields(my_field_name);
$db_info = content_database_info($field);
$table = $db_info['table'];
?>content_database_info($field) also contains info about the columns declared by the field so you know what field names to use in a SQL query. It returns an array that looks like:
Array (
[table] => content_type_story
[columns] => Array (
[value] => Array (
[type] => varchar
[length] => 50
[not null] => 1
[default] => ''
[sortable] => 1
[column] => field_phone_value
)
[value2] => Array (
[type] => int
[length] => 10
[unsigned] => 1
[not null] => 1
[default] => 0
[column] => field_phone_type
)
)
)
Accessing data in a cck node
In many cases, we know the table where something is stored, so don't need to do the procedure outlined here.
Is the best way to access a known field in a known content_type table just to do the database call:
select c.* from {content_type_xxx} c inner join node n on c.nid=n.nid and c.vid=n.vid??? or is there a better programmatic way to do it?
careful -- db tables for a cck field can change
even if you know what table is _currently_ used for a particular field, that could change if the field is added to (or removed from) other content types. the code outlined above by KarenS ensures always getting the correct, current table. sorry if you are already aware of that, but thought the clarification might help others.
a caution on usage for default values
If you use this code for populating cck field default values, take care to rename the $field, $table, and $db_info variables to something unique; because, the field default value code will be running in the same variable scope as the cck core modules (and the cck core is using these variable names). You can get some crazy errors when your default value code overwrites the core variables during validation.