07. Настройки



О чём речь: создание страницы настроек модуля.
Используемый hook: hook_menu.


Теперь мы знаем, что у нас рабочий модуль и мы попробуем его улучшить. Давайте добавим нашему модулю страницу настроек, на которой можно было бы выбрать дату для которой нужно показывать документы.

Создание функции настройки

Мы хотим иметь возможность определять какое количество ссылок нужно выводить в блоке, таким образом, давайте сделаем форму в которой администратор сможет установить это значение. Это будет реализовано в нашей функции onthisdate_admin. Отметьте, что admin — это не hook и мы можем использовать его в коде для чего угодно.

<?php
function onthisdate_admin() {

 
$form['onthisdate_maxdisp'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Maximum number of links'),
   
'#default_value' => variable_get('onthisdate_maxdisp', 3),
   
'#size' => 2,
   
'#maxlength' => 2,
   
'#description' => t("The maximum number of links to display in the block."),
   
'#required' => TRUE,
  );

  return
system_settings_form($form);
}
?>

Эта функция использует несколько мощных возможностей Друпала. Нам не нужно беспокоиться о создании текстовых полей путём HTML, Друпал сделает это за нас. Мы использовали функцию variable_get для возвращения значений переменной onthisdate_maxdisp и определили значение по умолчанию равное 3. Мы также использовали массив (который назван нами $form) для создания формы, которая содержит текстовое поле размером 2 знака (#size) и указав максимальную его длину также в 2 знака (#maxlength). Ещё мы использовали функцию t() при создании описания поля. Эта функция нужна для локализации системы и позволит перевести описание на любой язык. Ну а функция system_settings_form() позволит добавить к форме кнопки.

Вы можете обратиться к Forms API Reference и Drupal Forms API Quickstart Guide для подробной информации о том, как вы можете использовать Drupal Form API.

Когда вы сохраняете настройки любого модуля, переменная (в нашем случае это onthisdate_maxdisp) сохраняется в таблице variables. Таким образом, вы можете вернуть её значение функцией variable_get('variable_name', default_value).

Of course, we'll need to use the configuration value in our SQL SELECT, so we'll need to adjust our query statement in the onthisdate_block function. One way to do this is with a LIMIT value in our query:

<?php
  $limitnum
= variable_get('onthisdate_maxdisp', 3);
 
$query = "SELECT nid, title, created FROM " .
          
"{node} WHERE created >= '" . $start_time .
          
"' AND created <= '". $end_time . "' LIMIT " . $limitnum;
?>

However, this method may or may not translate across databases (really). Better to use one of Drupal's select methods. In this case, let's leave the original query the same, and call db_query_range:

<?php
  $limitnum
= variable_get("onthisdate_maxdisp", 3);

 
$query = "SELECT nid, title, created FROM " .
          
"{node} WHERE created >= %d " .
          
"AND created <= %d";

 
$queryResult = db_query_range($query, $start_time, $end_time, 0, $limitnum);
?>

Add the page to hook_menu

Once you have created the function with your settings, the page is added with a callback to the function which you specify in hook_menu. In hook_menu we will return an array which describes to Drupal which URL path to use, the title to display, the function to use and the permissions required.

We would like only administrators to be able to access this page, so we'll place the permissions check for the module here in hook_menu so that Drupal can itself check the appropriate permission. To minimize the number of permissions an administrator has to deal with, we're going to use the global administration permission for administrating our module instead of creating a new custom permission.

<?php
function onthisdate_menu() {

 
$items = array();

 
$items['admin/settings/onthisdate'] = array(
   
'title' => 'On this date module settings',
   
'description' => 'Description of your On this date settings control',
   
'page callback' => 'drupal_get_form',
   
'page arguments' => array('onthisdate_admin'),
   
'access arguments' => array('access administration pages'),
   
'type' => MENU_NORMAL_ITEM,
   );

  return
$items;
}
?>

You can test the settings page by editing the number of links displayed and noticing the block content adjusts accordingly. Navigate to the settings page: admin/settings/onthisdate or Administer » Site configuration » On this date. If the page doesn't exist, you may have to disable and enable the module for the system to register the new settings page. Adjust the number of links and save the configuration. Notice the number of links in the block adjusts accordingly.

Validate the user input

Although we arn't required to validate the user input, it is nice need to validate values. We can do this by writing a onthisdate_admin_validate function that would check whether the value the user entered is a number greater than 0. Drupal will see that we have a _validate function, and then check the values against it.

<?php
function onthisdate_admin_validate($form_id, $form_values) {
 
$maxdisp = $form_values['onthisdate_maxdisp'];
  if (!
is_numeric($maxdisp)) {
   
form_set_error('onthisdate_maxdisp', t('You must select a number for the maximum number of links.'));
  }
  else if (
$maxdisp <= 0) {
   
form_set_error('onthisdate_maxdisp', t('Maximum number of links must be positive.'));
  }
}
?>

Now if you try to enter something that it doesn't like (a word, or a negative number), it will tell you to enter a correct value.

Смотрите также

Comments

В блоке про валидацию (проверку) введенных пользователем данных третья строчка должна выглядеть следующим образом:

$maxdisp = $form_values['values']['onthisdate_maxdisp'];

Проверено на Drupal 6.5.

Post new comment

Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.