ShapeItem.php 2.12 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\field_test\Plugin\Field\FieldType\ShapeItem.
6 7
 */

8
namespace Drupal\field_test\Plugin\Field\FieldType;
9

10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\TypedData\DataDefinition;
12
use Drupal\Core\Field\FieldItemBase;
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

/**
 * Defines the 'shape_field' entity field item.
 *
 * @FieldType(
 *   id = "shape",
 *   label = @Translation("Shape"),
 *   description = @Translation("Another dummy field type."),
 *   settings = {
 *     "foreign_key_name" = "shape"
 *   },
 *   default_widget = "test_field_widget",
 *   default_formatter = "field_test_default"
 * )
 */
28
class ShapeItem extends FieldItemBase {
29 30 31 32

  /**
   * {@inheritdoc}
   */
33 34 35 36 37 38 39 40
  public static function propertyDefinitions(FieldDefinitionInterface $field_definition) {
    $properties['shape'] = DataDefinition::create('string')
      ->setLabel(t('Shape'));

    $properties['color'] = DataDefinition::create('string')
      ->setLabel(t('Color'));

    return $properties;
41 42 43 44 45
  }

  /**
   * {@inheritdoc}
   */
46
  public static function schema(FieldDefinitionInterface $field_definition) {
47 48
    $foreign_keys = array();
    // The 'foreign keys' key is not always used in tests.
49
    if ($field_definition->getSetting('foreign_key_name')) {
50 51 52
      $foreign_keys['foreign keys'] = array(
        // This is a dummy foreign key definition, references a table that
        // doesn't exist, but that's not a problem.
53 54 55
        $field_definition->getSetting('foreign_key_name') => array(
          'table' => $field_definition->getSetting('foreign_key_name'),
          'columns' => array($field_definition->getSetting('foreign_key_name') => 'id'),
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        ),
      );
    }
    return array(
      'columns' => array(
        'shape' => array(
          'type' => 'varchar',
          'length' => 32,
          'not null' => FALSE,
        ),
        'color' => array(
          'type' => 'varchar',
          'length' => 32,
          'not null' => FALSE,
        ),
      ),
    ) + $foreign_keys;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $item = $this->getValue();
    return empty($item['shape']) && empty($item['color']);
  }

}