This Drupal 8 code snippet provided is a hook implementation that alters a specific form in a custom module named myModule.

Here's a breakdown of what the code does:

1. Function Hook: The function `myModule_form_alter()` is designed to modify forms and is part of the Drupal form API. It's invoked for every form on the site, allowing custom alterations based on the form ID.

2. Target Form: The form alteration targets the form with the ID `commerce_billing_schedule_edit_form`.

3. Configuration Loading: It retrieves configuration settings from a custom configuration object named `myModule.subscription`.

4. Element Reordering: The `help` element within the `dunning` form section is adjusted to have a `#weight` of -10, which changes its order for display purposes.

5. New Checkbox Field: A new checkbox, `cancel_subscription`, is added to the `dunning` section. Its purpose is to allow the user to choose whether to cancel a subscription immediately if a payment fails. It includes a title, description, and default value sourced from the configuration.

6. Dynamic States: The `num_retries` and `retry[0]` elements are given states that disable them when the `cancel_subscription` checkbox is checked, reflecting dependencies within the form.

7. Submit Handler: The form's submit button is appended with an additional submit handler function, `myModule_form_submit_handler`, which will execute custom logic when the form is submitted.

CodeLet

<?php

function myModule_form_alter(&$form, \Drupal\core\Form\FormStateInterface $form_state, $form_id) {

 if ($form_id == 'commerce_billing_schedule_edit_form') {
   $config = \Drupal::config('myModule.subscription');
   $form['dunning']['help']['#weight'] = -10;
   $form['dunning']['cancel_subscription'] = [
     '#type' => 'checkbox',
     '#title' => "Cancel subscription upon payment failure",
     '#description' => "The subscription of the user will be cancelled immediately if the payment fails. Checking this option will override following options.",
     '#default_value' =>  $config->get('dunning.cancel_subscription'),
     '#weight' => -9,
   ];

   $form['dunning']['num_retries']['#states'] = [
     'disabled' => [
       ':input[name="dunning[cancel_subscription]"]' => ['checked' => TRUE],
     ],
   ];
   $form['dunning']['retry'][0]['#states'] = [
     'disabled' => [
       ':input[name="dunning[cancel_subscription]"]' => ['checked' => TRUE],
     ],
   ];
   $form['actions']['submit']['#submit'][] = 'myModule_form_submit_handler';
 }
}

?>

DrupalD
Enroll to Drupal 10 Training