You are here

public function RegcodeAdminCreateForm::submitForm in Registration codes 8

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/RegcodeAdminCreateForm.php, line 131

Class

RegcodeAdminCreateForm
Form for creation of registration codes.

Namespace

Drupal\regcode\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $code = new \stdClass();

  // Convert dates into timestamps.
  foreach ([
    'begins',
    'expires',
  ] as $field) {
    $value = $form_state
      ->getValue([
      'regcode_create_' . $field,
    ]);
    if (!empty($value)) {
      $code->{$field} = NULL;
      $date = strtotime($value);
      $day = date('d', $date);
      $month = date('m', $date);
      $year = date('Y', $date);
      if (isset($year) && $year != 0) {
        $code->{$field} = mktime(0, 0, 0, $month, $day, $year);
      }
    }
  }

  // Grab form values.
  $code->is_active = 1;
  $code->maxuses = $form_state
    ->getValue([
    'regcode_create_maxuses',
  ]);

  // Start creating codes.
  for ($i = 0; $i < (int) $form_state
    ->getValue([
    'regcode_create_number',
  ]); $i++) {
    $code->code = $form_state
      ->getValue([
      'regcode_create_code',
    ]);

    // Generate a code.
    if (empty($code->code) || $form_state
      ->getValue([
      'regcode_create_number',
    ]) > 1) {
      $gen = regcode_generate($form_state
        ->getValue([
        'regcode_create_length',
      ]), $form_state
        ->getValue([
        'regcode_create_format',
      ]), $form_state
        ->getValue([
        'regcode_create_case',
      ]));
      $code->code .= $gen;
    }

    // Save code.
    if (regcode_save($code, REGCODE_MODE_SKIP)) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Created registration code (%code)', [
        '%code' => $code->code,
      ]));
    }
    else {
      $this
        ->messenger()
        ->addWarning($this
        ->t('Unable to create code (%code) as code already exists', [
        '%code' => $code->code,
      ]));
    }
  }
}