You are here

public function Webform::applyVariants in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Entity/Webform.php \Drupal\webform\Entity\Webform::applyVariants()

Apply webform variants based on a webform submission or parameter.

Parameters

\Drupal\webform\WebformSubmissionInterface $webform_submission: A webform submission.

array $variants: An associative array of variant element keys and variant ids.

bool $force: Apply disabled variants. Defaults to FALSE.

Throws

\Exception Throws exception if submission was not created using this webform.

Overrides WebformInterface::applyVariants

File

src/Entity/Webform.php, line 2927

Class

Webform
Defines the webform entity.

Namespace

Drupal\webform\Entity

Code

public function applyVariants(WebformSubmissionInterface $webform_submission = NULL, array $variants = [], $force = FALSE) {

  // Get variants from webform submission.
  if ($webform_submission) {

    // Make sure webform submission is associated with this webform.
    if ($webform_submission
      ->getWebform()
      ->id() !== $this
      ->id()) {
      $t_args = [
        '@sid' => $webform_submission
          ->id(),
        '@webform_id' => $this
          ->id(),
      ];
      throw new \Exception($this
        ->t('Variants can not be applied because the #@sid submission was not created using @webform_id', $t_args));
    }
    $variants += $this
      ->getVariantsData($webform_submission);
  }

  // Skip if there are no variants that need to be applied.
  if (empty($variants)) {
    return;
  }

  // Ensure that translated webform elements are set and can be altered
  // by a variant.
  $this
    ->initElementsTranslation(TRUE);

  // Apply variants.
  $is_applied = FALSE;
  $variant_element_keys = $this
    ->getElementsVariant();
  foreach ($variant_element_keys as $variant_element_key) {
    if (!empty($variants[$variant_element_key])) {
      $instance_id = $variants[$variant_element_key];
      if ($this
        ->applyVariant($variant_element_key, $instance_id, $force)) {
        $is_applied = TRUE;
      }
    }
  }
  if ($is_applied) {
    $this
      ->setOverride();
  }
}