View source
<?php
namespace Drupal\interval\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\interval\IntervalPluginManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class IntervalWidget extends WidgetBase implements ContainerFactoryPluginInterface {
protected $intervalManager;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, IntervalPluginManagerInterface $interval_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->intervalManager = $interval_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['third_party_settings'], $container
->get('plugin.manager.interval.intervals'));
}
public static function defaultSettings() {
return [
'allowed_periods' => [],
] + parent::defaultSettings();
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$item = $items
->get($delta);
$element += [
'#type' => 'interval',
'#periods' => array_keys(array_filter($this
->getSetting('allowed_periods'))),
'#default_value' => [
'interval' => $item
->getInterval(),
'period' => $item
->getPeriod(),
],
];
return $element;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$options = [];
$intervals = $this->intervalManager
->getDefinitions();
foreach ($intervals as $key => $detail) {
$options[$key] = $detail['plural'];
}
$form['allowed_periods'] = [
'#type' => 'checkboxes',
'#title' => t('Allowed periods'),
'#options' => $options,
'#description' => t('Select the periods you wish to be available in the dropdown. Selecting none will make all of them available.'),
'#default_value' => $this
->getSetting('allowed_periods'),
];
return $form;
}
public function settingsSummary() {
$summary = [];
$summary[] = t('Allowed periods: @periods', [
'@periods' => implode(', ', array_filter($this
->getSetting('allowed_periods'))),
]);
return $summary;
}
}