Last active
May 6, 2023 07:14
-
-
Save drubb/dddb9af69a9d566c6f25becce6272d53 to your computer and use it in GitHub Desktop.
Backlinks with bundle class and Twig: Editorship bundle class providing a getter for all series nodes referencing the editorship entity, and Twig Template using this getter to render the series nodes below the editorship as backlinks. Uses the Twig Tweak module!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\frs_entities\Entity\Bundle; | |
use Drupal\Core\Field\FieldItemList; | |
/** | |
* A bundle class for node entities. | |
* | |
* @property FieldItemList $field_content | |
* @property FieldItemList $field_teaser | |
*/ | |
class EditorshipBundle extends NodeBundle { | |
/** | |
* Find all series entities referencing this editorship. | |
* | |
* @return array | |
* The series nodes referencing this editorship, if any. | |
*/ | |
public function getSeries(): array { | |
// Find the ids of all series entities referencing this editorship. | |
$ids = \Drupal::entityQuery('node') | |
->condition('type', 'series') | |
->condition('field_editorship', $this->id()) | |
->condition('status', 1) | |
->condition('field_discontinued', TRUE, '<>') | |
->sort('title') | |
->accessCheck(FALSE) | |
->execute(); | |
// Return the loaded entities, or an empty array if none were found. | |
return empty($ids) ? [] : self::loadMultiple($ids); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{ include('node.html.twig') }} | |
{{ {'#cache': {tags: ['node_list:series']}} }} | |
{% set series = node.getSeries() %} | |
{% if series is not empty %} | |
<h2>Series of this editorship</h2> | |
{% for series in node.getSeries() %} | |
<article> | |
<h3>{{ series|entity_link }}</h3> | |
<p>{{ series.field_teaser|view }}</p> | |
</article> | |
{% endfor %} | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a solution:
It's possible to add custom cache tags in a twig template, this way:
{{ {'#cache': {tags: ['node_list:series']}} }}
Now the cache will be invalidated whenever a series node is added, changed or deleted!