xtcentity-2.x-dev/src/Plugin/Field/FieldWidget/XtcFieldOptionsButtonsWidget.php

src/Plugin/Field/FieldWidget/XtcFieldOptionsButtonsWidget.php
<?php

namespace Drupal\xtcentity\Plugin\Field\FieldWidget;


use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'xtcfield_optionsbuttons_widget' widget.
 *
 * @FieldWidget(
 *   id = "xtcfield_options_buttons",
 *   label = @Translation("XTC Field Check boxes/radio buttons"),
 *   field_types = {
 *     "xtcfield_plugin_cache",
 *     "xtcfield_plugin_handler",
 *     "xtcfield_plugin_profile",
 *     "xtcfield_plugin_request",
 *     "xtcfield_plugin_server",
 *   },
 *   multiple_values = TRUE
 * )
 */
class XtcFieldOptionsButtonsWidget extends XtcFieldOptionsWidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

//    $options = $this->getOptions();
    $options = $this->getOptions($items->getEntity());
    $selected = $this->getSelectedOptions($items);

    // If required and there is one single option, preselect it.
    if ($this->required && count($options) == 1) {
      reset($options);
      $selected = [key($options)];
    }

    if ($this->multiple) {
      $element += [
        '#type' => 'checkboxes',
        '#default_value' => $selected,
        '#options' => $options,
      ];
    }
    else {
      $element += [
        '#type' => 'radios',
        // Radio buttons need a scalar value. Take the first default value, or
        // default to NULL so that the form element is properly recognized as
        // not having a default value.
        '#default_value' => $selected ? reset($selected) : NULL,
        '#options' => $options,
      ];
    }

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEmptyLabel() {
    if (!$this->required && !$this->multiple) {
      return t('N/A');
    }
  }

  /**
   * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
   *
   * @return array
   */
  protected function getOptions(FieldableEntityInterface $entity) {
    $options = [];
    $values = parent::getOptions($entity); // TODO: Change the autogenerated stub
    foreach ($values as $name => $value) {
      if (is_array($value)) {
        foreach ($value as $key => $option) {
          $options[$key] = $option;
        }
      }
      else {
        $options[$name] = $value;
      }
    }
    return $options;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc