Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
85.71% |
18 / 21 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
ComputedRelationshipContact | |
85.71% |
18 / 21 |
|
66.67% |
2 / 3 |
9.24 | |
0.00% |
0 / 1 |
computeValue | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
setValue | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
referencedEntities | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Drupal\crm\Field; |
6 | |
7 | use Drupal\Core\TypedData\ComputedItemListTrait; |
8 | use Drupal\Core\Field\FieldItemList; |
9 | use Drupal\Core\Field\EntityReferenceFieldItemListInterface; |
10 | |
11 | /** |
12 | * Computed field for the contact in a relationship. |
13 | */ |
14 | class ComputedRelationshipContact extends FieldItemList implements EntityReferenceFieldItemListInterface { |
15 | use ComputedItemListTrait; |
16 | |
17 | /** |
18 | * {@inheritdoc} |
19 | */ |
20 | protected function computeValue() { |
21 | $field_name = $this->getName(); |
22 | $entity = $this->getEntity(); |
23 | |
24 | $contacts = $entity->get('contacts')->getValue(); |
25 | $contact = $contacts[0]['target_id']; |
26 | if ($field_name === 'contact_b') { |
27 | $contact = $contacts[1]['target_id']; |
28 | } |
29 | |
30 | $this->list[0] = $this->createItem(0, ['target_id' => $contact]); |
31 | } |
32 | |
33 | /** |
34 | * {@inheritdoc} |
35 | */ |
36 | public function setValue($values, $notify = TRUE) { |
37 | |
38 | if (!empty($values)) { |
39 | $field_name = $this->getName(); |
40 | $entity = $this->getEntity(); |
41 | $contacts_field = $entity->get('contacts'); |
42 | |
43 | // Get current contacts. |
44 | $contacts = $contacts_field->getValue(); |
45 | |
46 | // Determine which contact to update based on field name. |
47 | $contact_index = ($field_name === 'contact_b') ? 1 : 0; |
48 | |
49 | // Ensure we have enough contacts in the array. |
50 | while (count($contacts) <= $contact_index) { |
51 | $contacts[] = ['target_id' => NULL]; |
52 | } |
53 | |
54 | // Update the appropriate contact. |
55 | $contacts[$contact_index]['target_id'] = is_array($values) ? $values[0]['target_id'] : $values; |
56 | |
57 | // Set the updated contacts field. |
58 | $contacts_field->setValue($contacts); |
59 | } |
60 | |
61 | // Call parent to maintain normal field behavior. |
62 | parent::setValue($values, $notify); |
63 | } |
64 | |
65 | /** |
66 | * {@inheritdoc} |
67 | */ |
68 | public function referencedEntities() { |
69 | $field_name = $this->getName(); |
70 | $entities = $this->getEntity()->get('contacts')->referencedEntities(); |
71 | return $field_name === 'contact_b' ? [$entities[1]] : [$entities[0]]; |
72 | } |
73 | |
74 | } |