You are here

HijriDefaultWidget.php in Hijri 1.0.x

File

src/Plugin/Field/FieldWidget/HijriDefaultWidget.php
View source
<?php

namespace Drupal\hijri\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'HijriDefaultWidget' widget.
 *
 * @FieldWidget(
 *   id = "HijriDefaultWidget",
 *   label = @Translation("Hijri default widget"),
 *   field_types = {
 *     "Hijri"
 *   }
 * )
 */
class HijriDefaultWidget extends WidgetBase {

  /**
   * Define the form for the field type.
   *
   * Inside this method we can define the form used to edit the field type.
   *
   * Here there is a list of allowed element types: https://goo.gl/XVd4tA
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Hijri'),
      '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
      '#empty_value' => '',
      '#placeholder' => $this
        ->t('Hijri'),
      '#element_validate' => [
        [
          $this,
          'validate',
        ],
      ],
    ];
    $element['correction'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Correction'),
      '#default_value' => isset($items[$delta]->correction) ? $items[$delta]->correction : NULL,
      '#empty_value' => '',
      '#placeholder' => $this
        ->t('Correction'),
    ];
    return $element;
  }

  /**
   * Validate field.
   */
  public function validate(&$element, FormStateInterface &$form_state, $form) {

    // parent::validate($element, $form_state, $form);.
    // @todo Fix this issue to support more than one field.
    // @todo Get field name the right way.
    $field_name = $element['#array_parents'][0];
    $field_values = $form_state
      ->getValue([
      $field_name,
    ]);
    $value = $field_values[0]['value'];

    // We have to convert this selected date to be in iso8601.
    // @todo We have to validate the provided Hijri date.
    if ($element['#required'] || strlen($value) > 0 || strlen($value) > 0) {
      $form_state
        ->setError($element, $this
        ->t('Field is required.'));
    }
  }

}

Classes

Namesort descending Description
HijriDefaultWidget Plugin implementation of the 'HijriDefaultWidget' widget.