This document provides an overview of the Field API in Drupal. It discusses key terminology like entities, field types, and bundles. It also demonstrates how to implement a field formatter and widget using hooks. Finally, it covers language handling and retrieving field data via the Entity API. The presentation aims to provide practical tips and examples for working with fields and entities in Drupal.
8. Implement formatter
Create a presentation of term_reference as a
comma-delimited items
1. hook_field_formatter_info()
2. hook_field_formatter_view()
(option)
3. hook_field_formatter_prepare_view()
22. Entity API: metadata
1. $invite = entity_metadata_wrapper('invite', $entity);
2.
3. // Get the value of field_name of the inviter profile.
4. $invite ->inviter->profile->field_name->value();
5. $invite ->inviter->profile->field_name->set('New name');
6.
7. // Value of the invite summary in german language.
8. $invite ->language('de')->body->summary->value();
9.
10. // Check whether we can edit inviter email address.
11. $invite ->inviter->mail->access('edit') ? TRUE : FALSE;
12.
13. // Get roles of inviter.
14. $invite ->inviter->roles->optionsList();
15.
16. // Set description of the first file in field field_files.
17. $invite ->field_files[0]->description = 'The first file';
18. $invite ->save();
19.
20. // Get invite object.
21. $invite = $invite->value();
23. Update a field without Entity
$node = node_load($nid);
$node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'value';
node_save($node);
$node = node_load($nid);
$node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'value';
field_attach_update('node', $node);
Note:
- be careful with security
- be careful with caching
24. Add AJAX validation to a specific
field
function smth_link_form_alter(&$form, &$form_state, $form_id) {
if ('example_node_form' == $form_id) {
$form['field_link'][$language][0]['#process'] =array('link_field_process',
'_smth_link_field_link_process');
}
}
function _smth_link_field_link_process($element, &$form_state, $form) {
$element['url']['#description'] = '<div id="example-link"></div>';
$element['url']['#ajax'] = array(
'callback' => 'smth_link_ajax_callback',
'wrapper' => 'example-link',
);
return $element;
}
25. Add AJAX validation to a specific
field
function kf_link_ajax_callback(&$form, $form_state) {
$values = $form_state['values'];
$field_link = $values['field_link'];
$language = $values['language'];
$url = $field_link[$language][0]['url'];
$duplicate_nodes = _kf_link_get_url_nid($url);
foreach ($duplicate_nodes as $duplicate_node) {
if (isset($duplicate_node->nid) && ($duplicate_node->nid !=$values['nid'])) {
drupal_set_message(t('This URL already exists in <a href="!url">!title</a>', array('!
title' => $duplicate_node->title, '!url' =>"node/{$duplicate_node->nid}")), 'error');
}
}
$commands = array();
$commands[] = ajax_command_html(NULL, theme('status_messages'));
return array(
'#type' => 'ajax',
'#commands' => $commands,
);
}