FormatterItem.php in Formatter Field 8        
                          
                  
                        
  
  
  
  
  
File
  src/Plugin/Field/FieldType/FormatterItem.php
  
    View source  
  <?php
namespace Drupal\formatter_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\field\FieldConfigInterface;
class FormatterItem extends FieldItemBase {
  
  protected $fieldManager;
  
  public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
    parent::__construct($definition, $name, $parent);
    
    $this->fieldManager = \Drupal::service('entity_field.manager');
  }
  
  public static function defaultFieldSettings() {
    return [
      'field' => NULL,
    ] + parent::defaultFieldSettings();
  }
  
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $own_definition = $this
      ->getFieldDefinition();
    
    $definitions = $this->fieldManager
      ->getFieldDefinitions($own_definition
      ->getTargetEntityTypeId(), $own_definition
      ->getTargetBundle());
    $own_name = $this
      ->getFieldDefinition()
      ->getName();
    $options = [];
    foreach ($definitions as $field_name => $definition) {
      if ($definition instanceof FieldConfigInterface && $field_name != $own_name) {
        $options[$field_name] = $definition
          ->label();
      }
    }
    $element['field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Field to be formatted'),
      '#default_value' => $this
        ->getSetting('field'),
      '#required' => TRUE,
      '#options' => $options,
      '#description' => $this
        ->t('The field to be formatted using the settings in this field.'),
    ];
    return $element;
  }
  
  public function isEmpty() {
    return empty($this
      ->get('type')
      ->getValue());
  }
  
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['type'] = DataDefinition::create('string')
      ->setLabel(t('Formatter'));
    $properties['settings'] = DataDefinition::create('any')
      ->setLabel(t('Formatter settings'));
    return $properties;
  }
  
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema['columns'] = [
      'type' => [
        'type' => 'varchar',
        'not null' => FALSE,
        'description' => 'Formatter type',
        'length' => 64,
      ],
      'settings' => [
        'type' => 'text',
        'size' => 'big',
        'not null' => FALSE,
      ],
    ];
    return $schema;
  }
}