View source
<?php
namespace Drupal\webform\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Utility\WebformElementHelper;
use Drupal\webform\WebformInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class WebformVariantViewForm extends FormBase {
protected $operation;
protected $webform;
public function getFormId() {
return 'webform_variant_view_form';
}
public function buildForm(array $form, FormStateInterface $form_state, WebformInterface $webform = NULL, $operation = 'view') {
$this->operation = $operation;
$this->webform = $webform;
switch ($operation) {
case 'view':
$form['#rel'] = 'canonical';
$submit_label = $this
->t('View');
$t_args = [
'@operation' => $this
->t('view'),
];
break;
case 'test':
$form['#rel'] = 'test-form';
$submit_label = $this
->t('Test');
$t_args = [
'@operation' => $this
->t('test'),
];
break;
case 'share':
$form['#rel'] = 'share-embed';
$submit_label = $this
->t('Share');
$t_args = [
'@operation' => $this
->t('share'),
];
break;
default:
throw new NotFoundHttpException();
}
$form['description'] = [
'#type' => 'container',
'text' => [
'#markup' => $this
->t('Select variants and then click submit, which will redirect you to the @operation form.', $t_args),
'#prefix' => '<p>',
'#suffix' => '</p>',
],
];
$element_keys = $webform
->getElementsVariant();
if (isset($element_keys)) {
$form['variants'] = [
'#tree' => TRUE,
];
foreach ($element_keys as $element_key) {
$element = $webform
->getElement($element_key);
$variants = $webform
->getVariants(NULL, TRUE, $element_key);
if (!$variants
->count()) {
continue;
}
$variant_options = [];
foreach ($variants as $variant) {
$variant_options[$variant
->getVariantId()] = $variant
->label();
}
$form['variants'][$element_key] = [
'#type' => 'select',
'#title' => WebformElementHelper::getAdminTitle($element),
'#options' => $variant_options,
'#empty_option' => $this
->t('- None -'),
];
}
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $submit_label,
'#button_type' => 'primary',
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$variants = $form_state
->getValue('variants');
$query = [];
$element_keys = $this->webform
->getElementsVariant();
foreach ($element_keys as $element_key) {
if (empty($variants[$element_key])) {
continue;
}
$variant_id = $variants[$element_key];
$variant_element = $this->webform
->getElement($element_key);
if (empty($variant_element['#prepopulate'])) {
$query += [
'_webform_variant' => [],
];
$query['_webform_variant'][$element_key] = $variant_id;
}
else {
$query[$element_key] = $variant_id;
}
}
$options = [
'query' => $query,
];
$rel = $form['#rel'];
$redirect_url = $this->webform
->toUrl($rel, $options);
$form_state
->setRedirectUrl($redirect_url);
}
}