Sample module in Drupal 8

Here is a sample module in Drupal 8 that meets the following conditions:

  • Check the telephone number format in 10 int
  • uploaded file should be renamed while uploaded appeding date and time stanp
  • displaying a thank you note after submission
<?php

/**
 * Implements hook_form_FORM_ID_alter().
 */
function collect_data_form_form_id_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['telephone_number'] = [
      '#type' => 'tel',
      '#title' => t('Telephone Number'),
      '#required' => TRUE,
      '#maxlength' => 10,
    ];

    $form['file_upload'] = [
      '#type' => 'managed_file',
      '#title' => t('File Upload'),
      '#upload_location' => 'public://',
      '#upload_validators' => [
        'file_validate_extensions' => ['pdf'],
      ],
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#submit' => ['collect_data_submit_handler'],
    ];
  }
}

/**
 * Submit handler for collect_data form.
 */
function collect_data_submit_handler(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $file = $form_state->getValue('file_upload');
  $file = \Drupal\file\Entity\File::load($file[0]);
  $destination = 'public://' . $file->getFilename() . '-' . date('Y-m-d_H-i-s');
  $file->setFileName($destination);
  $file->save();

  drupal_set_message(t('Thank you for submitting the form.'));
}

This code implements a hook that alters a form with the form ID form_id to include a telephone number field, a file upload field, and a submit button. The telephone number field is of type tel and has a maximum length of 10 characters, ensuring that only valid telephone numbers in the specified format can be entered.

The file upload field allows for PDFs to be uploaded and is set to the public file system. The file’s name will be renamed with a timestamp when it is uploaded.

Finally, a submit handler is added to the form that will display a thank you message once the form is successfully submitted.

Please leave your questions or comments below!


Posted

in

by

Tags: