API de Formularios

Categoría: API de Formularios

Alteración de títulos y atributos básicos de formularios

Modifica el título del formulario y añada atributos personalizados al formulario.
Alteración de títulos y atributos básicos de formularios
              

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


Añadir un botón de submit personalizado

Añade un botón de envío personalizado con atributos específicos y un gestor de envío personalizado.
Añadir un botón de submit personalizado
              

/**
* 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.

}


Añadir un campo personalizado

Añadir nuevos campos personalizados a un formulario existente.
Añadir un campo personalizado
              

/**
* 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.'),
        ];
    }
}
 


Añadir validación personalizada de formularios

Añadir validación personalizada de formularios
Añadir validación personalizada de formularios
              

/**
* 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. 
}


Modificación de campos existentes

Modifique las propiedades de los campos de formulario existentes, como los títulos y los valores por defecto.
Modificación de campos existentes
              

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


Uso de #states para mostrar/ocultar elementos del formulario

Cómo utilizar la propiedad #states para mostrar u ocultar elementos de formulario en función del valor de otro elemento de formulario.
Uso de #states para mostrar/ocultar elementos del formulario
              

/**
* 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,
                    ],
                ],
            ],
        ];
    }
}
 


Uso de AJAX en Drupal Forms

Cómo utilizar AJAX en un formulario de Drupal para actualizar dinámicamente los elementos del formulario sin recargar la página.
Uso de AJAX en 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'];
}