FORM api

Understanding FORM API

FORM API is an essential part of Drupal that helps developers build and handle forms in their modules. It is a powerful tool that allows you to create, validate, and process forms with ease while following Drupal's security best practices.

Creating a Form using FORM API

To create a form using FORM API, we need to define an array that describes the form and its elements. This array is then passed to the drupal_get_form function, which returns a renderable array that can be used to output the form.


/**
 * Implements hook_form().
 */
function my_module_my_form($form, &$form_state) {
  $form = array();
  
  // Add a textfield element to the form.
  $form['my_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('My Textfield'),
    '#description' => t('Enter some text.'),
    '#required' => TRUE,
  );
  
  // Add a submit button element to the form.
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  
  return $form;
}

// Render the form using drupal_get_form().
$form = drupal_get_form('my_module_my_form');
print render($form);

Validating Form Data

To validate user input in a Drupal form, we can define a validation function that checks the values of the form elements. The validation function is called after the user submits the form but before the data is processed. If any fields fail validation, an error message is displayed to the user.


/**
 * Implements hook_form_validate().
 */
function my_module_my_form_validate($form, &$form_state) {
  // Check if the textfield contains only letters.
  if (!ctype_alpha($form_state['values']['my_textfield'])) {
    form_set_error('my_textfield', t('The textfield should contain only letters.'));
  }
}

Processing Form Data

To process the data entered in a Drupal form, we can define a submission function that performs the necessary actions. The submission function is called after the form has been validated and the data is ready for processing.


/**
 * Implements hook_form_submit().
 */
function my_module_my_form_submit($form, &$form_state) {
  // Do something with the submitted data.
  $text = $form_state['values']['my_textfield'];
  
  // Display a message to the user.
  drupal_set_message(t('You entered: @text', array('@text' => $text)));
}

Conclusion

FORM API is a powerful tool that simplifies the process of creating and processing forms in Drupal. With its extensive documentation and examples, it's easy for developers to get started with FORM API and build robust, secure forms in their Drupal projects.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe