Створення простого модуля з використанням Field API в Drupal 7

11.04.2011
Creating simple module using Field API in Drupal 7
Автор:

Якщо вас зацікавить ця тема в повному обсязі, Ви можете її побачити на цій сторінці офіційного сайту Drupal.Тут вашій увазі надається приклад реалізації модуля с використанням Field API в Drupal 7.Найпростіший модуль, який може показати нам можливості Field API повинен складатися з 3-ох файлів:

Отож, почнемо.

Спочатку давайте роз'яснимо деякі поняття відносно полів, їх типів, методів форматування.Існують такі поняття як "Тип поля" і "Віджет". До кожного типу поля відноситься віджет або декілька віджетів.

Коли ми вибираємо Display fields, то тут нам будуть пропонувати вказати формат нашого поля. Формат поля може бути як один, так і декілька.

Приступаємо до самого модуля.

Файл text.info (в нашому прикладі всі файли будуть називатися textf) повинен містити такі рядки:

// The name of our module.
name = Text field  
// Description of our module.
description = A Simple Text Field for Drupal 7 
// What section will our module be in.
package = public-action fields   
// Drupal version in which our module will work.
core = 7.x 
// File name with which our module will work.
files[] = textf.module   
// Another file that we need.
files[] = textf.install

Зверніть увагу на рядки:

files[] = textf.module   
files[] = textf.install

В Drupal 7 при створенні будь-якого модуля, завжди бажано в кожному .info файлі вказувати ті файли, з якими працює модуль.

Далі беремось за файл textf.install. Він відповідає в нас за створення місця в БД для нашого поля.

/**
 * Implements hook_field_schema().
 */
function textf_field_schema($field) { 
  return array(     
    // Column.
    'columns' => array(           
      // In column there is a textf field.
      'textf' => array(          
        // Field has text type.
        'type' => 'text',       
       ), 
     ), 
  ); 
}

Щойно ми створили місце в БД, саме в textf буде вміщуватись текст з нашого поля. Але для цього налаштуємо це поле.

Попрацюємо з файлом textf.module.

/**
 * Implements hook_field_info().
 */
function textf_field_info() {  
  // Returning array.
  return array(  
    // Which is called textf.
    'textf' => array(  
      // Name of our type will be 'Te(x/s)t field'.
      'label' => t('Te(x/s)t field'),  
      // Description of our type.
      'description' => t('sample text field'),  
      // Standart widget that will be dispalyed at once.
      // After that we choose field type.
      'default_widget' => 'textf_widget',                        
      // Standart that will be dispayed right after we choose field type.
      'default_formatter' => 'textf_formatter',  
    ), 
  ); 
} 

/**
 * Implements hook_field_widget_info().
 */
function textf_field_widget_info() {  
  // Returning massive.
  return array(   
    // With textf name.
    'textf' => array(  
      // Our widget will be named textf label.
      'label' => t('textf label'),  
      // Our widget will work with a field in DB under the name textf.
      'field types' => array('textf'),  
    ), 
  ); 
} 

/**
 * Implements hook_field_formatter_info().
 */
function textf_field_formatter_info() {  
  // Returning array.
  return array(   
    // Name of our format for code.
    'textf_formatter' => array(  
      // Dispalyed name of format.
      'label' => t('Simple text field formatter'),  
      // Field in DB with which our format will work.
      'field types' => array('textf'),  
    ), 
  ); 
}

Далі візьмемось за присвоювання параметрів віджета. Простіше кажучи - ми створюємо поле для вводу нашого поля.

/**
 * Implements hook_field_widget_form ().
 */
function textf_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Setting switch into parameters that wll work widget types that are in module.
  switch ($instance['widget']['type']) {  
    // If parameter case is 'textf'.
    case 'textf':  
      // Then we assign to textf element an array.
      // With the following values.
      $element['textf'] = array(  
        // Element type 'textfield'.
        '#type' => 'textfield',  
        // Heading given in element settings.
        '#title' => $element['#title'],  
        // Widget description is given in element settings.
        '#description' => $element['#description'], 
        // Our widget will have standart value textfield
        '#default_value' => t('textfield'),  
        // If element is required it will be indicated in settings of the very element.
        '#required' => $element['#required'],  
        // Element location –  
        // If it's indicated, value should be used, if not, value is 0.
        '#weight' => isset($element['#weight']) ? $element['#weight'] : 0, 
        // Line that we'll need for the output,
        '#delta' => $delta,  
      ); 
      break; 
  } 
  return $element;
}

Потім задаємо параметри відображення нашого поля, так званий формат нашого поля.

/**
 * Implements hook_field_formatter_view().
 */
function textf_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) { 
  $element = array(); 
  // Processing format types.
  switch ($display['type']) { 
    case 'textf_formatter':  
      foreach ($items as $delta => $item) {  
        // If we have item then.
        if ($item['textf']) {  
          $formattedText = $item['textf'];  
          // Show text with tags. 
          $element[$delta]['#markup'] = '<h1><b>' . $formattedText .'</b></h1>'; 
        } 
      } 
      break; 
  } 
  return $element; 
}

І останній крок: потрібно показати Field API, що йому робити, якщо тексту немає. Це робиться так:

/**
 * Implements hook_field_is_empty().
 */
function textf_field_is_empty($item, $field) { 
   // If there's nothing in $item['textf'].
   if (empty($item['textf'])) { 
        // Then we return 1, i.e. we say to Drupal that everything is fine).
        return true;  
        // And if it's empty, nothing will be displayed.
   } 
}

Тільки що ми розібрали приклад комплементарного модуля Field API в Drupal 7.

Взагалі, Field API є новацією в Drupal 7. Для реалізації проектів (нескладних за своїм функціоналом) цілком  достатньо вже готових модулів, наприклад, поле для Email або ще щось подібне. Але якщо потрібні поля, яких ще не існує в проекті - згадуємо про Field API.

2 votes, Рейтинг: 3.5

Також по темі

1

Швидкість завантежння сторінки в браузері кінцевого користувача - один із ключових факторів популярності вашого сайту. Користувач може не дочекатися...

2

SSH - мережевий протокол рівня сеансів, з його допомогою виконується віддалене управління операційною системою і тунелювання ТСР-з'єднань (наприклад, для передачі файлів).

...

3

Якщо ви знаєте що таке jQuery чи починаєте його вивчати, то напевне вас зацікавить знання про те, як написати свій jQuery плагін. Зробити це досить просто. Прочитавши цю статтю ви зможете...

4

В Drupal по замовчуванню поставлена перевірка пароля користувача при реєстрації. Для її усунення потрібно виконати наступне:

5
Дуже часто буває потрібно зробити сортування нод по якомусь критерію. Для цього часто використовують Views, Nodequeue, Flag та інші схожі модулі. Але часто буває так, що функціоналу цих модулів...

Subscribe to our blog updates