You are here

TwitterEmbedWidget.php in Twitter Embed 8

File

src/Plugin/Field/FieldWidget/TwitterEmbedWidget.php
View source
<?php

namespace Drupal\twitter_embed\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\twitter_embed\TwitterWidgetInterface;

/**
 * Plugin implementation of the 'twitter_timeline_widget' widget.
 *
 * @FieldWidget(
 *   id = "twitter_embed_widget",
 *   label = @Translation("Twitter embed"),
 *   field_types = {
 *     "twitter_embed_field"
 *   }
 * )
 */
class TwitterEmbedWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'size' => 60,
      'placeholder' => '',
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $elements = [];
    $elements['size'] = [
      '#type' => 'number',
      '#title' => t('Size of textfield'),
      '#default_value' => $this
        ->getSetting('size'),
      '#required' => TRUE,
      '#min' => 1,
    ];
    $elements['placeholder'] = [
      '#type' => 'textfield',
      // @todo
      '#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 $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $summary[] = t('Textfield size: @size', [
      '@size' => $this
        ->getSetting('size'),
    ]);
    if (!empty($this
      ->getSetting('placeholder'))) {
      $summary[] = t('Placeholder: @placeholder', [
        '@placeholder' => $this
          ->getSetting('placeholder'),
      ]);
    }
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
      '#size' => $this
        ->getSetting('size'),
      '#placeholder' => $this
        ->getSetting('placeholder'),
      '#field_prefix' => '@',
      '#maxlength' => TwitterWidgetInterface::USERNAME_MAX_LENGTH,
    ];
    return $element;
  }

}

Classes

Namesort descending Description
TwitterEmbedWidget Plugin implementation of the 'twitter_timeline_widget' widget.