Showing posts with label field_get_items. Show all posts
Showing posts with label field_get_items. Show all posts

Sunday, 11 September 2011

field_extract module in beta

EDIT: Now out of beta. Fully implemented.

EDIT: You can now get the module from http://drupal.org/project/field_extract and it works properly with Drush.

My incredibly useful field_extract module is now available on drupal.org. I am slightly embarrassed because something went wrong in the project creation process so the actual URL is:

http://drupal.org/project/1158878

And when you download it the module comes inside another folder "1158878". In fact this will work just as it comes, you'll just get the folder 1158878 in your modules folder with field_extract inside that.

If you're competent you can extract the inner "field_extract" module and get rid of the outer 1158878 folder but, as I say, it should work out of the box anyway. (I may get around to re-uploading it properly at some point but I can't wait any longer to get it out to you.)

So what does it do? For a start, this is only a developer's module. It does nothing by itself and should only be downloaded if requested by another module. But what it does do is provide a couple of functions that make it much easier to extract field data from entities.

The project page provides clear instructions on how to use it.

Enjoy.

Tuesday, 22 February 2011

Proper way to get field values

EDIT: download the module that encapsulates this behaviour and does a lot more besides: read this blog.

If you haven't noticed the stored structure of fields in an entity, like a node, is not simple:

$entity ->fieldname[language][delta] = [item]

The Field API does contain useful functions for manipulating these values, so if you have a $node and a field_myfield, you can get the current items like this:

$items = field_get_items('node', $node, 'field_myfield', $node->language);

Which returns an array of the items in the field, indexed by their delta value.

The actual content of each item will be dependent on what it is, a simple textfield will have array('value' => [text]) while a term reference will have array('tid' => [tid]), a "longtext with summary" (such as the standard "body" field) has several values: for the main body ('value'), for the summary ('summary'), for the filter format ('format'), and already processed "safe" values of both the body (safe_value) and the summary (safe_summary).

You can find this, and other useful functions, at Field API.

EDIT: I now have a super-duper function that extracts values for you here.