SlideShare a Scribd company logo
1 of 27
Download to read offline
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

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 clienteLeonardo 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 2016Kacper Gunia
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate 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 EditionNate Abele
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez 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 needKacper 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 LithiumNate Abele
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan 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 FrameworksNate Abele
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data ModelAttila 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 Secretssmueller_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: Formsdrubb
 

What's hot (20)

Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
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
 
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
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
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
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
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
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
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!
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
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
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
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?
 
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
 
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...
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 

Similar to Field API Practical Usage

Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperGary Hockin
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your CodeDrupalDay
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hackingJeroen van Dijk
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
 
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 fieldIvan Zugec
 
Web::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTPWeb::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTPMichael Francis
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 

Similar to Field API Practical Usage (20)

Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
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
 
Web::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTPWeb::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTP
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 

Recently uploaded

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Recently uploaded (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

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, ); }