Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
54
Добавлен:
14.03.2016
Размер:
12.64 Mб
Скачать

CHAPTER 2 WRITING A MODULE

Validating User-Submitted Settings

If system_settings_form() is taking care of saving the form values for us, how can we check whether the value entered in the “Annotations per node” field is actually a number? We just need to add the check to see whether the value is numeric to a validation function (annotate_admin_settings_

validate($form, $form_state)) in sites/all/modules/custom/annotate/annotate.admin.inc and use it to set an error if we find anything wrong.

/**

* Validate annotation settings submission. */

function annotate_admin_settings_validate($form, &$form_state) { $limit = $form_state['values']['annotate_limit_per_node'];

if (!is_numeric($limit)) {

form_set_error('annotate_limit_per_node', t('Please enter number.'));

}

}

Now when Drupal processes the form, it will call back to annotate_admin_settings_validate() for validation. If we determine that a bad value has been entered, we set an error against the field where the error occurred, and this is reflected on the screen in a warning message and by highlighting the field containing the error.

How did Drupal know to call our function? We named it in a special way, using the name of the form definition function (annotate_admin_settings) plus _validate. For a full explanation of how Drupal determines which form validation function to call, see Chapter 11.

Storing Settings

In the preceding example, changing the settings and clicking the “Save configuration” button works. The sections that follow describe how this happens.

Using Drupal’s variables Table

Let’s look at the “Annotations per node” field first. Its #default_value key is set to variable_get('annotate_limit_per_node', 1)

Drupal has a variables table in the database, and key/value pairs can be stored using variable_set($key, $value) and retrieved using variable_get($key, $default). So we’re really saying, “Set the default value of the ‘Annotations per node’ field to the value stored in the variables database table for the variable annotate_limit_per_node, but if no value can be found, use the value 1.”

Caution In order for the settings to be stored and retrieved in the variables table without namespace collisions, always give your form element and your variable key the same name (e.g., annotate_limit_per_node in the preceding example). Create the form element/variable key name from your module name plus a descriptive name, and use that name for both your form element and variable key.

The “Annotations will be deleted” field is a little more complex, since it’s a radio button field. The #options for this field are the following:

29

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]