SlideShare a Scribd company logo
Field API
Practical usage
Presenter
Pavel Makhrinsky
Senior Drupal developer
Berlingske Media
Introducing Field API
● CCK module successor
● The way to store and represent Entities
  properties
● Utilize Form API mechanism
Some terminology
Entities
Field Types
Field Storage
Field Instances
Bundles
Some terminology: structure
Field API
Field Types API
Field Info API
Field CRUD API
Field Storage API
Field API bulk data deletion
Field Language API
Practical tips
   How to use
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()
Implement formatter: info
function smth_field_formatter_info() {
  return array(
    'taxonomy_comma_links' => array(
      'label' => t('Comma-links'),
      'field types' => array('taxonomy_term_reference'),
    ),
  );
}
Implement formatter: view
function smth_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display){
 $element = array();

    switch ($display['type']) {
      case 'taxonomy_comma_links': {
        $links = array();
        foreach ($items as $delta => $item) {
          $term = taxonomy_term_load($item['tid']);
          $uri = entity_uri('taxonomy_term', $term);
          $links[] = l($term->name, $uri['path']);
        }
        $element[] = array(
          '#markup' => implode(', ', $links),
        );
        break;
      }
    }
     return $element;
}
Implement widget: view

hook_field_widget_info()
hook_field_widget_form()
hook_field_is_empty()
Implement widget: info
function textf_field_widget_info() {
  return array(
    'textf' => array(
      'label' => t('Text field'),
      'field types' => array('text'),
      'settings' => array('size' => 60),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}
Implement widget: form
function textf_field_widget_form(&$form, &$form_state, $field, $instance, $langcode,
$items, $delta, $element) {
 switch ($instance['widget']['type']) {
   case 'textf':
    $element['textf'] = array(
      '#type' => 'textfield',
      '#title' => $element['#title'],
      '#description' => $element['#description'],
      '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
      '#required' => $element['#required'],
      '#weight' => isset($element['#weight']) ? $element['#weight'] : 0,
      '#delta' => $delta,
    );

  break;
 }
 return $element;
Language API
Language handling: Multilingual
types
Localized
Single language site


Multilingual site
Site with different content for different languages


Multilingual site with translation
Site with translated content
Language handling
Language handling
Locale module is disabled


1.   $entity->body[und][0][value];
2.   $langcode = entity_language('entity_type', $entity);
3.   $langcode == 'und'
Language handling
Locale and Content translation modules enabled


 1.   $entity->body[und][0][value];
 2.   $langcode = entity_language('entity_type', $entity);
 3.   $langcode == 'en'
Language handling
Locale and Entity translation modules enabled


Shared fields
1. $entity->body[und][0][value];
2. $langcode = entity_language('entity_type', $entity);
3. $langcode == 'en'

Translatable fields
1. $entity->body[en][0][value];
2. $entity->body[de][0][value];
3. $langcode = entity_language('entity_type', $entity);
4. $langcode == 'en'
Getting field data

function field_get_items($entity_type, $entity, $field_name, $langcode = NULL)
function field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL)
function field_view_value($entity_type, $entity, $field_name, $item, $display = array(), $langcode = NULL)
Entity API: metadata
 1.   // hook_entity_property_info_alter
 2.   class InviteMetadataController extends EntityDefaultMetadataController {
 3.     public function entityPropertyInfo() {
 4.      $info = parent::entityPropertyInfo();
 5.      $properties = &$info[$this->type]['properties'];
 6.
 7.        $properties['inviter'] = array(
 8.          'label' => t('Inviter'),
 9.          'type' => 'user',
10.          'getter callback' => 'entity_property_getter_method',
11.          'setter callback' => 'entity_property_setter_method',
12.          'schema field' => 'uid',
13.          'required' => TRUE,
14.        );
15.
16.        $properties['invite_accept_link'] = array(
17.          'label' => t('Invite action link: accept'),
18.          'getter callback' => 'invite_metadata_entity_get_properties',
19.          'type' => 'uri',
20.          'computed' => TRUE,
21.          'entity views field' => TRUE,
22.        );
23.
24.        return $info;
25.    }
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();
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
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;
}
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,
  );
}
Useful links
http://drupal.org/node/443536
http://drupal.org/project/entity
http://api.drupal.org/api/drupal/modules%21field%21field.
module/group/field/7
http://drupal.org/project/examples
http://drupal.org/project/edit
http://drupal.org/project/layout
Questions?
Pavel Makhrinsky
drupal.org: http://drupal.org/user/773216
facebook: https://www.facebook.com/gumanist

More Related Content

What's hot (20)

Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
Andy Postnikov
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
Kacper Gunia
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
Nate Abele
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Kacper Gunia
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
Richard McIntyre
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
Kacper Gunia
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
Attila Jenei
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
Kacper Gunia
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
Alexandru Badiu
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
drubb
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
Kacper Gunia
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
Nate Abele
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Kacper Gunia
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
Kacper Gunia
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
Attila Jenei
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
Alexandru Badiu
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
drubb
 

Similar to Drupal Field API. Practical usage (20)

Fields in Core: How to create a custom field
Fields in Core: How to create a custom fieldFields in Core: How to create a custom field
Fields in Core: How to create a custom field
Ivan Zugec
 
Entity api
Entity apiEntity api
Entity api
Bishant Shrestha
 
Pure Sign Breakfast Presentations - Drupal FieldAPI
Pure Sign Breakfast Presentations - Drupal FieldAPIPure Sign Breakfast Presentations - Drupal FieldAPI
Pure Sign Breakfast Presentations - Drupal FieldAPI
Pure Sign
 
Drupal 7 Entity & Entity API
Drupal 7 Entity & Entity APIDrupal 7 Entity & Entity API
Drupal 7 Entity & Entity API
均民 戴
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
marcingy
 
ознакомления с модулем Entity api
ознакомления с модулем Entity apiознакомления с модулем Entity api
ознакомления с модулем Entity api
DrupalCamp Kyiv Рысь
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
JD Leonard
 
Understanding the Entity API Module
Understanding the Entity API ModuleUnderstanding the Entity API Module
Understanding the Entity API Module
Sergiu Savva
 
DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)
DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)
DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)
Drupaltour
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
DrupalDay
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
Marco Vito Moscaritolo
 
Drupal Form API 101 (PHP) - DrupalCamp LA 2012
Drupal Form API 101 (PHP) - DrupalCamp LA 2012Drupal Form API 101 (PHP) - DrupalCamp LA 2012
Drupal Form API 101 (PHP) - DrupalCamp LA 2012
Chris Charlton
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra
 
Field formatters
Field formattersField formatters
Field formatters
Helior Colorado
 
sfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin BundlesfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin Bundle
th0masr
 
Fapi
FapiFapi
Fapi
Steven Rifkin
 
Web automation with #d8rules (European Drupal Days 2015)
Web automation with #d8rules (European Drupal Days 2015)Web automation with #d8rules (European Drupal Days 2015)
Web automation with #d8rules (European Drupal Days 2015)
Eugenio Minardi
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
Marco Vito Moscaritolo
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
Zsolt Tasnadi
 
Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!
tedbow
 
Fields in Core: How to create a custom field
Fields in Core: How to create a custom fieldFields in Core: How to create a custom field
Fields in Core: How to create a custom field
Ivan Zugec
 
Pure Sign Breakfast Presentations - Drupal FieldAPI
Pure Sign Breakfast Presentations - Drupal FieldAPIPure Sign Breakfast Presentations - Drupal FieldAPI
Pure Sign Breakfast Presentations - Drupal FieldAPI
Pure Sign
 
Drupal 7 Entity & Entity API
Drupal 7 Entity & Entity APIDrupal 7 Entity & Entity API
Drupal 7 Entity & Entity API
均民 戴
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
marcingy
 
ознакомления с модулем Entity api
ознакомления с модулем Entity apiознакомления с модулем Entity api
ознакомления с модулем Entity api
DrupalCamp Kyiv Рысь
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
JD Leonard
 
Understanding the Entity API Module
Understanding the Entity API ModuleUnderstanding the Entity API Module
Understanding the Entity API Module
Sergiu Savva
 
DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)
DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)
DrupalTour. Lviv — Bumpy road of Drupal7 (Pavel Shevchuk, EPAM)
Drupaltour
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
DrupalDay
 
Drupal Form API 101 (PHP) - DrupalCamp LA 2012
Drupal Form API 101 (PHP) - DrupalCamp LA 2012Drupal Form API 101 (PHP) - DrupalCamp LA 2012
Drupal Form API 101 (PHP) - DrupalCamp LA 2012
Chris Charlton
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra
 
sfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin BundlesfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin Bundle
th0masr
 
Web automation with #d8rules (European Drupal Days 2015)
Web automation with #d8rules (European Drupal Days 2015)Web automation with #d8rules (European Drupal Days 2015)
Web automation with #d8rules (European Drupal Days 2015)
Eugenio Minardi
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
Zsolt Tasnadi
 
Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!
tedbow
 
Ad

Recently uploaded (20)

ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Ad

Drupal Field API. Practical usage

  • 2. Presenter Pavel Makhrinsky Senior Drupal developer Berlingske Media
  • 3. Introducing Field API ● CCK module successor ● The way to store and represent Entities properties ● Utilize Form API mechanism
  • 4. Some terminology Entities Field Types Field Storage Field Instances Bundles
  • 6. Field API Field Types API Field Info API Field CRUD API Field Storage API Field API bulk data deletion Field Language API
  • 7. Practical tips How to use
  • 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()
  • 9. Implement formatter: info function smth_field_formatter_info() { return array( 'taxonomy_comma_links' => array( 'label' => t('Comma-links'), 'field types' => array('taxonomy_term_reference'), ), ); }
  • 10. Implement formatter: view function smth_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display){ $element = array(); switch ($display['type']) { case 'taxonomy_comma_links': { $links = array(); foreach ($items as $delta => $item) { $term = taxonomy_term_load($item['tid']); $uri = entity_uri('taxonomy_term', $term); $links[] = l($term->name, $uri['path']); } $element[] = array( '#markup' => implode(', ', $links), ); break; } } return $element; }
  • 12. Implement widget: info function textf_field_widget_info() { return array( 'textf' => array( 'label' => t('Text field'), 'field types' => array('text'), 'settings' => array('size' => 60), 'behaviors' => array( 'multiple values' => FIELD_BEHAVIOR_DEFAULT, 'default value' => FIELD_BEHAVIOR_DEFAULT, ), ), ); }
  • 13. Implement widget: form function textf_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) { switch ($instance['widget']['type']) { case 'textf': $element['textf'] = array( '#type' => 'textfield', '#title' => $element['#title'], '#description' => $element['#description'], '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL, '#required' => $element['#required'], '#weight' => isset($element['#weight']) ? $element['#weight'] : 0, '#delta' => $delta, ); break; } return $element;
  • 15. Language handling: Multilingual types Localized Single language site Multilingual site Site with different content for different languages Multilingual site with translation Site with translated content
  • 17. Language handling Locale module is disabled 1. $entity->body[und][0][value]; 2. $langcode = entity_language('entity_type', $entity); 3. $langcode == 'und'
  • 18. Language handling Locale and Content translation modules enabled 1. $entity->body[und][0][value]; 2. $langcode = entity_language('entity_type', $entity); 3. $langcode == 'en'
  • 19. Language handling Locale and Entity translation modules enabled Shared fields 1. $entity->body[und][0][value]; 2. $langcode = entity_language('entity_type', $entity); 3. $langcode == 'en' Translatable fields 1. $entity->body[en][0][value]; 2. $entity->body[de][0][value]; 3. $langcode = entity_language('entity_type', $entity); 4. $langcode == 'en'
  • 20. Getting field data function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) function field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL) function field_view_value($entity_type, $entity, $field_name, $item, $display = array(), $langcode = NULL)
  • 21. Entity API: metadata 1. // hook_entity_property_info_alter 2. class InviteMetadataController extends EntityDefaultMetadataController { 3. public function entityPropertyInfo() { 4. $info = parent::entityPropertyInfo(); 5. $properties = &$info[$this->type]['properties']; 6. 7. $properties['inviter'] = array( 8. 'label' => t('Inviter'), 9. 'type' => 'user', 10. 'getter callback' => 'entity_property_getter_method', 11. 'setter callback' => 'entity_property_setter_method', 12. 'schema field' => 'uid', 13. 'required' => TRUE, 14. ); 15. 16. $properties['invite_accept_link'] = array( 17. 'label' => t('Invite action link: accept'), 18. 'getter callback' => 'invite_metadata_entity_get_properties', 19. 'type' => 'uri', 20. 'computed' => TRUE, 21. 'entity views field' => TRUE, 22. ); 23. 24. return $info; 25. }
  • 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, ); }