View source
<?php
namespace Drupal\webform_invitation\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\webform\WebformInterface;
use Drupal\Core\Messenger\MessengerTrait;
class WebformInvitationForm extends FormBase {
use MessengerTrait;
public function getFormId() {
return 'webform_invitation_form';
}
public function buildForm(array $form, FormStateInterface $form_state, WebformInterface $webform = NULL) {
$elements = $webform
->getElementsDecodedAndFlattened();
$enabled = isset($elements['webform_invitation_code']);
$form['webform_invitation'] = [
'#type' => 'details',
'#title' => $this
->t('Webform Invitation'),
'#open' => TRUE,
];
$form['webform_invitation']['enable'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Enable invitations for this webform'),
'#default_value' => $enabled,
'#description' => $this
->t('If checked, invitations will be enabled for this webform.'),
];
$form['webform'] = [
'#type' => 'value',
'#value' => $webform,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Save'),
'#button_type' => 'primary',
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$webform = $form_state
->getValue('webform');
$enable = boolval($form_state
->getValue('enable'));
$elements = $webform
->getElementsDecodedAndFlattened();
$enabled = isset($elements['webform_invitation_code']);
if ($enable) {
if (!$enabled) {
$element = [
'webform_invitation_code' => [
'#type' => 'textfield',
'#title' => $this
->t('Invitation Code')
->render(),
'#default_value' => '[current-page:query:code:clear]',
'#description' => $this
->t('Enter your personal invitation code (only applies if the field is not populated yet).')
->render(),
'#maxlength' => 64,
'#required' => TRUE,
],
];
$elements = $element + $elements;
$webform
->setElements($elements);
$webform
->save();
}
$this
->messenger()
->addMessage($this
->t('Invitation mode has been activated. You should now <a href="@link">create some invitation codes</a>.', [
'@link' => Url::fromRoute('entity.webform.invitation_generate', [
'webform' => $webform
->id(),
])
->toString(),
]));
}
else {
if ($enabled) {
$webform
->deleteElement('webform_invitation_code');
$webform
->save();
}
$this
->messenger()
->addMessage($this
->t('Invitation mode has been disabled.'));
}
}
}