You are here

SettingsForm.php in Christmas Lights 8

File

src/Form/SettingsForm.php
View source
<?php

namespace Drupal\christmas_lights\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Defines a form that configures christmas_lights settings.
 */
class SettingsForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'christmas_lights.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $config = $this
      ->config('christmas_lights.settings');
    $form['enabled'] = [
      '#type' => 'checkbox',
      '#default_value' => $config
        ->get('enabled'),
      '#title' => $this
        ->t('Enable christmas lights'),
    ];
    $form['start'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Start date'),
      '#default_value' => date('Y-m-d', $config
        ->get('start')),
      '#description' => $this
        ->t('The date your enable christmas lights'),
      '#required' => TRUE,
    ];
    $form['end'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Finish date'),
      '#default_value' => date('Y-m-d', $config
        ->get('end')),
      '#description' => $this
        ->t('The date your disable christmas lights'),
      '#required' => TRUE,
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $start = strtotime($values['start']);
    $end = strtotime($values['end']);
    if ($start >= $end) {
      $form_state
        ->setErrorByName('start', $this
        ->t('You must select a valid start date.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $this
      ->config('christmas_lights.settings')
      ->set('enabled', $values['enabled'])
      ->set('start', strtotime($values['start']))
      ->set('end', strtotime($values['end']))
      ->save();
  }

}

Classes

Namesort descending Description
SettingsForm Defines a form that configures christmas_lights settings.