You are here

class OfficeHoursList in Office Hours 8

Provides a one-line text field form element for the List Widget.

Plugin annotation

@FormElement("office_hours_list");

Hierarchy

Expanded class hierarchy of OfficeHoursList

1 #type use of OfficeHoursList
OfficeHoursListWidget::formElement in src/Plugin/Field/FieldWidget/OfficeHoursListWidget.php
Returns the form for a single field widget.

File

src/Element/OfficeHoursList.php, line 16

Namespace

Drupal\office_hours\Element
View source
class OfficeHoursList extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $info = [
      '#input' => TRUE,
      '#tree' => TRUE,
      '#process' => [
        [
          static::class,
          'processOfficeHoursSlot',
        ],
      ],
      '#element_validate' => [
        [
          static::class,
          'validateOfficeHoursSlot',
        ],
      ],
    ];
    return $info;
  }

  /**
   * Gets this list element's default operations.
   *
   * @param array $element
   *   The entity the operations are for.
   *
   * @return array
   *   The array structure is identical to the return value of
   *   self::getOperations().
   */
  public static function getDefaultOperations(array $element) {
    $operations = [];
    $max_delta = $element['#field_settings']['cardinality_per_day'] - 1;
    $day_delta = $element['#daydelta'];
    $day = isset($element['#value']['day']) ? (int) $element['#value']['day'] : 0;
    $suffix = ' ';

    // Show a 'Clear this line' js-link to each element.
    // Use text 'Remove', which has lots of translations.
    $operations['delete'] = [];
    if (isset($element['#value']['starthours']) || isset($element['#value']['endhours'])) {
      $operations['delete'] = [
        '#type' => 'link',
        '#title' => t('Remove'),
        '#weight' => 12,
        '#url' => Url::fromRoute('<front>'),
        // Dummy, will be catch-ed by js.
        '#suffix' => $suffix,
        '#attributes' => [
          'class' => [
            'office-hours-delete-link',
            'office-hours-link',
          ],
        ],
      ];
    }

    // Add 'Copy' link to first slot of each day.
    // First day copies from last day.
    $operations['copy'] = [];
    if ($day_delta == 0) {
      $operations['copy'] = [
        '#type' => 'link',
        '#title' => $day !== OfficeHoursDateHelper::getFirstDay() ? t('Copy previous day') : t('Copy last day'),
        '#weight' => 16,
        '#url' => Url::fromRoute('<front>'),
        // Dummy, will be catch-ed by js.
        '#suffix' => $suffix,
        '#attributes' => [
          'class' => [
            'office-hours-copy-link',
            'office-hours-link',
          ],
        ],
      ];
    }

    // Add 'Add time slot' link to all-but-last slots of each day.
    $operations['add'] = [];
    if ($day_delta < $max_delta) {
      $operations['add'] = [
        '#type' => 'link',
        '#title' => t('Add @node_type', [
          '@node_type' => t('time slot'),
        ]),
        '#weight' => 11,
        '#url' => Url::fromRoute('<front>'),
        // Dummy, will be catch-ed by js.
        '#suffix' => $suffix,
        '#attributes' => [
          'class' => [
            'office-hours-add-link',
            'office-hours-link',
          ],
        ],
      ];
    }
    return $operations;
  }

  /**
   * Process an individual element.
   *
   * Build the form element. When creating a form using Form API #process,
   * note that $element['#value'] is already set.
   *
   * @param $element
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param $complete_form
   *
   * @return array
   *   The enriched element, identical to first parameter.
   */
  public static function processOfficeHoursSlot(&$element, FormStateInterface $form_state, &$complete_form) {
    $field_settings = $element['#field_settings'];
    $day = isset($element['#value']['day']) ? $element['#value']['day'] : '';
    $day_delta = $element['#daydelta'];
    $element['#attributes']['class'][] = 'form-item';
    $element['#attributes']['class'][] = 'office-hours-slot';
    $element['day'] = [
      '#type' => 'select',
      '#options' => OfficeHoursDateHelper::weekDays(FALSE),
      '#default_value' => $day,
    ];
    $element['starthours'] = [
      '#type' => $field_settings['element_type'],
      // datelist, datetime.
      '#field_settings' => $field_settings,
      // Get the valid, restricted hours. Date API doesn't provide a straight method for this.
      '#hour_options' => OfficeHoursDateHelper::hours($field_settings['time_format'], FALSE, $field_settings['limit_start'], $field_settings['limit_end']),
      // Attributes for element \Drupal\Core\Datetime\Element\Datelist - Start.
      '#date_part_order' => in_array($field_settings['time_format'], [
        'g',
        'h',
      ]) ? [
        'hour',
        'minute',
        'ampm',
      ] : [
        'hour',
        'minute',
      ],
      '#date_increment' => $field_settings['increment'],
      '#date_time_element' => 'time',
      '#date_time_format' => OfficeHoursDateHelper::getTimeFormat($field_settings['time_format']),
      '#date_timezone' => '+0000',
    ];
    $element['endhours'] = $element['starthours'];
    $element['starthours']['#default_value'] = isset($element['#value']['starthours']) ? $element['#value']['starthours'] : NULL;
    $element['endhours']['#default_value'] = isset($element['#value']['endhours']) ? $element['#value']['endhours'] : NULL;
    $element['comment'] = !$field_settings['comment'] ? NULL : [
      '#type' => 'textfield',
      '#default_value' => isset($element['#value']['comment']) ? $element['#value']['comment'] : NULL,
      '#size' => 20,
      '#maxlength' => 255,
      '#field_settings' => $field_settings,
    ];

    // Copied from EntityListBuilder::buildOperations().
    $element['operations'] = [
      'data' => OfficeHoursList::getDefaultOperations($element),
    ];
    $element['day_delta'] = [
      '#type' => 'value',
      '#value' => $day_delta,
    ];
    return $element;
  }

  /**
   * Render API callback: Validates the element.
   *
   * Implements a callback for _office_hours_elements().
   *
   * For 'office_hours_slot' (day) and 'office_hours_datelist' (hour) elements.
   * You can find the value in $element['#value'],
   * but better in $form_state['values'],
   * which is set in validateOfficeHoursSlot().
   *
   * @param $element
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param $complete_form
   */
  public static function validateOfficeHoursSlot(&$element, FormStateInterface $form_state, &$complete_form) {
    $error_text = '';

    // Return an array with starthours, endhours, comment.
    $input_exists = FALSE;
    $input = NestedArray::getValue($form_state
      ->getValues(), $element['#parents'], $input_exists);
    $input_exists = TRUE;
    if (OfficeHoursDatetime::isEmpty($input)) {
      return;
    }
    $field_settings = $element['#field_settings'];
    $validate_hours = $field_settings['valhrs'];
    $limit_start = $field_settings['limit_start'];
    $limit_end = $field_settings['limit_end'];
    $start = OfficeHoursDatetime::get($input['starthours'], 'Hi');
    $end = OfficeHoursDatetime::get($input['endhours'], 'Hi');

    // If any field of slot is filled, check for required time fields.
    $required_start = $field_settings['required_start'] ?? FALSE;
    if ($required_start && empty($start)) {
      $error_text = 'Opening hours must be set.';
      $erroneous_element =& $element['starthours'];
    }
    $required_end = $field_settings['required_end'] ?? FALSE;
    if ($required_end && empty($end)) {
      $error_text = 'Closing hours must be set.';
      $erroneous_element =& $element['endhours'];
    }
    if ($validate_hours) {
      if ((!empty($start) xor !empty($end)) && !empty($limit_end)) {
        $error_text = 'Both Opening hours and Closing hours must be set.';
        $erroneous_element =& $element;
      }
      elseif ($end < $start && $end == '0000') {

        // Exception: end time is 00:00 / 24:00.
        $error_text = 'Closing hours are earlier than Opening hours.';
        $erroneous_element =& $element;
      }
      elseif (!empty($limit_start) || !empty($limit_end)) {
        if ($start && $limit_start * 100 > $start || $end && $limit_end * 100 < $end) {
          $error_text = 'Hours are outside limits ( @start - @end ).';
          $erroneous_element =& $element;
        }
      }
    }
    if ($error_text) {
      $day_name = OfficeHoursDateHelper::weekDays(FALSE)[$input['day']];
      $error_text = $day_name . ': ' . t($error_text, [
        '@start' => $limit_start . ':00',
        '@end' => $limit_end . ':00',
      ], [
        'context' => 'office_hours',
      ]);
      $form_state
        ->setError($erroneous_element, $error_text);
    }
  }

}

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
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
FormElement::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElementInterface::valueCallback 15
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
OfficeHoursList::getDefaultOperations public static function Gets this list element's default operations.
OfficeHoursList::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
OfficeHoursList::processOfficeHoursSlot public static function Process an individual element. 1
OfficeHoursList::validateOfficeHoursSlot public static function Render API callback: Validates the element.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
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.