3 namespace Drupal\Core\Field\Plugin\Field\FieldWidget;
5 use Drupal\Core\Field\FieldItemListInterface;
6 use Drupal\Core\Field\WidgetBase;
7 use Drupal\Core\Form\FormStateInterface;
10 * Plugin implementation of the 'boolean_checkbox' widget.
13 * id = "boolean_checkbox",
14 * label = @Translation("Single on/off checkbox"),
18 * multiple_values = TRUE
21 class BooleanCheckboxWidget extends WidgetBase {
26 public static function defaultSettings() {
28 'display_label' => TRUE,
29 ] + parent::defaultSettings();
35 public function settingsForm(array $form, FormStateInterface $form_state) {
36 $element['display_label'] = [
37 '#type' => 'checkbox',
38 '#title' => t('Use field label instead of the "On" label as the label.'),
39 '#default_value' => $this->getSetting('display_label'),
48 public function settingsSummary() {
51 $display_label = $this->getSetting('display_label');
52 $summary[] = t('Use field label: @display_label', ['@display_label' => ($display_label ? t('Yes') : 'No')]);
60 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
61 $element['value'] = $element + [
62 '#type' => 'checkbox',
63 '#default_value' => !empty($items[0]->value),
66 // Override the title from the incoming $element.
67 if ($this->getSetting('display_label')) {
68 $element['value']['#title'] = $this->fieldDefinition->getLabel();
71 $element['value']['#title'] = $this->fieldDefinition->getSetting('on_label');