niobi-8.x-2.0-alpha4/modules/niobi_form/modules/niobi_app/src/Plugin/Field/FieldWidget/NiobiAppDecisionWidget.php
modules/niobi_form/modules/niobi_app/src/Plugin/Field/FieldWidget/NiobiAppDecisionWidget.php
<?php
namespace Drupal\niobi_app\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
use Drupal\niobi_app\NiobiAppUtilities;
/**
* Plugin implementation of the 'niobi_app_decision_widget' widget.
*
* @FieldWidget(
* id = "niobi_app_decision_widget",
* label = @Translation("Niobi Application Decision widget"),
* field_types = {
* "niobi_app_decision_type"
* },
* multiple_values = TRUE
* )
*/
class NiobiAppDecisionWidget extends OptionsWidgetBase {
var $multiple;
var $required;
var $has_value;
/**
* {@inheritdoc}
*/
protected function sanitizeLabel(&$label) {
// Select form inputs allow unencoded HTML entities, but no HTML tags.
$label = Html::decodeEntities(strip_tags($label));
}
/**
* {@inheritdoc}
*/
protected function supportsGroups() {
return TRUE;
}
/**
* {@inheritdoc}
*/
protected function getEmptyLabel() {
if ($this->multiple) {
// Multiple select: add a 'none' option for non-required fields.
if (!$this->required) {
return t('- None -');
}
}
else {
// Single select: add a 'none' option for non-required fields,
// and a 'select a value' option for required fields that do not come
// with a value selected.
if (!$this->required) {
return t('- None -');
}
if (!$this->has_value) {
return t('- Select a value -');
}
}
}
protected function getOptions(FieldableEntityInterface $entity) {
return NiobiAppUtilities::getDecisionsAsOptions();
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$element += [
'#type' => $this->multiple ? 'checkboxes' : 'radios',
'#options' => $this->getOptions($items->getEntity()),
'#empty_option' => $this->getEmptyLabel(),
'#default_value' => $this->getSelectedOptions($items),
// Do not display a 'multiple' select box if there is only one option.
'#multiple' => $this->multiple && count($this->getOptions($items->getEntity())) > 1,
];
return $element;
}
}
