You are here

public function WebformSame::alterForm in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Plugin/WebformElement/WebformSame.php \Drupal\webform\Plugin\WebformElement\WebformSame::alterForm()

Alter an element's associated form.

Parameters

array $element: An element.

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides WebformElementBase::alterForm

File

src/Plugin/WebformElement/WebformSame.php, line 128

Class

WebformSame
Provides a 'webform_same' element.

Namespace

Drupal\webform\Plugin\WebformElement

Code

public function alterForm(array &$element, array &$form, FormStateInterface $form_state) {
  if (!isset($element['#source']) || !isset($element['#destination'])) {
    return;
  }

  // Get source element.
  $source = $element['#source'];
  $source_element = WebformElementHelper::getElement($form, $source);
  if (!$source_element) {
    return;
  }

  // Get destination element.
  $destination = $element['#destination'];
  $destination_element =& WebformElementHelper::getElement($form, $destination);
  if (!$destination_element) {
    return;
  }

  // Add #states to destination element.
  $selector = ':input[name="' . $element['#webform_key'] . '"]';
  $state = !empty($element['#destination_state']) ? $element['#destination_state'] : 'visible';
  $destination_element['#states'][$state][$selector] = [
    'checked' => FALSE,
  ];
  $destination_element['#states_clear'] = FALSE;

  // Track webform same elements and add validation callback used
  // to sync source to destination.
  $form += [
    '#webform_same' => [],
  ];
  $form['#webform_same'][$element['#webform_key']] = [
    'source' => $source,
    'destination' => $destination,
  ];
  $form['#validate'][] = [
    get_called_class(),
    'validateForm',
  ];
}