StringTextfieldWidget.php 2.34 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextfieldWidget.
6
7
8
9
10
11
 */

namespace Drupal\Core\Field\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
12
use Drupal\Core\Form\FormStateInterface;
13
14

/**
15
 * Plugin implementation of the 'string_textfield' widget.
16
17
 *
 * @FieldWidget(
18
19
 *   id = "string_textfield",
 *   label = @Translation("Textfield"),
20
 *   field_types = {
21
 *     "string"
22
23
24
 *   }
 * )
 */
25
class StringTextfieldWidget extends WidgetBase {
26

27
28
29
30
31
32
33
34
35
36
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'size' => 60,
      'placeholder' => '',
    ) + parent::defaultSettings();
  }

37
38
39
  /**
   * {@inheritdoc}
   */
40
  public function settingsForm(array $form, FormStateInterface $form_state) {
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    $element['size'] = array(
      '#type' => 'number',
      '#title' => t('Size of textfield'),
      '#default_value' => $this->getSetting('size'),
      '#required' => TRUE,
      '#min' => 1,
    );
    $element['placeholder'] = array(
      '#type' => 'textfield',
      '#title' => t('Placeholder'),
      '#default_value' => $this->getSetting('placeholder'),
      '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();

    $summary[] = t('Textfield size: !size', array('!size' => $this->getSetting('size')));
    $placeholder = $this->getSetting('placeholder');
    if (!empty($placeholder)) {
      $summary[] = t('Placeholder: @placeholder', array('@placeholder' => $placeholder));
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
75
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
76
77
78
79
80
81
    $element['value'] = $element + array(
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
      '#size' => $this->getSetting('size'),
      '#placeholder' => $this->getSetting('placeholder'),
      '#maxlength' => $this->getFieldSetting('max_length'),
82
      '#attributes' => array('class' => array('js-text-full', 'text-full')),
83
84
85
86
87
88
    );

    return $element;
  }

}