Tuesday 12 March 2019

Alter Form in Drupal 8

Alter form in Drupal 8


  1. To alter form in Drupal 7 & Drupal 8, use hook_form_alter(). 
  2. Now add a new field "Status" to company add form created in Custom Form
  3. To implement hooks in Drupal 8, we need to create .module file.
In this case file name is: firstcustommodule.module 

<?php

/**
 * @file
 * Contains firstcustommodule hooks
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter()
 */
function firstcustommodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'company_add_form') {
    $form['company_status'] = [
  '#type' => 'radios',
  '#title' => t('Company Status'),
  '#default_value' => '',
  '#options' => [
    t('Enable'),
    t('Disable'),
  ],
  '#weight' => 0
];

$form['#submit'][] = 'firstcustommodule_form_alter_custom_submit';
  }
  return $form;
}
Now save file and clear cache. Then see the form which is altered. It will having the field which is added.


Field "Company Status" is new field and added from hook_form_alter().














  • Now to save this new field value, add form_submit method in the form alter. 
  • Line: "$form['#submit'][]" this will add a new submit method in the array of submit methods.
  • //To submit this field value, you need to update table structure with a new field "company_status" Now new field in the already exist table can be added with the help of hook_update_N() in .install file.
  • To add a new field in already existing table please see Add new field in existing custom table.
function which is mentioned in "#submit".
function firstcustommodule_form_alter_custom_submit($form, FormStateInterface $form_state) {
  // To save company information in custom table.
  // Use of database service.
  $database = \Drupal::database();
  // Insert query.
  $insert = $database->insert('company_information')
    ->fields(
      [
        'status' => $form_state->getValue('company_status')
      ]
    )->execute();
if ($insert) {
  drupal_set_message(t('Company information has been saved successfully from form_alter.'));
}
}

Above code will save "status" field value.

Issue: When I have created custom form and now I am altering this custom form and adding new field in the custom form. Now on submission of form, How new field value will be saved in the custom table. (Only do with submit method on form alter).



No comments:

Post a Comment