You are here

class RegcodeAdminCreateForm in Registration codes 8

Form for creation of registration codes.

Hierarchy

Expanded class hierarchy of RegcodeAdminCreateForm

1 string reference to 'RegcodeAdminCreateForm'
regcode.routing.yml in ./regcode.routing.yml
regcode.routing.yml

File

src/Form/RegcodeAdminCreateForm.php, line 11

Namespace

Drupal\regcode\Form
View source
class RegcodeAdminCreateForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'regcode_admin_create';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $regcode_config = $this
      ->config('regcode.settings');

    // Basics.
    $form = [];
    $form['regcode_create'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('General settings'),
    ];
    $form['regcode_create']['regcode_create_code'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Registration code'),
      '#description' => $this
        ->t('Leave blank to have code generated. Used as prefix when <em>Number of codes</em> is greater than 1.'),
    ];
    $form['regcode_create']['regcode_create_maxuses'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Maximum uses'),
      '#description' => $this
        ->t('How many times this code can be used to register (enter 0 for unlimited).'),
      '#size' => 10,
      '#default_value' => 1,
      '#required' => TRUE,
    ];
    $form['regcode_create']['regcode_create_length'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Code size'),
      '#size' => 10,
      '#default_value' => 12,
    ];
    $form['regcode_create']['regcode_create_format'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Format of the generated codes'),
      '#options' => [
        'alpha' => $this
          ->t('Letters'),
        'numeric' => $this
          ->t('Numbers'),
        'alphanum' => $this
          ->t('Numbers & Letters'),
        'hexadec' => $this
          ->t('Hexadecimal'),
      ],
      '#default_value' => $regcode_config
        ->get('regcode_generate_format'),
    ];
    $form['regcode_create']['regcode_create_case'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Convert generated codes to uppercase'),
      '#default_value' => $regcode_config
        ->get('regcode_generate_case'),
    ];
    $form['regcode_create']['regcode_create_begins'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Active from'),
      '#description' => $this
        ->t('When this code should activate (leave blank to activate immediately). Accepts any date format that strtotime can handle.'),
      '#default_value' => [
        'day' => 0,
        'month' => 0,
        'year' => 0,
      ],
      '#element_validate' => [
        [
          $this,
          'validateDate',
        ],
      ],
    ];
    $form['regcode_create']['regcode_create_expires'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Expires on'),
      '#description' => $this
        ->t('When this code should expire (leave blank for no expiry). Accepts any date format that strtotime can handle.'),
      '#default_value' => [
        'day' => 0,
        'month' => 0,
        'year' => 0,
      ],
      '#element_validate' => [
        [
          $this,
          'validateDate',
        ],
      ],
    ];

    // Bulk.
    $form['regcode_create_bulk'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Bulk settings'),
      '#description' => $this
        ->t('Multiple codes can be created at once, use these settings to configure the code generation.'),
    ];
    $form['regcode_create_bulk']['regcode_create_number'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Number of codes to generate'),
      '#size' => 10,
      '#default_value' => 1,
    ];
    $form['regcode_create_bulk_submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Create codes'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!is_numeric($form_state
      ->getValue([
      'regcode_create_maxuses',
    ])) || $form_state
      ->getValue([
      'regcode_create_maxuses',
    ]) < 0) {
      $form_state
        ->setErrorByName('regcode_create_maxuses', $this
        ->t('Invalid maxuses, specify a positive integer or enter "0" for unlimited'));
    }
  }

  /**
   * {@inheritdoc}
   */
  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,
        ]));
      }
    }
  }

  /**
   * Ensures a blank date validates.
   */
  public function validateDate(array &$element, FormStateInterface $form_state) {
    if (isset($element['#value']) && !empty($element['#value'])) {
      $date = strtotime($element['#value']);
      $day = date('d', $date);
      $month = date('m', $date);
      $year = date('Y', $date);
      if (!checkdate($month, $day, $year)) {
        $form_state
          ->setError($element, $this
          ->t('The specified date is invalid.'));
      }
    }
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
RegcodeAdminCreateForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
RegcodeAdminCreateForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RegcodeAdminCreateForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
RegcodeAdminCreateForm::validateDate public function Ensures a blank date validates.
RegcodeAdminCreateForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.