Skip to content
Snippets Groups Projects
Commit 59e83875 authored by Joshua Bolduc's avatar Joshua Bolduc
Browse files

Initial commit

parents
No related branches found
Tags 7.x-1.3 7x-1.3
No related merge requests found
Showing
with 1110 additions and 0 deletions
INTRODUCTION
------------
Alert Types gives you the ability display different types of alerts anywhere
on your site.
Some of the major features include:
* The ability to define different alert types using Drupal’s bundle system.
* Each alert type is fieldable allowing you to extend it to create your own functionality.
* Drag and drop functionality allowing you to prioritize each alert.
* Optional user dismiss or auto dismiss.
* Visibility rules supporting paths, bundles or roles.
All the alerts are placed on your site via a block so that it can appear anywhere you want. Alerts are rendered via AJAX and accommodate cache contexts and paths. When an alert is dismissed that gets stored as a cookie in the user’s browser so that it won’t appear again.
REQUIREMENTS
------------
This module requires no modules outside of Drupal core.
name: 'Alert Types'
type: module
description: 'Provides the ability to create and prioritize different alerts.'
core: 8.x
package: Alerts
alerts:
js:
js/alert_types.alerts.js: {}
dependencies:
- core/jquery
- core/jquery.cookie
- core/jquery.once
- core/drupal
entity.alert.add_form:
route_name: entity.alert.add_page
title: 'Add Alert'
appears_on:
- entity.alert.collection
entity.alert_type.add_form:
route_name: entity.alert_type.add_form
title: 'Add Alert type'
appears_on:
- entity.alert_type.collection
entity.alert.collection:
title: 'Alerts'
route_name: entity.alert.collection
description: 'List Alerts'
parent: system.admin_content
weight: 100
entity.alert_type.collection:
title: 'Alert types'
route_name: entity.alert_type.collection
description: 'Create and manage fields, forms and display settings for your alerts.'
parent: system.admin_structure
weight: 99
entity.alert_type.edit_form:
title: 'Edit'
route_name: entity.alert_type.edit_form
base_route: entity.alert_type.edit_form
entity.alert.collection:
route_name: entity.alert.collection
base_route: system.admin_content
title: 'Alerts'
entity.alert.canonical:
route_name: entity.alert.canonical
base_route: entity.alert.canonical
title: 'View'
entity.alert.edit_form:
route_name: entity.alert.edit_form
base_route: entity.alert.canonical
title: 'Edit'
entity.alert.version_history:
route_name: entity.alert.version_history
base_route: entity.alert.canonical
title: 'Revisions'
entity.alert.delete_form:
route_name: entity.alert.delete_form
base_route: entity.alert.canonical
title: Delete
weight: 10
<?php
/**
* @file
* Contains alert_types.module.
*/
/**
* Implements hook_theme().
*/
function alert_types_theme() {
$theme = [];
$theme['alert_block'] = [
'render element' => 'elements',
];
$theme['alert'] = [
'render element' => 'elements',
'file' => 'alert_types.page.inc',
'template' => 'alert',
];
return $theme;
}
/**
* Implements hook_preprocess_alert().
*/
function alert_types_preprocess_alert(&$variables) {
$alert = $variables['elements']['#alert'];
// Pass the alert entity to the template.
$variables['alert'] = $alert;
// Process the dismiss_timer value. Need to ensure that it returns
// its value as an integer.
if (!empty($alert->get('dismiss_timer')->first())) {
$dismiss = $alert->get('dismiss_timer')->first()->getValue();
if (!empty($dismiss['value'])) {
$variables['dismiss_timer'] = intval($dismiss['value']);
}
}
// Process the dismissable value. Need to ensure that it returns
// its value as boolean.
if (!empty($alert->get('dismissable')->first())) {
$dismissable = $alert->get('dismissable')->first()->getValue();
if (!empty($dismissable['value'])) {
$variables['dismissable'] = TRUE;
}
}
// Add attributes. This is necessary for javascript.
$variables['attributes']['class'] = 'alert';
$variables['attributes']['id'] = 'alert--' . $alert->id();
$variables['attributes']['data-dismiss-timer'] = $alert->get('dismiss_timer')->value;
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function alert_types_theme_suggestions_alert(array $variables) {
$suggestions = [];
$entity = $variables['elements']['#alert'];
$sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
$suggestions[] = 'alert__' . $sanitized_view_mode;
$suggestions[] = 'alert__' . $entity->bundle();
$suggestions[] = 'alert__' . $entity->bundle() . '__' . $sanitized_view_mode;
$suggestions[] = 'alert__' . $entity->id();
$suggestions[] = 'alert__' . $entity->id() . '__' . $sanitized_view_mode;
return $suggestions;
}
<?php
/**
* @file
* Contains alert_types.page.inc.
*
* Page callback for Alert entities.
*/
use Drupal\Core\Render\Element;
/**
* Prepares variables for Alert templates.
*
* Default template: alert.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the user information and any
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_alert(array &$variables) {
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
add alert entities:
title: 'Create new Alert entities'
administer alert entities:
title: 'Administer Alert entities'
description: 'Allow to access the administration form to configure Alert entities.'
restrict access: true
delete alert entities:
title: 'Delete Alert entities'
edit alert entities:
title: 'Edit Alert entities'
view published alert entities:
title: 'View published Alert entities'
view unpublished alert entities:
title: 'View unpublished Alert entities'
view all alert revisions:
title: 'View all Alert revisions'
revert all alert revisions:
title: 'Revert all Alert revisions'
description: 'Role requires permission <em>view Alert revisions</em> and <em>edit rights</em> for alert entities in question or <em>administer alert entities</em>.'
delete all alert revisions:
title: 'Delete all revisions'
description: 'Role requires permission to <em>view Alert revisions</em> and <em>delete rights</em> for alert entities in question or <em>administer alert entities</em>.'
alerts.json:
path: '/alerts/json'
defaults:
_controller: '\Drupal\alert_types\Controller\AlertServiceController::json'
requirements:
_permission: 'access content'
alerts.alert_type.*:
type: config_entity
label: 'Alert type config'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
description:
type: text
label: 'Description'
uuid:
type: string
/**
* @file
**/
(function ($, window, Drupal, cookies) {
Drupal.Alerts = {};
Drupal.behaviors.AlertsService = {
attach: function attach(context, settings) {
// Run this script only once.
$('main', context).once('#alerts').each(function() {
var path = "/" + drupalSettings.path.currentPath;
var params = {
'_format':'json',
'path': path,
};
var query = $.param(params, true);
var url = window.location.protocol + "//" + window.location.host + '/alerts/json?' + query;
$.ajax({
url: url,
method: "GET",
headers: {
'Content-Type': "application/vnd.api+json",
'Accept': 'application/vnd.api+json"',
},
success: function(data, status, xhr) {
data.some(function (item) {
if (drupalSettings.alerts.includes(item.id)) {
var cookieName = 'alert--' + item.id;
// Check to see if user has no cookie set for this alert or if
// they have not yet dismissed it.
var show = (!cookies.get(cookieName) || cookies.get(cookieName) === 'shown');
// Add alert if it has rendered content and has not been dismissed.
if (item.content && show) {
$('#alerts').append(item.content);
return true;
}
}
});
},
complete: function(xhr, status) {
$(context).find('.alert').once('setupAlerts').each(function(i, e) {
let a = new Drupal.Alerts.Alert(e);
});
}
});
});
}
}
Drupal.Alerts.Alert = function ($target) {
this.$el = $($target)
this.$closeButton = this.$el.find('.alert--close')
this.dismissTimer = this.$el.data('dismiss-timer')
this.cookieName = this.$el.attr('id')
this.speed = 500
var self = this;
this.close = function() {
self.$el.slideUp(this.speed, function(e) {
cookies.set(self.cookieName, 'dismissed')
});
}
this.open = function() {
self.$el.slideDown(this.speed, function(e) {
cookies.set(self.cookieName, 'shown')
});
}
this.$closeButton.on('click', function(e) {
e.preventDefault();
self.close()
});
if (!cookies.get(this.cookieName) || cookies.get(this.cookieName) === 'shown') {
self.open()
}
if (this.dismissTimer > 0) {
setTimeout( function() {
self.close()
}, (this.dismissTimer * 1000))
}
}
})(jQuery, window, Drupal, window.Cookies);
<?php
namespace Drupal\alert_types;
use Drupal\Component\Plugin\Exception\ContextException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Condition\ConditionAccessResolverTrait;
use Drupal\Core\Condition\ConditionManager;
use Drupal\Core\Condition\ConditionPluginCollection;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Plugin\Context\ContextHandler;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
/**
* Access controller for the Alert entity.
*
* @see \Drupal\alert_types\Entity\Alert.
*/
class AlertAccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {
use ConditionAccessResolverTrait;
/**
* The condition manager.
*
* @var \Drupal\Core\Condition\ConditionManager
*/
protected $conditionManager;
/**
* The context handler.
*
* @var \Drupal\Core\Plugin\Context\ContextHandler
*/
protected $contextHandler;
/**
* The context repository.
*
* @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
*/
protected $contextRepository;
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('plugin.manager.condition'),
$container->get('context.handler'),
$container->get('context.repository')
);
}
/**
* AlertAccessControlHandler constructor.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Condition\ConditionManager $condition_manager
* The condition plugin manager.
* @param \Drupal\Core\Plugin\Context\ContextHandler $contxt_handler
* The context handler.
* @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
* The context repository.
*/
public function __construct(EntityTypeInterface $entity_type, ConditionManager $condition_manager, ContextHandler $context_handler, ContextRepositoryInterface $context_repository) {
parent::__construct($entity_type);
$this->conditionManager = $condition_manager;
$this->contextHandler = $context_handler;
$this->contextRepository = $context_repository;
}
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
switch ($operation) {
case 'view':
if (!$entity->isPublished()) {
return AccessResult::allowedIfHasPermission($account, 'view unpublished alert entities');
}
else {
$conditions = [];
if ($entity->getConditions()) {
$conditionCollection = new ConditionPluginCollection($this->conditionManager, $entity->getConditions());
foreach ($conditionCollection as $condition_id => $condition) {
if ($condition instanceof ContextAwarePluginInterface) {
try {
$contexts = $this->contextRepository->getRuntimeContexts(array_values($condition->getContextMapping()));
$this->contextHandler->applyContextMapping($condition, $contexts);
} catch (ContextException $e) {
}
}
$conditions[$condition_id] = $condition;
}
}
// TODO: Add support for OR.
$allowed = $this->resolveConditions($conditions, 'and');
$access = $allowed ? AccessResult::allowed() : AccessResult::forbidden();
$this->mergeCacheabilityFromConditions($access, $conditions);
return $access->addCacheableDependency($entity);
}
case 'update':
return AccessResult::allowedIfHasPermission($account, 'edit alert entities');
case 'delete':
return AccessResult::allowedIfHasPermission($account, 'delete alert entities');
}
return AccessResult::neutral();
}
/**
* Merges cacheable metadata from conditions onto the access result object.
*
* @param \Drupal\Core\Access\AccessResult $access
* The access result object.
* @param \Drupal\Core\Condition\ConditionInterface[] $conditions
* List of conditions conditions.
*/
protected function mergeCacheabilityFromConditions(AccessResult $access, array $conditions) {
foreach ($conditions as $condition) {
if ($condition instanceof CacheableDependencyInterface) {
$access->addCacheTags($condition->getCacheTags());
$access->addCacheContexts($condition->getCacheContexts());
$access->setCacheMaxAge(Cache::mergeMaxAges($access->getCacheMaxAge(), $condition->getCacheMaxAge()));
}
}
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
return AccessResult::allowedIfHasPermission($account, 'add alert entities');
}
}
<?php
namespace Drupal\alert_types;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Symfony\Component\Routing\Route;
/**
* Provides routes for Alert entities.
*
* @see \Drupal\Core\Entity\Routing\AdminHtmlRouteProvider
* @see \Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider
*/
class AlertHtmlRouteProvider extends AdminHtmlRouteProvider {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = parent::getRoutes($entity_type);
$entity_type_id = $entity_type->id();
if ($history_route = $this->getHistoryRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.version_history", $history_route);
}
if ($revision_route = $this->getRevisionRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.revision", $revision_route);
}
if ($revert_route = $this->getRevisionRevertRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.revision_revert", $revert_route);
}
if ($delete_route = $this->getRevisionDeleteRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.revision_delete", $delete_route);
}
if ($translation_route = $this->getRevisionTranslationRevertRoute($entity_type)) {
$collection->add("{$entity_type_id}.revision_revert_translation_confirm", $translation_route);
}
if ($settings_form_route = $this->getSettingsFormRoute($entity_type)) {
$collection->add("$entity_type_id.settings", $settings_form_route);
}
return $collection;
}
/**
* Gets the version history route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getHistoryRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('version-history')) {
$route = new Route($entity_type->getLinkTemplate('version-history'));
$route
->setDefaults([
'_title' => "{$entity_type->getLabel()} revisions",
'_controller' => '\Drupal\alert_types\Controller\AlertController::revisionOverview',
])
->setRequirement('_permission', 'access alert revisions')
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the revision route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getRevisionRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('revision')) {
$route = new Route($entity_type->getLinkTemplate('revision'));
$route
->setDefaults([
'_controller' => '\Drupal\alert_types\Controller\AlertController::revisionShow',
'_title_callback' => '\Drupal\alert_types\Controller\AlertController::revisionPageTitle',
])
->setRequirement('_permission', 'access alert revisions')
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the revision revert route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getRevisionRevertRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('revision_revert')) {
$route = new Route($entity_type->getLinkTemplate('revision_revert'));
$route
->setDefaults([
'_form' => '\Drupal\alert_types\Form\AlertRevisionRevertForm',
'_title' => 'Revert to earlier revision',
])
->setRequirement('_permission', 'revert all alert revisions')
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the revision delete route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getRevisionDeleteRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('revision_delete')) {
$route = new Route($entity_type->getLinkTemplate('revision_delete'));
$route
->setDefaults([
'_form' => '\Drupal\alert_types\Form\AlertRevisionDeleteForm',
'_title' => 'Delete earlier revision',
])
->setRequirement('_permission', 'delete all alert revisions')
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the revision translation revert route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getRevisionTranslationRevertRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('translation_revert')) {
$route = new Route($entity_type->getLinkTemplate('translation_revert'));
$route
->setDefaults([
'_form' => '\Drupal\alert_types\Form\AlertRevisionRevertTranslationForm',
'_title' => 'Revert to earlier revision of a translation',
])
->setRequirement('_permission', 'revert all alert revisions')
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the settings form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getSettingsFormRoute(EntityTypeInterface $entity_type) {
if (!$entity_type->getBundleEntityType()) {
$route = new Route("/admin/structure/{$entity_type->id()}/settings");
$route
->setDefaults([
'_form' => 'Drupal\alert_types\Form\AlertSettingsForm',
'_title' => "{$entity_type->getLabel()} settings",
])
->setRequirement('_permission', $entity_type->getAdminPermission())
->setOption('_admin_route', TRUE);
return $route;
}
}
}
<?php
namespace Drupal\alert_types;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Render\RendererInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Defines a class to build a listing of Alert entities.
*
* @ingroup alert_types
*/
class AlertListBuilder extends EntityListBuilder implements FormInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entities being listed.
*
* @var \Drupal\Core\Entity\EntityInterface[]
*/
protected $entities = [];
/**
* The term storage handler.
*
* @var \Drupal\taxonomy\TermStorageInterface
*/
protected $storageController;
/**
* The renderer service.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The form builder.
*
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* Constructs an AlertListForm object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity manager service.
* @param \Drupal\Core\Render\RendererInterface|null $renderer
* The renderer service.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
*/
public function __construct(EntityTypeInterface $entity_type, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer = NULL) {
parent::__construct($entity_type, $entity_type_manager->getStorage($entity_type->id()));
$this->entityTypeManager = $entity_type_manager;
$this->storageController = $entity_type_manager->getStorage('alert');
$this->renderer = $renderer;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('entity_type.manager'),
$container->get('renderer')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'alerts_alerts_list';
}
/**
* {@inheritdoc}
*/
public function render() {
return $this->formBuilder()->getForm($this);
}
/**
* Load alerts sorted by weight.
*
* @return array
* Return an array of alert entities.
*/
public function load() {
$query = $this->storageController->getQuery();
$entity_ids = $query->sort('weight', 'asc')
->execute();
$entities = $this->storageController->loadMultiple($entity_ids);
return $entities;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Fetching all the alerts sorted by weight.
$this->entities = $this->load();
// Build draggable table.
$form['alerts'] = [
'#type' => 'table',
'#header' => $this->buildHeader(),
'#empty' => ['#markup' => $this->t('No Alerts Found.')],
'#attributes' => [
'id' => 'alerts',
],
'#tabledrag' => [
[
'action' => 'order',
'relationship' => 'sibling',
'group' => 'weight',
],
],
];
if (!empty($this->entities)) {
foreach ($this->entities as $alert) {
$form['alerts'][$alert->id()] = $this->buildRow($alert);
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => t('Save'),
'#button_type' => 'primary',
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function buildHeader() {
return [
'label' => $this->t('Name'),
'type' => $this->t('Alert Type'),
'status' => $this->t('Status'),
'changed' => $this->t('Updated'),
'weight' => $this->t('Weight'),
'operations' => $this->t('Operations'),
];
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/* @var $entity \Drupal\alert_types\Entity\Alert */
$row['#attributes']['class'][] = 'draggable';
$row['#weight'] = $entity->getWeight();
$row['label'] = ['#markup' => $entity->label()];
$row['type'] = ['#markup' => $entity->bundle()];
$row['status'] = ['#markup' => $entity->isPublished() ? $this->t('Published') : $this->t('Unpublished')];
$row['changed'] = ['#markup' => format_date($entity->getChangedTime(), 'short')];
// Add weight column.
$row['weight'] = [
'#type' => 'weight',
'#title' => t('Weight for @title', ['@title' => $entity->label()]),
'#title_display' => 'invisible',
'#default_value' => $entity->getWeight(),
'#attributes' => ['class' => ['weight']],
];
return $row + parent::buildRow($entity);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Intentionally left blank.
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
foreach ($form_state->getValue('alerts') as $id => $value) {
if (isset($this->entities[$id]) && $this->entities[$id]->getWeight() != $value['weight']) {
// Save entity only when its weight was changed.
$this->entities[$id]->setWeight($value['weight']);
$this->entities[$id]->save();
}
}
}
/**
* Returns the form builder.
*
* @return \Drupal\Core\Form\FormBuilderInterface
* The form builder.
*/
protected function formBuilder() {
if (!$this->formBuilder) {
$this->formBuilder = \Drupal::formBuilder();
}
return $this->formBuilder;
}
}
<?php
namespace Drupal\alert_types;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\alert_types\Entity\AlertInterface;
/**
* Defines the storage handler class for Alert entities.
*
* This extends the base storage class, adding required special handling for
* Alert entities.
*
* @ingroup alert_types
*/
class AlertStorage extends SqlContentEntityStorage implements AlertStorageInterface {
/**
* {@inheritdoc}
*/
public function revisionIds(AlertInterface $entity) {
return $this->database->query(
'SELECT vid FROM {alert_revision} WHERE id=:id ORDER BY vid',
[':id' => $entity->id()]
)->fetchCol();
}
/**
* {@inheritdoc}
*/
public function userRevisionIds(AccountInterface $account) {
return $this->database->query(
'SELECT vid FROM {alert_field_revision} WHERE uid = :uid ORDER BY vid',
[':uid' => $account->id()]
)->fetchCol();
}
/**
* {@inheritdoc}
*/
public function countDefaultLanguageRevisions(AlertInterface $entity) {
return $this->database->query('SELECT COUNT(*) FROM {alert_field_revision} WHERE id = :id AND default_langcode = 1', [':id' => $entity->id()])
->fetchField();
}
/**
* {@inheritdoc}
*/
public function clearRevisionsLanguage(LanguageInterface $language) {
return $this->database->update('alert_revision')
->fields(['langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED])
->condition('langcode', $language->getId())
->execute();
}
}
<?php
namespace Drupal\alert_types;
use Drupal\Core\Entity\ContentEntityStorageInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\alert_types\Entity\AlertInterface;
/**
* Defines the storage handler class for Alert entities.
*
* This extends the base storage class, adding required special handling for
* Alert entities.
*
* @ingroup alert_types
*/
interface AlertStorageInterface extends ContentEntityStorageInterface {
/**
* Gets a list of Alert revision IDs for a specific Alert.
*
* @param \Drupal\alert_types\Entity\AlertInterface $entity
* The Alert entity.
*
* @return int[]
* Alert revision IDs (in ascending order).
*/
public function revisionIds(AlertInterface $entity);
/**
* Gets a list of revision IDs having a given user as Alert author.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The user entity.
*
* @return int[]
* Alert revision IDs (in ascending order).
*/
public function userRevisionIds(AccountInterface $account);
/**
* Counts the number of revisions in the default language.
*
* @param \Drupal\alert_types\Entity\AlertInterface $entity
* The Alert entity.
*
* @return int
* The number of revisions in the default language.
*/
public function countDefaultLanguageRevisions(AlertInterface $entity);
/**
* Unsets the language for all Alert with the given language.
*
* @param \Drupal\Core\Language\LanguageInterface $language
* The language object.
*/
public function clearRevisionsLanguage(LanguageInterface $language);
}
<?php
namespace Drupal\alert_types;
use Drupal\content_translation\ContentTranslationHandler;
/**
* Defines the translation handler for alert.
*/
class AlertTranslationHandler extends ContentTranslationHandler {
// Override here the needed methods from ContentTranslationHandler.
}
<?php
namespace Drupal\alert_types;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
/**
* Provides routes for Alert type entities.
*
* @see Drupal\Core\Entity\Routing\AdminHtmlRouteProvider
* @see Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider
*/
class AlertTypeHtmlRouteProvider extends AdminHtmlRouteProvider {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = parent::getRoutes($entity_type);
// Provide your custom entity routes here.
return $collection;
}
}
<?php
namespace Drupal\alert_types;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides a listing of Alert type entities.
*/
class AlertTypeListBuilder extends ConfigEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Name');
$header['description'] = $this->t('Description');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row['label'] = $entity->label();
$row['description']['data'] = ['#markup' => $entity->getDescription()];
return $row + parent::buildRow($entity);
}
/**
* {@inheritdoc}
*/
public function getDefaultOperations(EntityInterface $entity) {
/** @var \Drupal\field\FieldConfigInterface $entity */
$operations = parent::getDefaultOperations($entity);
if (isset($operations['edit'])) {
$operations['edit']['weight'] = 30;
}
return $operations;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment