Untitled

 avatar
unknown
plain_text
a year ago
4.8 kB
9
Indexable
<?php

namespace Drupal\tigo\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\td_atomic_design\Element\TextfieldAtomic;

/**
 * Provides a one-line text field form element.
 *
 * Properties:
 * - #value [optional]: An text to show by default'.
 * - #help_text: An text to show under the input.
 * - #status [optional]: A status to show in input (Available: activo, disabled
 *    or error).
 *
 * @code
 * $form['expiration'] = array(
 *  '#type' => 'date_tigo',
 *  '#title' => $this->t('Atómico'),
 *  '#value' => 'Valor',
 *  '#maxlength' => 200,
 *  '#help_text' => $this->t('Texto de ayuda.'),
 *  '#status' => 'activo',
 * );
 * @endcode
 *
 * @FormElement("date_tigo")
 */
class DateTigo extends TextfieldAtomic {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = static::class;
    return [
      '#input' => TRUE,
      '#autocomplete_route_name' => FALSE,
      '#process' => [
        [$class, 'processAutocomplete'],
        [$class, 'processAjaxForm'],
        [$class, 'processPattern'],
        [$class, 'processGroup'],
        [$class, 'processDateTigo'],
      ],
      '#pre_render' => [
        [$class, 'preRenderTextfield'],
        [$class, 'preRenderGroup'],
      ],
      '#theme' => 'textfield_atomic',
      '#theme_wrappers' => ['form_element_atomic'],
      '#attributes' => [
        'class' => [
          'at-input-textfield',
          'js-date',
          'tigo-date',
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function preRenderTextfield($element) {
    $element['#attributes']['type'] = 'text';
    Element::setAttributes($element, ['id', 'name', 'value', 'size',
      'maxlength', 'placeholder',
    ]);
    static::setAttributes($element, [
      'at-input-textfield',
      'js-date',
      'tigo-date',
    ]);
    $element['#attached']['library'] = ['td_atomic_design/textfield'];
    return $element;
  }

  /**
   * Redenrizado para la selfie.
   */
  public static function processDateTigo(&$element, FormStateInterface $form_state, &$form) {
    if (!empty($element['#default_value'])) {
      $element['#value'] = self::defaultValue($element['#default_value']);
    }
    // Agregar una validación personalizada para la fecha.
    $element['#element_validate'][] = [static::class, 'validateDateTigo'];

    return $element;
  }

  /**
   * Valida la fecha ingresada en el campo.
   */
  public static function validateDateTigo($element, FormStateInterface $form_state, $form) {
    // Obtener el valor enviado desde el estado del formulario.
    $value = $form_state->getValue($element['#name']);

    // Definir el patrón para una fecha válida en el formato "dd-mmm-yyyy".
    $pattern = '/^\d{2}-[A-Za-z]{3}-\d{4}$/';

    // Verificar si el valor enviado coincide con el patrón.
    if (!preg_match($pattern, $value)) {
      $form_state->setError($element, t('Por favor, ingrese una fecha válida en el formato "dd-mm-yyyy".'));
      return;
    }

    // Extraer día, mes y año del valor enviado.
    [$day, $month, $year] = explode('-', $value);

    $monthsMapping = [
      'Ene' => '01',
      'Feb' => '02',
      'Mar' => '03',
      'Abr' => '04',
      'May' => '05',
      'Jun' => '06',
      'Jul' => '07',
      'Ago' => '08',
      'Sep' => '09',
      'Oct' => '10',
      'Nov' => '11',
      'Dic' => '12',
    ];

    $month = $monthsMapping[$month];

    // Actualizar el valor del campo con el nuevo formato.
    $form_state->setValue($element['#name'], strtotime("{$day}-{$month}-{$year}"));

    // Obtener el año actual.
    $current_year = date('Y');

    // Verificar si el año es mayor que el año actual y mostrar un mensaje de error si es así.
    if ((int) $year > $current_year) {
      $form_state->setError($element, t('El año no puede ser mayor que el año actual.'));
      return;
    }

    // Verificar si el año es menor a 100 años en el pasado y mostrar un mensaje de error si es así.
    $min_year = $current_year - 100;
    if ((int) $year < $min_year) {
      $form_state->setError($element, t('El año no puede ser hace más de 100 años.'));
    }
  }

  /**
   *
   */
  public static function defaultValue($date) {
    $output = NULL;
    if ($date) {
      $monthsMapping = [
        '01' => 'Ene',
        '02' => 'Feb',
        '03' => 'Mar',
        '04' => 'Abr',
        '05' => 'May',
        '06' => 'Jun',
        '07' => 'Jul',
        '08' => 'Ago',
        '09' => 'Sep',
        '10' => 'Oct',
        '11' => 'Nov',
        '12' => 'Dic',
      ];
      $date = date('d-m-Y', $date);
      [$day, $monthAbbrev, $year] = explode('-', $date);
      $monthNumeric = $monthsMapping[$monthAbbrev];
      $output = "$day-$monthNumeric-$year";
    }

    return $output;
  }

}
Editor is loading...
Leave a Comment