Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.92% covered (warning)
76.92%
10 / 13
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
PrimaryEntityReferenceItem
76.92% covered (warning)
76.92%
10 / 13
66.67% covered (warning)
66.67%
2 / 3
3.11
0.00% covered (danger)
0.00%
0 / 1
 propertyDefinitions
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 schema
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 generateSampleValue
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace Drupal\primary_entity_reference\Plugin\Field\FieldType;
4
5use Drupal\Core\Field\Attribute\FieldType;
6use Drupal\Core\Field\FieldDefinitionInterface;
7use Drupal\Core\Field\FieldStorageDefinitionInterface;
8use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
9use Drupal\Core\Field\PreconfiguredFieldUiOptionsInterface;
10use Drupal\Core\StringTranslation\TranslatableMarkup;
11use Drupal\Core\TypedData\OptionsProviderInterface;
12use Drupal\Core\TypedData\DataDefinition;
13use Drupal\primary_entity_reference\Plugin\Field\PrimaryEntityReferenceFieldItemList;
14
15/**
16 * Defines the 'primary_entity_reference' entity field type.
17 *
18 * Supported settings (below the definition's 'settings' key) are:
19 * - target_type: The entity type to reference. Required.
20 */
21#[FieldType(
22  id: "primary_entity_reference",
23  label: new TranslatableMarkup("Primary entity reference"),
24  description: new TranslatableMarkup("An entity reference field with one reference as primary."),
25  category: "reference",
26  default_widget: "primary_entity_reference_autocomplete",
27  default_formatter: "primary_entity_reference_label",
28  list_class: PrimaryEntityReferenceFieldItemList::class,
29)]
30class PrimaryEntityReferenceItem extends EntityReferenceItem implements OptionsProviderInterface, PreconfiguredFieldUiOptionsInterface {
31
32  /**
33   * {@inheritdoc}
34   */
35  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
36    $properties = parent::propertyDefinitions($field_definition);
37
38    $properties['primary'] = DataDefinition::create('boolean')
39      ->setLabel(t('Primary'));
40
41    return $properties;
42  }
43
44  /**
45   * {@inheritdoc}
46   */
47  public static function schema(FieldStorageDefinitionInterface $field_definition) {
48    $schema = parent::schema($field_definition);
49    $schema['columns']['primary'] = [
50      'type' => 'int',
51      'size' => 'tiny',
52    ];
53
54    return $schema;
55  }
56
57  /**
58   * {@inheritdoc}
59   */
60  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
61    $values = parent::generateSampleValue($field_definition);
62
63    $values['primary'] = (bool) mt_rand(0, 1);
64
65    return $values;
66  }
67
68}