Snippets

Views:13

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';
    }
}
 


Create an Admin User using Drush

Creates a new user with a specified username and password.
Create an Admin User using Drush
              

/**
* Create a new user with a password.
*/
drush user:create username --mail=user@example.com --password=password;
 


Delete a Record

Deletes a record from a specific table
Delete a Record
              

/**
* Deletes a record from a custom table.
*/
function my_module_delete_data() {
    \Drupal::database()->delete('custom_table')
        ->condition('id', 10, '=')
        ->execute();
}
 


Insert Data into a Table

Inserts a new record into a table
Insert Data into a Table
              

/**
* Inserts a record into a custom table.
*/
function my_module_insert_data() {
    \Drupal::database()->insert('custom_table')
        ->fields([
            'name' => 'Sample Name',
            'status' => 1,
        ])
        ->execute();
}
 


Install and uninstall a module with drush in Drupal

Install/Uninstalls a module from Drupal. When uninstalling, this also removes any associated configuration.
Install and uninstall a module with drush in Drupal
              

/**
* Enable a specific module.
*/
drush en module_name -y;
 

/**
* Uninstall a specific module.
*/
drush pm:uninstall module_name -y;
 


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;
        }
    }
}
 


Simple Select Query

Basic query to fetch results from a specific table
Simple Select Query
              

/**
* Fetches data from a custom table.
*/
function my_module_get_data() {
    $query = \Drupal::database()->select('custom_table', 'ct');
    $query->fields('ct', ['id', 'name', 'status']);

    $result = $query->execute()->fetchAll();

    return $result;
}
 


Update Data in a Table

Updates an existing record in a table
Update Data in a Table
              

/**
* Updates data in a custom table.
*/
function my_module_update_data() {
    \Drupal::database()->update('custom_table')
        ->fields([
            'status' => 0,
        ])
        ->condition('id', 5, '=')
        ->execute();
}
 


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'];
}