Form

Views:7

Adding a Custom Field

Add new custom fields to an existing form.
Adding a Custom Field
              

/**
* Implements hook_form_alter().
*/
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    // Lets modify the registration form.
    if ($form_id == 'user_register_form') {
        // Add a new custom text field.
        $form['new_text_field'] = [
            '#type' => 'textfield',
            '#title' => t('Custom Field'),
            '#description' => t('This is a custom field added via form alter.'),
        ];
    }
}
 


Adding a Custom Submit Button

Add a custom submit button with specific attributes and custom submit handler.
Adding a Custom Submit Button
              

/**
* Implements hook_form_alter() to add a custom submit button.
*/
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'user_register_form') {
        // Add a custom submit button.
        $form['actions']['custom_submit'] = [
            '#type' => 'submit',
            '#value' => t('Custom Register'),
            '#attributes' => [
                'class' => ['custom-submit-button'],
            ],
            '#submit' => ['my_module_custom_submit_handler'],
        ];
    }
}

function my_module_custom_submit_handler(&$form, $form_state, $form_id) { 

// Custom submit code.

}


Adding Custom Form Validation

Add custom validation to a form.
Adding Custom Form Validation
              

/**
* Implements hook_form_alter() to add custom validation.
*/
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'user_register_form') {
        // Add custom validation callback.
        $form['#validate'][] = 'my_module_custom_validate';
    }
}

// Now the validation function should be implemented.
function my_module_custom_validate(&$form, FormStateInterface $form_state, $form_id) {
 // Validation code. 
}


Basic Form Title and Attributes Alteration

Modify the form title and add custom attributes to the form.
Basic Form Title and Attributes Alteration
              

/**
* Implements hook_form_alter().
*/
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    // Check if the form ID matches.
    if ($form_id == 'user_register_form') {
        // Change form title.
        $form['#title'] = t('Custom User Registration');

        // Modify form attributes.
        $form['#attributes']['class'][] = 'custom-form-class';
        $form['#attributes']['id'] = 'custom_form_id';
    }
}
 


Modifying Existing Fields

Alter properties of existing form fields, such as titles and default values.
Modifying Existing Fields
              

/**
* Implements hook_form_alter() to modify existing form fields.
*/
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'user_register_form') {
        if (isset($form['mail'])) {
            // Change the title of the 'mail' field.
            $form['mail']['#title'] = t('Custom Email Address');

            // Change the value of the 'mail' field.
            $form['mail']['#value'] = test@example.com;
        }
    }
}
 


Using #states to Show/Hide Form Elements Conditionally

How to use the #states property to show or hide form elements based on the value of another form element.
Using #states to Show/Hide Form Elements Conditionally
              

/**
* Implements hook_form_alter() to add conditional states.
*/
function my_module_form_alter($form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'custom_form_id') {
        // Add a checkbox to control the visibility of another field.
        $form['show_additional_info'] = [
            '#type' => 'checkbox',
            '#title' => t('Show additional information'),
        ];

        // Add a textfield that will only be shown when the checkbox is checked.
        $form['additional_info'] = [
            '#type' => 'textfield',
            '#title' => t('Additional Information'),
            '#states' => [
                'visible' => [
                    ':input[name="show_additional_info"]' => [
                        'checked' => TRUE,
                    ],
                ],
            ],
        ];
    }
}
 


Using AJAX in Drupal Forms

How to use AJAX in a Drupal form to dynamically update form elements without a page reload.
Using AJAX in Drupal Forms
              

/**
* Implements hook_form_alter() to add AJAX functionality.
*/
function my_module_form_alter($form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'custom_form_id') {
        // Add a select element with AJAX properties.
        $form['select_field'] = [
            '#type' => 'select',
            '#title' => t('Choose an option'),
            '#options' => [
                'option_1' => 'Option 1',
                'option_2' => 'Option 2',
            ],
            '#ajax' => [
                'callback' => 'my_module_ajax_callback',
                'wrapper' => 'ajax-wrapper',
            ],
        ];

        // Add a container to be updated via AJAX.
        $form['ajax_container'] = [
            '#type' => 'container',
            '#attributes' => [
                'id' => 'ajax-wrapper',
            ],
        '#markup' => t('Select an option to update this content.'),
        ];
    }
}
 

/**
* AJAX callback function.
*/
function my_module_ajax_callback(array $form, FormStateInterface $form_state) {
    // Update the content of the AJAX container based on the selected value.
    $selected_value = $form_state->getValue('select_field');
    if ($selected_value == 'option_1') {
        $form['ajax_container']['#markup'] = t('You selected Option 1.');
    } else if ($selected_value == 'option_2') {
        $form['ajax_container']['#markup'] = t('You selected Option 2.');
    }

    // Return the updated container.
    return $form['ajax_container'];
}