drupal Module development - Drupal 7 Basic custom form for inclusion in either page or block examples.

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Simple form, validation and submission functions to create a "mailing list" feature. This can then be applied to either the basic page or basic block examples.

Assumes you have created a table in the drupal database called 'mailing_list' with the fields first name, last name and email address.

Additional information on the Form API and additional field options: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/

function custom_module_form($form, &$form_state) {
  $form['first_name'] = array (
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#required' => TRUE,
  );
  $form['last_name'] = array (
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#required' => TRUE,
  );
  $form['email'] = array (
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#required' => TRUE,
  );

  return $form;
}

function custom_module_form_validate($form, &$form_state) {
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    form_set_error('email', t('Please provide a valid email address.'));
  }
}

function custom_module_form_submit($form, &$form_state) {
  //Useful function for just getting the submitted form values
  form_state_values_clean($form_state);

  //Save time later by assigning the form values to variables.
  $first_name = $form_state['values']['first_name'];
  $last_name = $form_state['values']['last_name'];
  $email = $form_state['values']['email'];

  //Insert the submitted data to the mailing_list database table.
  db_insert('mailing_list')
    ->fields(array(
      'first name' => $first_name,
      'last name' => $last_name,
      'email' => $email,
    ))
    ->execute();
  //Set a thank you message.
  drupal_set_message('Thank you for subscribing to our mailing list!');

  //drupal_goto() could be used here to redirect to another page or omitted to reload the same page.
  //If used, drupal_goto() must come AFTER drupal_set_message() for the message to be displayed on the new page.
}


Got any drupal Question?