oliverdavies.uk/source/_zets/32.md

61 lines
1.3 KiB
Markdown
Raw Normal View History

2025-08-04 01:09:00 +01:00
---
title: Drupal Bundle classes
date: 2025-07-12 23:25:52
tags:
- drupal
- php
---
By overridding a given bundle type:
```php
<?php
// modules/opd_presentations/opd_presentations.module
function opd_presentations_entity_bundle_info_alter(array &$bundles): void {
if (isset($bundles['node'])) {
$bundles['node'][Presentation::NODE_TYPE]['class'] = Presentation::class;
}
if (isset($bundles['paragraph'])) {
$bundles['paragraph'][Event::PARAGRAPH_TYPE]['class'] = Event::class;
}
}
```
I can write my own bundle classes that extend `Node`, `Paragraph`, etc, with its own custom methods and behaviour.
```php
<?php
// modules/opd_presentations/src/Presentation.php
declare(strict_types=1);
namespace Drupal\opd_presentations;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\paragraphs\ParagraphInterface;
final class Event extends Paragraph implements ParagraphInterface {
public const PARAGRAPH_TYPE = 'event';
public function getEventDate(): string {
/** @var non-empty-string */
return $this->get('field_date')->value;
}
public function getEventName(): string {
/** @var non-empty-string */
return $this->get('field_event_name')->value;
}
public function isPast(): bool {
return $this->getEventDate() < strtotime('today');
}
}
```