You are here

SignatureFormatter.php in SignatureField 1.x

File

src/Plugin/Field/FieldFormatter/SignatureFormatter.php
View source
<?php

namespace Drupal\signaturefield\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides the signature formatter for the signature field.
 *
 * @FieldFormatter(
 *   id = "signature",
 *   label = @Translation("Signature"),
 *   field_types = {
 *     "signature",
 *   },
 * )
 */
class SignatureFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'width' => 400,
      'height' => 200,
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);
    $form['width'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Width'),
      '#default_value' => $this
        ->getSetting('width'),
      '#min' => 100,
      '#step' => 5,
      '#required' => TRUE,
      '#field_suffix' => 'px',
    ];
    $form['height'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Height'),
      '#default_value' => $this
        ->getSetting('height'),
      '#min' => 75,
      '#step' => 5,
      '#required' => TRUE,
      '#field_suffix' => 'px',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();
    $summary[] = $this
      ->t('Dimensions: @widthx@heightpx', [
      '@width' => $this
        ->getSetting('width'),
      '@height' => $this
        ->getSetting('height'),
    ]);
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];
    foreach ($items as $delta => $item) {
      $element[$delta] = [
        '#theme' => 'image',
        '#width' => $this
          ->getSetting('width'),
        '#height' => $this
          ->getSetting('height'),
        '#alt' => $this
          ->t('Signature'),
        '#attributes' => [
          'src' => $item->value,
        ],
      ];
    }
    return $element;
  }

}

Classes

Namesort descending Description
SignatureFormatter Provides the signature formatter for the signature field.