Drupal Bundle classes
This commit is contained in:
parent
b70d6aed7a
commit
a6939bbe3c
1 changed files with 60 additions and 0 deletions
60
source/_zets/32.md
Normal file
60
source/_zets/32.md
Normal file
|
@ -0,0 +1,60 @@
|
||||||
|
---
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
Loading…
Add table
Add a link
Reference in a new issue