You are here

public function ExampleCustomInput::validateVoucherCode in Extra Field 8.2

Field validation callback for voucher code.

Parameters

array $form: The form element.

\Drupal\Core\Form\FormStateInterface $form_state: The form state.

File

modules/extra_field_example/src/Plugin/ExtraField/Form/ExampleCustomInput.php, line 99

Class

ExampleCustomInput
Example Extra field form display.

Namespace

Drupal\extra_field_example\Plugin\ExtraField\Form

Code

public function validateVoucherCode(array $form, FormStateInterface $form_state) {
  $voucherCode = $this
    ->lookupVoucherCodeEntity($form_state
    ->getValue('voucher_code_text'));
  if (empty($voucherCode)) {
    $form_state
      ->setErrorByName(self::VOUCHER_CODE_FIELD, $this
      ->t('Invalid voucher code'));
    return;
  }
  if ($voucherCode
    ->isExpired()) {
    $form_state
      ->setErrorByName(self::VOUCHER_CODE_FIELD, $this
      ->t('This voucher code is no longer valid'));
    return;
  }

  // Set the entity reference to match the voucher code input.
  $form_state
    ->setValue(self::VOUCHER_REFERENCE_FIELD, [
    [
      'target_id' => $voucherCode
        ->id(),
    ],
  ]);
}