包含在頁面或塊示例中的基本自定義表單

簡單的表單,驗證和提交功能,以建立郵件列表功能。然後,這可以應用於基本頁面或基本塊示例。

假設你在 drupal 資料庫中建立了一個名為’mailing_list’的表,其中包含欄位的名字,姓氏和電子郵件地址。

有關 Form API 和其他欄位選項的其他資訊: 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.
}