Skip to content

Instantly share code, notes, and snippets.

@d0t15t
Last active August 19, 2021 13:17
Show Gist options
  • Save d0t15t/3b46b1d9fa06b43626f5ed422f2700b7 to your computer and use it in GitHub Desktop.
Save d0t15t/3b46b1d9fa06b43626f5ed422f2700b7 to your computer and use it in GitHub Desktop.
Drupal computed field example
<?php
namespace Drupal\my_module\Fields;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
use Drupal\Core\Url;
class MenuTeasers extends EntityReferenceFieldItemList {
use ComputedItemListTrait;
/**
* Computes the field value.
*/
protected function computeValue() {
$context = $this->getEntity();
$link = $context->get('link')->getValue();
if (empty($link[0]['uri'])) {
return;
}
$url = Url::fromUri($link[0]['uri']);
if ($url->isRouted()) {
$params = $url->getRouteParameters();
$entity = NULL;
$entity_type = key($params);
if ($entity_type) {
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
}
if (!is_null($entity)) {
$language_manager = \Drupal::languageManager();
$priorities = [];
if (!empty($context)) {
if (!empty($context->getFields()['langcode'])) {
$context_language = $context->getFields()['langcode']->language;
$priorities[] = $context_language;
} elseif (!empty($context->getFields()['language'])) {
$context_language = $context->getFields()['language']->language;
$priorities[] = $context_language;
}
}
$priorities[] = $language_manager->getDefaultLanguage();
$priorities[] = $language_manager->getCurrentLanguage();
$priorities+= $entity->getTranslationLanguages();
foreach ($priorities as $priority) {
if ($entity->hasTranslation($priority->getId())) {
$translation = $entity->getTranslation($priority->getId());
if ($translation instanceof EntityPublishedInterface && !$translation->isPublished()) {
// link published check
continue;
}
if ($translation->hasField('field_menu_teaser_enabled')) {
$this->list[0] = $this->createItem(0, [
'target_id' => $translation->id(),
]);
}
break;
}
}
}
}
}
}
<?php
function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
if ($entity_type->id() == 'menu_link_content') {
$fields['teasers'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Teasers reference'))
->setDescription(t('Field value is managed by the \'USU API\'-module.'))
->setComputed(TRUE)
->setClass('\\Drupal\\my_module\\Fields\\MenuTeasers')
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
->setName('teasers') # Important for multi-lang sites.
->setTargetEntityTypeId('menu_link_content') # Important for multi-lang sites.
->setSettings(array(
'target_type' => 'node',
'default_value' => 0,
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment