Skip to content

Commit

Permalink
add a computed field example for obtaining situation updates for banners
Browse files Browse the repository at this point in the history
  • Loading branch information
alexfinnarn committed Jan 17, 2024
1 parent 1b6c870 commit 8e09dc3
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Drupal\va_gov_api\Field;

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
* Provides a computed breadcrumbs field item list.
*/
class ComputedSituationUpdatesItemList extends FieldItemList {

use ComputedItemListTrait;

/**
* {@inheritdoc}
*/
protected function computeValue() {
$parent = $this->getEntity();
if ($parent->isNew()) {
return;
}

// Get paragraph ids from 'field_situation_updates' field.
$situation_updates = $parent->get('field_situation_updates')->getValue();
$situation_update_ids = array_column($situation_updates, 'target_id');

// Load paragraph entities.
$paragraphs = \Drupal::entityTypeManager()
->getStorage('paragraph')
->loadMultiple($situation_update_ids);

foreach ($paragraphs as $key => $paragraph) {
$paragraphData = [
'revision_id' => $paragraph->getRevisionId(),
'paragraph_type' => $paragraph->getType(),
'uuid' => $paragraph->uuid(),
'field_datetime_range_timezone' => $paragraph->get('field_datetime_range_timezone')
->getValue()[0],
'field_send_email_to_subscribers' => $paragraph->get('field_send_email_to_subscribers')
->getValue()[0],
'field_wysiwyg' => $paragraph->get('field_wysiwyg')->getValue()[0],
];

$this->list[$key] = $this->createItem($key, $paragraphData);
}
}

}
29 changes: 29 additions & 0 deletions docroot/modules/custom/va_gov_api/va_gov_api.module
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

/**
* @file
* Defines the hooks for va_gov_api module.
*/

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;

/**
* Implements hook_entity_bundle_field_info().
*
* The hook_event_dispatcher module has this hook listed as a todo.
*
* @see core_event_dispatcher.module#L26
*/
function va_gov_api_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
if ($bundle === 'full_width_banner_alert') {
$base_field_definitions['computed_situations_updates'] = BaseFieldDefinition::create('map')
->setName('computed_situations_updates')
->setLabel(t('Computed Situation Updates'))
->setComputed(TRUE)
->setClass('\Drupal\va_gov_api\Field\ComputedSituationUpdatesItemList')
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
}
return $base_field_definitions;
}

0 comments on commit 8e09dc3

Please sign in to comment.