PHP API
Modules can show announcements somewhere else, such as on a dashboard, with the
Drupal\platform_announcements\PlatformAnnouncements service. It's autowired,
so inject it by its class name.
build(): array
Returns a render array for the announcements list
(platform-announcements.html.twig), with the module's library and the
settings' cache tags and max-age. The Announcements page and the block use it.
When the feed can't be fetched or isn't a JSON Feed, it logs the error and throws an exception, so each caller chooses what to show instead:
buildError()returns core's Announcements module's error message, "An error occurred while parsing the announcements feed, check the logs for more information.", cached for at most five minutes (ERROR_MAX_AGE). The Announcements page and the toolbar's dialog show it.- The block shows nothing, with
buildError()'s cache metadata, since visitors can't act on the error.
The error is part of the render array, as in core, rather than added with the messenger: dialog responses don't render the messenger's messages, so they'd only show on the next page.
use Drupal\platform_announcements\PlatformAnnouncements;
public function __construct(
protected readonly PlatformAnnouncements $platformAnnouncements,
) {}
public function dashboard(): array {
try {
return ['announcements' => $this->platformAnnouncements->build()];
}
catch (\Exception) {
// The error is logged.
return ['announcements' => $this->platformAnnouncements->buildError()];
}
}
Check the "access platform announcements" permission before showing it, as the block and the page do.
fetch(bool $force = FALSE): array
Returns the announcements as Drupal\platform_announcements\Announcement
objects, from the cache or the feed: up to the limit setting, featured ones
first. It returns an empty array when no feed URL is set, and logs the error
and throws an exception when the feed can't be fetched or isn't a JSON Feed, as
core's AnnounceFetcher::fetch() does. Pass TRUE to
fetch the feed even when it's cached.
Each Announcement has read-only id, title, url, contentHtml,
published, modified (timestamps) and featured properties. See the
feed format for where they come from.