You are here

function fz152_form_alter in FZ152 8

Same name and namespace in other branches
  1. 7 fz152.module \fz152_form_alter()

Implements hook_form_alter().

File

./fz152.module, line 32
Main file for hooks and custom functions.

Code

function fz152_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $config = \Drupal::config('fz152.settings');
  $plugin_service = \Drupal::service('plugin.manager.fz152');
  $active_forms = [];
  foreach ($plugin_service
    ->getDefinitions() as $plugin_id => $plugin) {
    $instance = $plugin_service
      ->createInstance($plugin_id);
    $active_forms = array_merge($active_forms, $instance
      ->getForms());
  }
  if ($config
    ->get('enable')) {
    $pattern_for_forms = '';
    foreach ($active_forms as $current_form) {
      $pattern_for_forms .= $current_form['form_id'] . PHP_EOL;
    }
    $matches = fz152_form_id_matches($form_id, $pattern_for_forms);
    if (!empty($matches)) {
      $matched_form_id = $matches[0];

      // Find checkbox weight by matched form id with available in array.
      // Because we have support for wildcards, this is necessary.
      $checkbox_weight = NULL;
      foreach ($active_forms as $k => $v) {
        $current_form_id = str_replace('*', '.*', $v['form_id']);
        $pattern = "/{$current_form_id}/";
        if (preg_match($pattern, $matched_form_id)) {
          $checkbox_weight = $v['weight'];
          break;
        }
      }

      // Finally we add checkbox.
      $is_checkbox = $config
        ->get('is_checkbox');
      $checkbox_form = [
        '#type' => 'checkbox',
        '#required' => TRUE,
        '#title' => $config
          ->get('checkbox_title'),
        // HTML5 support.
        '#attributes' => [
          'required' => 'required',
        ],
        '#weight' => $checkbox_weight,
        '#element_validate' => [
          'fz152_agreement_element_validate',
        ],
      ];
      $text_form = [
        '#name' => 'fz152-agreement',
        '#type' => 'item',
        '#markup' => $config
          ->get('checkbox_title'),
        '#weight' => $checkbox_weight,
      ];
      if (isset($form['elements']['actions']['#type']) && $form['elements']['actions']['#type'] == 'webform_actions') {
        $new = array();
        foreach ($form['elements'] as $f => $value) {
          if ($f === 'actions') {
            $new['fz152_agreement'] = $is_checkbox ? $checkbox_form : $text_form;
          }
          $new[$f] = $value;
          $form['elements'] = $new;
        }
      }
      else {
        $form['actions']['#weight'] = 110;
        $form['fz152_agreement'] = $is_checkbox ? $checkbox_form : $text_form;
      }
    }
  }
}