Field API
Nice example: http://evolvingweb.ca/story/poutine-maker-introduction-field-api-drupal-7-part-1
Providing a field requires:
- Defining a field:
- hook_field_info()
- Tell your field system about the fieldtypes (custom fields). It defines what the default widget en formatter are. We can specify one or more fieldtypes.
- hook_field_info()
- hook_field_schema()
- For each fieldtype we tell what kind of scheme to use.
- This hook must be defined in .install for it to be detected during installation and upgrade.
- hook_field_validate()
- For each fieldtype we can specify a validation rule.
- hook_field_is_empty()
name = Color Picker description = Defines an RGB color picker version = VERSION core = 7.x files[] = colorpicker.module |
<?php /** * @file * Defines a simple color picker field type. */ /*************************************************************** * Field Type API hooks ***************************************************************/ /** * Implement hook_field_info(). */ function colorpicker_field_info() { return array( 'colorpicker_rgb' => array( 'label' => t('Color RGB'), 'description' => t('Stores an RGB color.'), 'default_widget' => 'colorpicker_3text', 'default_formatter' => 'colorpicker_helloworld', ), ); } /** * Implement hook_field_schema(). */ function colorpicker_field_schema($field) { $columns = array( 'rgb' => array('type' => 'varchar', 'length' => 7, 'not null' => FALSE), ); return array('columns' => $columns); } /** * Implement hook_field_validate(). */ function colorpicker_field_validate($obj_type, $object, $field, $instance, $langcode, &$items, &$errors) { foreach($items as $delta => $item) { if(isset($item['rgb'])) { if(! preg_match('@^#[0-9a-f]{6}$@', $item['rgb'])) { $errors[$field['field_name']][$langcode][$delta][] = array( 'error' => 'colorpicker_invalid', 'message' => t('Color must be an HTML spec'), ); } } } } /** * Implement hoo_field_is_empty(). */ function colorpicker_field_is_empty($item, $field) { return empty($item['rgb']); } |