public function WebformInvitationGenerateForm::submitForm in Webform Invitation 8
Same name and namespace in other branches
- 2.0.x src/Form/WebformInvitationGenerateForm.php \Drupal\webform_invitation\Form\WebformInvitationGenerateForm::submitForm()
Form submission handler.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Overrides FormInterface::submitForm
File
- src/
Form/ WebformInvitationGenerateForm.php, line 142
Class
- WebformInvitationGenerateForm
- Provides a form to generate invitation codes.
Namespace
Drupal\webform_invitation\FormCode
public function submitForm(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\webform\Entity\Webform $webform */
$webform = $form_state
->getValue('webform');
$webform_id = $webform
->id();
$number = $form_state
->getValue('number');
$type = $form_state
->getValue('type');
$length = $form_state
->getValue('length');
$chars = $form_state
->getValue('chars');
// Prepare character set for custom code.
$set = '';
if (!empty($chars[1])) {
$set .= 'abcdefghijklmnopqrstuvwxyz';
}
if (!empty($chars[2])) {
$set .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
if (!empty($chars[3])) {
$set .= '0123456789';
}
if (!empty($chars[4])) {
$set .= '.,:;-_!?';
}
if (!empty($chars[5])) {
$set .= '#+*=$%&|';
}
$i = $l = 1;
// Process all requested tokens.
while ($i <= $number && $l < $number * 10) {
$code = '';
// Code generation.
switch ($type) {
case 'md5':
$code = md5(microtime(1) * rand());
break;
case 'custom':
for ($j = 1; $j <= $length; $j++) {
$code .= $set[rand(0, strlen($set) - 1)];
}
break;
}
try {
// Insert code to DB.
$this->database
->insert('webform_invitation_codes')
->fields([
'webform' => $webform_id,
'code' => $code,
'created' => $this->time
->getRequestTime(),
])
->execute();
$i++;
} catch (\Exception $e) {
// The generated code is already in DB, make another one.
}
$l++;
}
// Output number of generated codes.
$codes_count = $i - 1;
if ($l >= $number * 10) {
$this
->messenger()
->addMessage($this
->t('Due to unique constraint, only @ccount codes have been generated.', [
'@ccount' => $codes_count,
]), 'error');
}
elseif ($codes_count == 1) {
$this
->messenger()
->addMessage($this
->t('A single code has been generated.'));
}
else {
$this
->messenger()
->addMessage($this
->t('A total of @ccount codes has been generated.', [
'@ccount' => $codes_count,
]));
}
// Redirect user to list of codes.
$form_state
->setRedirect('entity.webform.invitation_codes', [
'webform' => $webform_id,
]);
}