Drupal 7 create custom form module with system variables

Categorías: 

Etiquetas: 

Objective

Create a custom module with a form to set/get custom system variables from Drupal. We're going to add custom permissions to access this new page. Bonus: add simple page to count every node for each content type.

Summary

  • Step 1: create custom module
  • Step 2: call hook_menu and hook_permissions
  • Step 3: create custom callbacks for new menus
  • Step 4: create a Drupal form by code. Form, validate and submit
  • Step 5: bonus, send mail after submit

Step 1: create custom module

  • Create '.module' and '.info' files inside your Drupal installation. Can be in 'drupal/sites/all/modules/configuration_module' or 'drupal/sites/default/modules/configuration_module'

File: configuration_module.info

;$Id$
name = Configuration module
description = Example module for a form with custom system variables
package = Example modules
core = 7.x
files[] = configuration_module.module
;dependencies[] = autoload
;php = 5.3
version = "7.x-1.0"

Step 2: call hook_menu and hook_permissions

File: configuration_module.module

/**
 * hook_menu
 */
function configuration_module_menu()
{
    $items = array();
 
    $items['configuration_module/variables'] = array(
        'title' => t('Configuration module configuration'),
        'description' => t('Configuration module variables page'),
        'page callback' => 'configuration_module_callback_variables_form',
        'access arguments' => array('access configuration_module configuration'),
    );
 
    $items['configuration_module/counter'] = array(
        'title' => t('Configuration module counter'),
        'description' => t('Configuration module counter'),
        'page callback' => 'configuration_module_callback_counter',
        'access arguments' => array('access configuration_module counter'),
    );
 
    return $items;
}
 
/**
 * Implements hook_permission() to provide a demonstration access string.
 */
function configuration_module_variables_permission()
{
    return array(
        'access configuration_module configuration' => array(
            'title' => t('Access Configuration module configuration'),
            'description' => t('Access Configuration module  parameters configuration.'),
        ),
        'access configuration_module count' => array(
            'title' => t('Access Configuration module count'),
            'description' => t('Access Configuration module  count list.'),
        ),
    );
}

Step 3: create custom callbacks for new menus

/**
 * Print table with counter for every content type
 * @return string
 */
function configuration_module_callback_counter()
{
    // query for count every content type, group by type
    $query = db_select('node', 'n');
    $query->condition('n.status', 1)
            ->fields('n', array('type', 'nid'))
            ->groupBy('type');
    $query->addExpression('COUNT(n.nid)', 'count');
    $query->orderBy('count', 'DESC');
    $results = $query->execute();
 
    if ($results) {
        // prepare table header and rows
        $header = array(
            'content' => array('data' => t('Content')),
            'quantity' => array('data' => t('Quantity'))
        );
        $rows = array();
        foreach ($results as $key => $value) {
            $rows[] = array(strtoupper($value->type), $value->count);
        }
        $attributes = array('width' => '100%');
 
        $table = array(
            'header' => $header,
            'rows' => $rows,
            'attributes' => $attributes,
            'sticky' => FALSE
        );
        return theme_table($table);
    }
}
 
/**
 * Callback variables form
 * @return string
 */
function configuration_module_callback_variables_form()
{
    $obj = drupal_get_form('configuration_module_variables_form');
    return drupal_render($obj);
}

Step 4: create a Drupal form by code. Form, validate and submit

/**
 * Generate Drupal form with hook_form
 */
function configuration_module_variables_form($form, &$form_state)
{
    // use Drupal variable_get 
    $variable_one = variable_get('variable_one');
    $variable_two = variable_get('variable_two');
 
    $form['variable_one'] = array(
        '#type' => 'textfield',
        '#title' => t('Variable one'),
        '#size' => 2,
        '#default_value' => $variable_one,
        '#required' => TRUE,
    );
 
    $form['variable_two'] = array(
        '#type' => 'textfield',
        '#title' => t('Variable two'),
        '#size' => 2,
        '#default_value' => $variable_two,
        '#required' => TRUE,
    );
 
    $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
 
    return $form;
}
 
/**
 * Validate hook before submit with hook form_validate
 */
function configuration_module_variables_form_validate($form, &$form_state)
{
    if (isset($form_state['values']['variable_one']) 
            && !is_numeric($form_state['values']['variable_one'])) {
        form_set_error('variable_one', t('The value must be numeric.'));
    }
 
    if (isset($form_state['values']['variable_two']) 
            && !is_numeric($form_state['values']['variable_two'])) {
        form_set_error('variable_two', t('The value must be numeric.'));
    }
}
 
/**
 * Save form data with hook form_submit
 */
function configuration_module_variables_form_submit($form, &$form_state)
{
    if (isset($form_state['values']['variable_one'])) {
        variable_set('variable_one', $form_state['values']['variable_one']);
    }
 
    if (isset($form_state['values']['variable_two'])) {
        variable_set('variable_two', $form_state['values']['variable_two']);
    }
 
    if (custom_function_send_mail($form, $form_state) {
        drupal_set_message(t('Data saved.'));         
    } else {
        drupal_set_message(t('Error sending email.'));         
    }
}

Step 5: bonus, send mail after submit

/**
 * Send mail with Drupal
 * @return boolean
 */
function custom_function_send_mail($form, &$form_state)
{
    global $base_url;
 
    // Form data
    $params['variable_one'] = $form_state['input']['variable_one'];
    $params['variable_two'] = $form_state['input']['variable_two'];
 
    $from = 'example@mail.com';
    $to = variable_get('site_mail', ini_get('sendmail_from'));
 
    // Send email
    $message = drupal_mail(
        'configuration_module',
        'configuration_module',
        $to,
        'es',
        $params,
        $from
    );
 
    if ($message['result']) {
        watchdog('configuration_module', t('Email sent to %recipient'), array('%recipient' => $to));
        return true;
    } else {
        return false;
    }
}
 
/**
 * hook_mail
 */
function configuration_module_mail($key, &$message, $params)
{
    $message['subject'] = t('Configuration module example mail');
    $message['body'][] = t("Request data");
    $message['body'][] = t("Variable one: @variable_one", array('@variable_one' => $params['variable_one']));
    $message['body'][] = t("Variable two: @variable_two", array('@variable_two' => $params['variable_two']));
}