You are here

public function CivicrmOptions::prepare in Webform CiviCRM Integration 8.5

Prepare an element to be rendered within a webform.

Parameters

array $element: An element.

\Drupal\webform\WebformSubmissionInterface $webform_submission: A webform submission. Webform submission is optional since it is not used by composite sub elements.

Overrides OptionsBase::prepare

See also

\Drupal\webform\Element\WebformCompositeBase::processWebformComposite

File

src/Plugin/WebformElement/CivicrmOptions.php, line 159

Class

CivicrmOptions
Provides a 'civicrm_options' element.

Namespace

Drupal\webform_civicrm\Plugin\WebformElement

Code

public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
  \Drupal::service('civicrm')
    ->initialize();
  $as_list = !empty($element['#extra']['aslist']);
  $is_multiple = !empty($element['#extra']['multiple']);
  $use_live_options = !empty($element['#civicrm_live_options']);
  $data = [];
  if ($webform_submission && $webform_submission
    ->getWebform()
    ->getHandlers()
    ->has('webform_civicrm')) {
    $data = $webform_submission
      ->getWebform()
      ->getHandler('webform_civicrm')
      ->getConfiguration()['settings']['data'] ?? [];
  }
  if (empty($element['#options'])) {
    $element['#options'] = $this
      ->getFieldOptions($element, $data);
  }
  if ($use_live_options) {
    $new = $this
      ->getFieldOptions($element, $data);
    $old = $element['#options'];

    // If an item doesn't exist, we add it. If it's changed, we update it.
    // But we don't subtract items that have been removed in civi - this prevents
    // breaking the display of old submissions.
    foreach ($new as $k => $v) {
      if (!isset($old[$k]) || $old[$k] !== $v) {
        $old[$k] = $v;
      }
    }
    $element['#options'] = $new;
  }
  if (!empty($element['#default_option'])) {
    $element['#default_value'] = $element['#default_option'];
  }
  $element['#type'] = 'select';
  if (!$as_list) {
    $element['#type'] = 'radios';

    // A single static radio should be shown as a checkbox
    if ($is_multiple || !$use_live_options && count($element['#options']) === 1) {
      $element['#type'] = 'checkboxes';
      $element['#default_value'] = empty($element['#default_value']) ? [] : (array) $element['#default_value'];
    }
  }
  if ($is_multiple) {
    $element['#multiple'] = TRUE;
  }
  parent::prepare($element, $webform_submission);
}