WebformDevelEntityFormApiTestForm.php in Webform 6.x
File
modules/webform_devel/src/Form/WebformDevelEntityFormApiTestForm.php
View source
<?php
namespace Drupal\webform_devel\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Form\WebformDialogFormTrait;
use Drupal\webform\Utility\WebformFormHelper;
use Drupal\webform\Utility\WebformYaml;
class WebformDevelEntityFormApiTestForm extends WebformDevelEntityFormApiBaseForm {
use WebformDialogFormTrait;
public function buildForm(array $form, FormStateInterface $form_state) {
$webform = $this
->getEntity();
$elements = $webform
->getElementsDecoded();
$this
->cleanupElements($elements);
$this
->setDefaultValues($elements);
$this->elementManager
->processElements($elements);
$elements = $this->tokenManager
->replace($elements);
$form += $elements;
$form['actions'] = [
'#type' => 'actions',
'#tree' => TRUE,
'submit' => [
'#type' => 'submit',
'#value' => $this
->t('Test'),
'#button_type' => 'primary',
],
];
$form['#attached']['library'][] = 'webform/webform.form';
$form['#attributes']['class'][] = 'js-webform-autofocus';
$form['#attached']['library'][] = 'webform/webform.form.auto_focus';
$form['#attributes']['class'][] = 'js-webform-unsaved';
$form['#attached']['library'][] = 'webform/webform.form.unsaved';
$form['#attached']['library'][] = 'webform/webform.element.details.save';
$form['#attributes']['class'][] = 'js-webform-details-toggle';
$form['#attributes']['class'][] = 'webform-details-toggle';
$form['#attached']['library'][] = 'webform/webform.element.details.toggle';
return $this
->buildDialogConfirmForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($this
->isDialog()) {
$form_state
->setRebuild();
}
$values = $form_state
->getValues();
unset($values['form_build_id'], $values['form_token'], $values['form_id'], $values['op'], $values['actions']);
$build = [
'#markup' => 'Submitted values are:<pre>' . WebformYaml::encode($values) . '</pre>',
];
$this
->messenger()
->addWarning($this->renderer
->renderPlain($build));
}
protected function setDefaultValues(array &$elements) {
$webform = $this
->getEntity();
$data = $this->generate
->getData($webform);
$flattened_elements =& WebformFormHelper::flattenElements($elements);
foreach ($flattened_elements as $element_key => &$element) {
if (isset($data[$element_key])) {
$element['#default_value'] = $data[$element_key];
}
}
}
}