SlideShare a Scribd company logo
FIELDS IN CORE:
HOW TO CREATE A CUSTOM
         FIELD
        By Ivan Zugec
WHO AM I?


• Name: Ivan   Zugec

• Drupal   username: Ivan Zugec

• Twitter: http://twitter.com/zugec

• Blog: http://zugec.com
SESSION AGENDA

• What’s   new in Drupal 7

• Understanding   fields

• How   to create a field

• Custom   formatters

• Documentation

• Q&A
WHAT’S NEW IN DRUPAL 7
WHAT’S NEW IN DRUPAL 7



• InDrupal 6 we used the
 CCK module to add fields
 into nodes
WHAT’S NEW IN DRUPAL 7



• In
   Drupal 7 a lot of CCK’s functionality has been moved into
 core

• Not   all CCK modules made it into core
WHAT’S NEW IN DRUPAL 7


• “Node  reference” and “User reference” moved to http://
 drupal.org/project/references

• “Fieldset” moved   to http://drupal.org/project/field_group

• “Contentpermission” moved to http://drupal.org/project/
 field_permissions
WHAT’S NEW IN DRUPAL 7



• Drupal    7 ships with text, options, number and list

• File   and image field all in core
UNDERSTANDING FIELDS
UNDERSTANDING FIELDS


• Pieceof functionality
 attached to an entity (node,
 taxonomy, etc...)

• Example: Date   module
UNDERSTANDING FIELDS

• Fields
     have 4 major
 components

• Field

• Field    type

• Widget

• Formatter
UNDERSTANDING FIELDS



• Field

• field.module, field.info   and field.install
UNDERSTANDING FIELDS
                                 /**
                                  * Implements hook_field_schema().
                                  */
                                 function text_field_schema($field) {
                                   switch ($field['type']) {
                                     case 'text':
                                      $columns = array(
                                        'value' => array(
                                          'type' => 'varchar',

• Field   type                            'length' => $field['settings']['max_length'],
                                          'not null' => FALSE,
                                        ),
                                      );
                                      break;

• How  the field will be stored   
                                      case 'text_long':
                                        
       ....

 in the database
                                       break;
                                     }
                                     $columns += array(
                                       'format' => array(
                                         'type' => 'varchar',
                                         'length' => 255,

• Using   hook_field_schema             ),
                                         'not null' => FALSE,

                                     );
                                     return array(
                                       'columns' => $columns,

• Using   hook_field_info               'indexes' => array(

                                       ),
                                         'format' => array('format'),

                                       'foreign keys' => array(
                                         'format' => array(
                                           'table' => 'filter_format',
                                           'columns' => array('format' => 'format'),
                                         ),
                                       ),
                                     );
UNDERSTANDING FIELDS



• Widget

• Form element a user will use
 to enter in the data
UNDERSTANDING FIELDS
UNDERSTANDING FIELDS



• Formatter

• How  to data will be
 displayed
HOW TO CREATE A FIELD
HOW TO CREATE A FIELD

• Createa custom
 “Collaborators” field

• Module will be called
 “collabfield”

• Unlimited value field with a
 Name, Role and Link text
 fields within
HOW TO CREATE A FIELD


• Createa module called
 collabfield

• Createcollabfield.info,
 collabfield.install and
 collabfield.module files
HOW TO CREATE A FIELD
                 collabfield.info


  ; $Id$

  name = Collaborator field
  description = Custom collaborator field.

  dependencies[] = field_ui

  core = 7.x
HOW TO CREATE A FIELD
                 collabfield.install
  <?php
  // $Id$

  /**
   * Implements hook_install().
   */

  function collabfield_install() {
  }

  /**
   * Implements hook_uninstall().
   */

  function collabfield_uninstall() {
  }
HOW TO CREATE A FIELD
  /**
                             collabfield.install
   * Implementation of hook_field_schema().
   */
  function collabfield_field_schema($field) {
    if ($field['type'] == 'collabfield') {
      $schema['columns']['name'] = array(
        'type' => 'varchar',
        'length' => '255',
        'not null' => FALSE,
      );

       $schema['columns']['role'] = array(
         'type' => 'varchar',
         'length' => '255',
         'not null' => FALSE,
       );

       $schema['columns']['link'] = array(
         'type' => 'varchar',
         'length' => '255',
         'not null' => FALSE,
       );

       $schema['indexes'] = array(
         'name' => array('name'),
         'role' => array('role'),
         'link' => array('link'),
       );
       return $schema;
   }
HOW TO CREATE A FIELD
                         collabfield.module
<?php
// $Id$

/**
 * Implementation of hook_field_info().
 */
function collabfield_field_info() {
  return array(
    'collabfield' => array(
      'label' => t('Collaborator'),
      'description' => t('Custom collaborators field.'),
      'default_widget' => 'collabfield_collabfield_form',
      'default_formatter' => 'collabfield_default',
    ),
  );
}
HOW TO CREATE A FIELD
                                   collabfield.module

/**
 * Implementation of hook_field_is_empty().
 */
function collabfield_field_is_empty($item, $field) {
  if ($field['type'] == 'collabfield') {

    if (empty($item['name']) && empty($item['role']) && empty($item['link'])) {
     return TRUE;

 }

  }
  return FALSE;
}
HOW TO CREATE A FIELD

• Create   a widget

• Use hook_field_widget_info
 to setup field

• Use
 hook_field_widget_form for
 the actual form element
HOW TO CREATE A FIELD
/**
 * Implements hook_field_widget_info().
 */
function collabfield_field_widget_info() {
  return array(
    'collabfield_collabfield_form' => array(
      'label' => t('Collabfield form'),
      'field types' => array('collabfield'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        //Use FIELD_BEHAVIOR_NONE for no default value.
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}
HOW TO CREATE A FIELD
/**
 * Implementation of hook_field_widget_form().
 */
function collabfield_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $base = $element;
    if ($instance['widget']['type'] == 'collabfield_collabfield_form') {
      $widget = $instance['widget'];
      $settings = $widget['settings'];

     $element['name'] = array(
       '#type' => 'textfield',
       '#title' => t('Name'),
       '#default_value' => isset($items[$delta]['name']) ? $items[$delta]['name'] : NULL,
     );
     $element['role'] = array(
       '#type' => 'textfield',
       '#title' => t('Role'),
       '#default_value' => isset($items[$delta]['role']) ? $items[$delta]['role'] : NULL,
     );
     $element['link'] = array(
       '#type' => 'textfield',
       '#title' => t('Link'),
       '#default_value' => isset($items[$delta]['link']) ? $items[$delta]['link'] : NULL,
       '#element_validate' => array('_collabfield_link_validate'),
     );

    }
    return $element;
}
HOW TO CREATE A FIELD

•   To validate an element add #element_validate to the specific
    element
$element['link'] = array(
  '#type' => 'textfield',
  '#title' => t('Link'),
  '#default_value' => isset($items[$delta]['link']) ? $items[$delta]['link'] : NULL,
  '#element_validate' => array('_collabfield_link_validate'),
);

/**
 * Validation callback for a collabfield link element.
 */
function _collabfield_link_validate($element, &$form_state, $form) {
  $value = $element['#value'];
  if (!empty($value) && !valid_url($value, TRUE)) {
    form_error($element, t('Invalid URL.'));
  }

}
HOW TO CREATE A FIELD

• Drupalships with three form element validators in
 field.module

• _element_validate_integer()

• _element_validate_integer_positive()

• _element_validate_number()
HOW TO CREATE A FIELD

• Create   a formatter

• Use
 hook_field_formatter_info
 to setup a formatter

• Use
 hook_field_formatter_view
 for the actual formatter
HOW TO CREATE A FIELD
 /**
  * Implements hook_field_formatter_info().
  */
 function collabfield_field_formatter_info() {
   return array(
     'collabfield_default' => array(
       'label' => t('Default'),
       'field types' => array('collabfield'),
     ),
   );
 }
HOW TO CREATE A FIELD
/**
 * Implements hook_field_formatter_view().
 */
function collabfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

    switch ($display['type']) {
      case 'collabfield_default':
       foreach ($items as $delta => $item) {
         $element[$delta]['#markup'] = theme('collabfield_formatter_default', $item);
       }
       break;
    }

    return $element;
}
CUSTOM FORMATTERS
CUSTOM FORMATTERS


• Formatter   to change default term reference link formatter

• Create   as custom module

• Change   URL taxonomy/term/[tid] to whatever/[tid]
CUSTOM FORMATTERS
/**
 * Implements hook_field_formatter_info().
 */
function termpathfield_field_formatter_info() {
  return array(
    'termpathfield_term_reference_link' => array(
      'label' => t('Custom path link'),
      'field types' => array('taxonomy_term_reference'),
      'settings' => array(
        'taxonomy_custom_url' => 'taxonomy/term/[tid]',
      ),
    ),
  );
}
CUSTOM FORMATTERS
/**
 * Implements hook_field_formatter_settings_form().
 */
function termpathfield_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $form = array();

    if ($display['type'] == 'termpathfield_term_reference_link') {
      $form['taxonomy_custom_url'] = array(
        '#type' => 'textfield',
        '#title' => t('Custom term page URL'),
        '#default_value' => $settings['taxonomy_custom_url'],
        '#required' => TRUE,
      );
    }

    return $form;
}
CUSTOM FORMATTERS
CUSTOM FORMATTERS
/**
 * Implements hook_field_formatter_settings_summary().
 */
function termpathfield_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = '';

    if ($display['type'] == 'termpathfield_term_reference_link') {
      $summary = $settings['taxonomy_custom_url'];
    }

    return $summary;
}
CUSTOM FORMATTERS
CUSTOM FORMATTERS
/**
 * Implements hook_field_formatter_view().
 */
function termpathfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $result = array();

    switch ($display['type']) {
     case 'termpathfield_term_reference_link':
      foreach ($items as $delta => $item) {
        $term = taxonomy_term_load($item['tid']);

          $uri_path = str_replace('[tid]', $term->tid, $display['settings']['taxonomy_custom_url']);
          $uri = url($uri_path, array('absolute' => TRUE));

          $result[$delta] = array(
            '#type' => 'link',
            '#title' => $term->name,
            '#href' => $uri,
          );
         }
        break;
    }

    return $result;
}
DOCUMENTATION
DOCUMENTATION

• http://api.drupal.org

• Field Types API

 http://api.drupal.org/api/
 drupal/modules--field--
 field.api.php/group/
 field_types/7
DOCUMENTATION


• Other   core field modules

• list.module, number.module,
 options.module and
 text.module

• modules/fields/modules
DOCUMENTATION



• Examples   for Developers

• http://drupal.org/project/
 examples
THE END
Q&A

More Related Content

What's hot

Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
brockboland
 
Apache Solr Search Mastery
Apache Solr Search MasteryApache Solr Search Mastery
Apache Solr Search Mastery
Acquia
 
Shortcodes In-Depth
Shortcodes In-DepthShortcodes In-Depth
Shortcodes In-Depth
Micah Wood
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
tompunk
 
Make your own wp cli command in 10min
Make your own wp cli command in 10minMake your own wp cli command in 10min
Make your own wp cli command in 10min
Ivelina Dimova
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to ask
Andrea Giuliano
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress sitereferences
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
Bernhard Schussek
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
mussawir20
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
guest48224
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
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óvilesLuis Curo Salvatierra
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012
Rafael Dohms
 
Mastering Custom Post Types - WordCamp Atlanta 2012
Mastering Custom Post Types - WordCamp Atlanta 2012Mastering Custom Post Types - WordCamp Atlanta 2012
Mastering Custom Post Types - WordCamp Atlanta 2012
Mike Schinkel
 
Daily notes
Daily notesDaily notes
Daily notes
meghendra168
 
Custom Post Types and Meta Fields
Custom Post Types and Meta FieldsCustom Post Types and Meta Fields
Custom Post Types and Meta Fields
Liton Arefin
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3
Karsten Dambekalns
 
Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)
Rafael Dohms
 

What's hot (20)

Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 
Apache Solr Search Mastery
Apache Solr Search MasteryApache Solr Search Mastery
Apache Solr Search Mastery
 
Shortcodes In-Depth
Shortcodes In-DepthShortcodes In-Depth
Shortcodes In-Depth
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
Make your own wp cli command in 10min
Make your own wp cli command in 10minMake your own wp cli command in 10min
Make your own wp cli command in 10min
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to ask
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
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
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012
 
Mastering Custom Post Types - WordCamp Atlanta 2012
Mastering Custom Post Types - WordCamp Atlanta 2012Mastering Custom Post Types - WordCamp Atlanta 2012
Mastering Custom Post Types - WordCamp Atlanta 2012
 
Daily notes
Daily notesDaily notes
Daily notes
 
Custom Post Types and Meta Fields
Custom Post Types and Meta FieldsCustom Post Types and Meta Fields
Custom Post Types and Meta Fields
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3
 
Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)
 

Similar to Fields in Core: How to create a custom field

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
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Pavel Makhrinsky
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
Barang CK
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
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
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
D8 Form api
D8 Form apiD8 Form api
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 DatasourceKaz Watanabe
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkJeremy Kendall
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
Michelangelo van Dam
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with Slim
Raven Tools
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkJeremy Kendall
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
Viswanath Polaki
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
Kris Wallsmith
 

Similar to Fields in Core: How to create a custom field (20)

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
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Get on with Field API
Get on with Field APIGet on with Field API
Get on with Field 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?
What's new in the Drupal 7 API?
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
D8 Form api
D8 Form apiD8 Form api
D8 Form api
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Field formatters
Field formattersField formatters
Field formatters
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with Slim
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro framework
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 

Recently uploaded

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 

Recently uploaded (20)

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 

Fields in Core: How to create a custom field

  • 1. FIELDS IN CORE: HOW TO CREATE A CUSTOM FIELD By Ivan Zugec
  • 2. WHO AM I? • Name: Ivan Zugec • Drupal username: Ivan Zugec • Twitter: http://twitter.com/zugec • Blog: http://zugec.com
  • 3. SESSION AGENDA • What’s new in Drupal 7 • Understanding fields • How to create a field • Custom formatters • Documentation • Q&A
  • 4. WHAT’S NEW IN DRUPAL 7
  • 5. WHAT’S NEW IN DRUPAL 7 • InDrupal 6 we used the CCK module to add fields into nodes
  • 6. WHAT’S NEW IN DRUPAL 7 • In Drupal 7 a lot of CCK’s functionality has been moved into core • Not all CCK modules made it into core
  • 7. WHAT’S NEW IN DRUPAL 7 • “Node reference” and “User reference” moved to http:// drupal.org/project/references • “Fieldset” moved to http://drupal.org/project/field_group • “Contentpermission” moved to http://drupal.org/project/ field_permissions
  • 8. WHAT’S NEW IN DRUPAL 7 • Drupal 7 ships with text, options, number and list • File and image field all in core
  • 10. UNDERSTANDING FIELDS • Pieceof functionality attached to an entity (node, taxonomy, etc...) • Example: Date module
  • 11. UNDERSTANDING FIELDS • Fields have 4 major components • Field • Field type • Widget • Formatter
  • 12. UNDERSTANDING FIELDS • Field • field.module, field.info and field.install
  • 13. UNDERSTANDING FIELDS /** * Implements hook_field_schema(). */ function text_field_schema($field) { switch ($field['type']) { case 'text': $columns = array( 'value' => array( 'type' => 'varchar', • Field type 'length' => $field['settings']['max_length'], 'not null' => FALSE, ), ); break; • How the field will be stored case 'text_long': .... in the database break; } $columns += array( 'format' => array( 'type' => 'varchar', 'length' => 255, • Using hook_field_schema ), 'not null' => FALSE, ); return array( 'columns' => $columns, • Using hook_field_info 'indexes' => array( ), 'format' => array('format'), 'foreign keys' => array( 'format' => array( 'table' => 'filter_format', 'columns' => array('format' => 'format'), ), ), );
  • 14. UNDERSTANDING FIELDS • Widget • Form element a user will use to enter in the data
  • 16. UNDERSTANDING FIELDS • Formatter • How to data will be displayed
  • 17. HOW TO CREATE A FIELD
  • 18. HOW TO CREATE A FIELD • Createa custom “Collaborators” field • Module will be called “collabfield” • Unlimited value field with a Name, Role and Link text fields within
  • 19. HOW TO CREATE A FIELD • Createa module called collabfield • Createcollabfield.info, collabfield.install and collabfield.module files
  • 20. HOW TO CREATE A FIELD collabfield.info ; $Id$ name = Collaborator field description = Custom collaborator field. dependencies[] = field_ui core = 7.x
  • 21. HOW TO CREATE A FIELD collabfield.install <?php // $Id$ /** * Implements hook_install(). */ function collabfield_install() { } /** * Implements hook_uninstall(). */ function collabfield_uninstall() { }
  • 22. HOW TO CREATE A FIELD /** collabfield.install * Implementation of hook_field_schema(). */ function collabfield_field_schema($field) { if ($field['type'] == 'collabfield') { $schema['columns']['name'] = array( 'type' => 'varchar', 'length' => '255', 'not null' => FALSE, ); $schema['columns']['role'] = array( 'type' => 'varchar', 'length' => '255', 'not null' => FALSE, ); $schema['columns']['link'] = array( 'type' => 'varchar', 'length' => '255', 'not null' => FALSE, ); $schema['indexes'] = array( 'name' => array('name'), 'role' => array('role'), 'link' => array('link'), ); return $schema; }
  • 23. HOW TO CREATE A FIELD collabfield.module <?php // $Id$ /** * Implementation of hook_field_info(). */ function collabfield_field_info() { return array( 'collabfield' => array( 'label' => t('Collaborator'), 'description' => t('Custom collaborators field.'), 'default_widget' => 'collabfield_collabfield_form', 'default_formatter' => 'collabfield_default', ), ); }
  • 24. HOW TO CREATE A FIELD collabfield.module /** * Implementation of hook_field_is_empty(). */ function collabfield_field_is_empty($item, $field) { if ($field['type'] == 'collabfield') { if (empty($item['name']) && empty($item['role']) && empty($item['link'])) { return TRUE; } } return FALSE; }
  • 25. HOW TO CREATE A FIELD • Create a widget • Use hook_field_widget_info to setup field • Use hook_field_widget_form for the actual form element
  • 26. HOW TO CREATE A FIELD /** * Implements hook_field_widget_info(). */ function collabfield_field_widget_info() { return array( 'collabfield_collabfield_form' => array( 'label' => t('Collabfield form'), 'field types' => array('collabfield'), 'behaviors' => array( 'multiple values' => FIELD_BEHAVIOR_DEFAULT, //Use FIELD_BEHAVIOR_NONE for no default value. 'default value' => FIELD_BEHAVIOR_DEFAULT, ), ), ); }
  • 27. HOW TO CREATE A FIELD /** * Implementation of hook_field_widget_form(). */ function collabfield_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) { $base = $element; if ($instance['widget']['type'] == 'collabfield_collabfield_form') { $widget = $instance['widget']; $settings = $widget['settings']; $element['name'] = array( '#type' => 'textfield', '#title' => t('Name'), '#default_value' => isset($items[$delta]['name']) ? $items[$delta]['name'] : NULL, ); $element['role'] = array( '#type' => 'textfield', '#title' => t('Role'), '#default_value' => isset($items[$delta]['role']) ? $items[$delta]['role'] : NULL, ); $element['link'] = array( '#type' => 'textfield', '#title' => t('Link'), '#default_value' => isset($items[$delta]['link']) ? $items[$delta]['link'] : NULL, '#element_validate' => array('_collabfield_link_validate'), ); } return $element; }
  • 28. HOW TO CREATE A FIELD • To validate an element add #element_validate to the specific element $element['link'] = array( '#type' => 'textfield', '#title' => t('Link'), '#default_value' => isset($items[$delta]['link']) ? $items[$delta]['link'] : NULL, '#element_validate' => array('_collabfield_link_validate'), ); /** * Validation callback for a collabfield link element. */ function _collabfield_link_validate($element, &$form_state, $form) { $value = $element['#value']; if (!empty($value) && !valid_url($value, TRUE)) { form_error($element, t('Invalid URL.')); } }
  • 29. HOW TO CREATE A FIELD • Drupalships with three form element validators in field.module • _element_validate_integer() • _element_validate_integer_positive() • _element_validate_number()
  • 30. HOW TO CREATE A FIELD • Create a formatter • Use hook_field_formatter_info to setup a formatter • Use hook_field_formatter_view for the actual formatter
  • 31. HOW TO CREATE A FIELD /** * Implements hook_field_formatter_info(). */ function collabfield_field_formatter_info() { return array( 'collabfield_default' => array( 'label' => t('Default'), 'field types' => array('collabfield'), ), ); }
  • 32. HOW TO CREATE A FIELD /** * Implements hook_field_formatter_view(). */ function collabfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) { $element = array(); switch ($display['type']) { case 'collabfield_default': foreach ($items as $delta => $item) { $element[$delta]['#markup'] = theme('collabfield_formatter_default', $item); } break; } return $element; }
  • 34. CUSTOM FORMATTERS • Formatter to change default term reference link formatter • Create as custom module • Change URL taxonomy/term/[tid] to whatever/[tid]
  • 35. CUSTOM FORMATTERS /** * Implements hook_field_formatter_info(). */ function termpathfield_field_formatter_info() { return array( 'termpathfield_term_reference_link' => array( 'label' => t('Custom path link'), 'field types' => array('taxonomy_term_reference'), 'settings' => array( 'taxonomy_custom_url' => 'taxonomy/term/[tid]', ), ), ); }
  • 36. CUSTOM FORMATTERS /** * Implements hook_field_formatter_settings_form(). */ function termpathfield_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) { $display = $instance['display'][$view_mode]; $settings = $display['settings']; $form = array(); if ($display['type'] == 'termpathfield_term_reference_link') { $form['taxonomy_custom_url'] = array( '#type' => 'textfield', '#title' => t('Custom term page URL'), '#default_value' => $settings['taxonomy_custom_url'], '#required' => TRUE, ); } return $form; }
  • 38. CUSTOM FORMATTERS /** * Implements hook_field_formatter_settings_summary(). */ function termpathfield_field_formatter_settings_summary($field, $instance, $view_mode) { $display = $instance['display'][$view_mode]; $settings = $display['settings']; $summary = ''; if ($display['type'] == 'termpathfield_term_reference_link') { $summary = $settings['taxonomy_custom_url']; } return $summary; }
  • 40. CUSTOM FORMATTERS /** * Implements hook_field_formatter_view(). */ function termpathfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) { $result = array(); switch ($display['type']) { case 'termpathfield_term_reference_link': foreach ($items as $delta => $item) { $term = taxonomy_term_load($item['tid']); $uri_path = str_replace('[tid]', $term->tid, $display['settings']['taxonomy_custom_url']); $uri = url($uri_path, array('absolute' => TRUE)); $result[$delta] = array( '#type' => 'link', '#title' => $term->name, '#href' => $uri, ); } break; } return $result; }
  • 42. DOCUMENTATION • http://api.drupal.org • Field Types API http://api.drupal.org/api/ drupal/modules--field-- field.api.php/group/ field_types/7
  • 43. DOCUMENTATION • Other core field modules • list.module, number.module, options.module and text.module • modules/fields/modules
  • 44. DOCUMENTATION • Examples for Developers • http://drupal.org/project/ examples
  • 46. Q&A

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n