opigno_certificate.module in Opigno certificate 3.x
Same filename and directory in other branches
Contains opigno_certificate.module.
File
opigno_certificate.moduleView source
<?php
/**
* @file
* Contains opigno_certificate.module.
*/
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Render\Element;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\AccessAwareRouterInterface;
use Drupal\opigno_certificate\FieldStorageDefinition;
use Drupal\editor\Entity\Editor;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\opigno_learning_path\Entity\LPStatus;
use Drupal\user\UserInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* Implements hook_entity_bundle_info().
*/
function opigno_certificate_entity_bundle_info() {
$bundles['opigno_certificate']['wysiwyg']['label'] = t('Wysiwyg');
$bundles['opigno_certificate']['template']['label'] = t('Template');
return $bundles;
}
/**
* Implements hook_entity_view_mode_alter().
*
* This hook was saved from module view_mode_selector.
*/
function opigno_certificate_entity_view_mode_alter(&$view_mode, EntityInterface $entity, $context) {
if ($view_mode !== 'view_mode_selector.') {
return;
}
// Set view mode to 'Default', this is for entities without
// a view mode selector field.
$view_mode = 'default';
// Find the first view mode selector field and change the view mode.
$fields = \Drupal::service('entity_field.manager')
->getFieldDefinitions($entity
->getEntityTypeId(), $entity
->bundle());
foreach ($fields as $field_name => $field) {
if ($field
->getType() == 'view_mode_selector' && ($field_value = $entity->{$field_name}->value)) {
$view_mode = $field_value;
break;
}
}
return $view_mode;
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function opigno_certificate_form_entity_view_display_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
/** @var \Drupal\field_ui\Form\EntityViewDisplayEditForm $form_object */
$form_object = $form_state
->getFormObject();
/** @var \Drupal\Core\Entity\Entity\EntityViewDisplay $view_display */
$view_display = $form_object
->getEntity();
if ($view_display
->getMode() == 'view_mode_selector') {
\Drupal::messenger()
->addMessage(t('This is a placeholder view mode from the <a href="@view-mode-selector">View Mode Selector</a> module. It will be replaced with a selected view mode.', [
'@view-mode-selector' => Url::fromUri('https://www.drupal.org/project/view_mode_selector')
->toUriString(),
]));
\Drupal::messenger()
->addWarning(t('The field settings have been disabled by the <a href="@view-mode-selector">View Mode Selector</a> module.', [
'@view-mode-selector' => Url::fromUri('https://www.drupal.org/project/view_mode_selector')
->toUriString(),
]));
$form['fields']['#disabled'] = TRUE;
}
}
/**
* Implements hook_entity_view_mode_info_alter().
*
* This hook was saved from module view_mode_selector.
*/
function opigno_certificate_entity_view_mode_info_alter(&$view_modes) {
// Load all view mode selector fields.
$storage = \Drupal::entityTypeManager()
->getStorage('field_config');
$field_ids = \Drupal::entityQuery('field_config')
->condition('field_type', 'view_mode_selector')
->execute();
$fields = $storage
->loadMultiple($field_ids);
// Create the extra fields which represent the field deltas.
/** @var \Drupal\field\Entity\FieldConfig $field */
foreach ($fields as $field) {
$entity_type = $field
->getTargetEntityTypeId();
// Load the view mode selector view mode and add it to the list.
$storage = \Drupal::entityTypeManager()
->getStorage('entity_view_mode');
$id = $entity_type . '.view_mode_selector';
$view_mode = $storage
->load($id);
if (!$view_mode) {
// Create the view mode if it does not exist.
$view_mode = $storage
->create([
'label' => t('View mode selector'),
'id' => $id,
'status' => true,
// must be true; see: drupal.org/node/2322503
'targetEntityType' => $entity_type,
], 'entity_view_mode');
$view_mode
->save();
}
$view_modes[$entity_type]['view_mode_selector'] = $view_mode
->toArray();
}
}
/**
* Implements hook_entity_field_storage_info().
*/
function opigno_certificate_entity_field_storage_info(EntityTypeInterface $entity_type) {
if ($entity_type
->id() == 'opigno_certificate') {
$fields['body'] = FieldStorageDefinition::create('text_long')
->setLabel(t('Body'))
->setName('body')
->setTargetEntityTypeId($entity_type
->id());
$fields['view_mode'] = FieldStorageDefinition::create('view_mode_selector')
->setLabel(t('View mode'))
->setName('view_mode')
->setTargetEntityTypeId($entity_type
->id());
return $fields;
}
}
/**
* Implements hook_entity_bundle_field_info().
*/
function opigno_certificate_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle) {
$fields = [];
if ($entity_type
->id() === 'opigno_certificate' && $bundle == 'wysiwyg') {
$fields['body'] = FieldStorageDefinition::create('text_long')
->setLabel(t('Body'))
->setRequired(TRUE)
->setCardinality(1)
->setTranslatable(FALSE)
->setTargetbundle($bundle)
->setDisplayOptions('form', [
'type' => 'text_textarea',
'label' => 'hidden',
'settings' => [
'placeholder' => t('Message'),
],
])
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'text_textfield',
'settings' => [],
'weight' => 0,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
}
if ($entity_type
->id() == 'opigno_certificate' && $bundle == 'template') {
return;
$fields['view_mode'] = FieldStorageDefinition::create('view_mode_selector')
->setLabel(t('View mode'))
->setRequired(TRUE)
->setCardinality(1)
->setTranslatable(FALSE)
->setTargetbundle($bundle)
->setDisplayOptions('form', [
'type' => 'opigno_certificate_view_mode_selector_select',
'label' => 'hidden',
'settings' => [],
])
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'hidden',
'settings' => [],
'weight' => 0,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', FALSE);
}
return $fields;
}
/**
* Implements hook_theme().
*/
function opigno_certificate_theme() {
return [
'opigno_certificate' => [
'render element' => 'elements',
],
];
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function opigno_certificate_theme_suggestions_opigno_certificate(array $variables) {
$suggestions = [];
/** @var \Drupal\opigno_certificate\OpignoCertificateInterface $opigno_certificate */
$opigno_certificate = $variables['elements']['#opigno_certificate'];
$view_mode = $variables['elements']['#view_mode'];
if ($view_mode == 'default') {
$view_mode = 'full';
}
$sanitized_view_mode = strtr($view_mode, '.', '_');
$suggestions[] = 'opigno_certificate__' . $sanitized_view_mode;
$suggestions[] = 'opigno_certificate__' . $opigno_certificate
->bundle();
$suggestions[] = 'opigno_certificate__' . $opigno_certificate
->bundle() . '__' . $sanitized_view_mode;
$suggestions[] = 'opigno_certificate__' . $opigno_certificate
->id();
$suggestions[] = 'opigno_certificate__' . $opigno_certificate
->id() . '__' . $sanitized_view_mode;
return $suggestions;
}
/**
* Implements template_preprocess_HOOK().
*/
function template_preprocess_opigno_certificate(array &$variables) {
// Get the actual user.
$user = NULL;
if (\Drupal::routeMatch()
->getRouteName() === 'certificate.entity.pdf') {
$referer = \Drupal::request()->server
->get('HTTP_REFERER');
$router = \Drupal::service('router');
if ($router instanceof AccessAwareRouterInterface) {
try {
$route_info = $router
->match($referer);
$user = $route_info['user'] ?? $user;
} catch (AccessDeniedHttpException $e) {
watchdog_exception('opigno_social_exception', $e);
}
}
}
$user = $user instanceof UserInterface ? $user : \Drupal::currentUser();
/** @var \Drupal\opigno_certificate\OpignoCertificateInterface $opigno_certificate */
$opigno_certificate = $variables['elements']['#opigno_certificate'];
/** @var \Drupal\Core\Entity\ContentEntityInterface $referencing_entity */
$referencing_entity = $opigno_certificate->referencing_entity->entity;
// Provide the referencing entity context.
if ($referencing_entity) {
$variables['referencing_entity'] = $referencing_entity;
if ($opigno_certificate
->getViewModeSelectorField()) {
$variables['content']['referencing_entity'] = [
'#markup' => $referencing_entity
->label(),
];
}
// Get the completion date.
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
$gid = (int) $referencing_entity
->id();
$uid = (int) $user
->id();
try {
$completed = opigno_learning_path_completed_on($gid, $uid, TRUE);
} catch (InvalidPluginDefinitionException|PluginNotFoundException|PluginException $e) {
$completed = NULL;
watchdog_exception('opigno_certificate_exception', $e);
}
if ($completed) {
$variables['completed_on'] = $date_formatter
->format($completed, 'certificate_date');
}
// Get the expiration date.
$expire = LPStatus::getCertificateExpireTimestamp($gid, $uid);
if ($expire) {
$variables['expire_on'] = $date_formatter
->format($expire, 'certificate_date');
}
}
// Add the background image and logo.
$bg_img = drupal_get_path('theme', 'aristotle') . '/assets/Logo-Opigno-circle.svg';
$variables['bg_image'] = file_exists($bg_img) ? file_url_transform_relative(base_path() . $bg_img) : '';
$logo = drupal_get_path('theme', 'aristotle') . '/assets/Logo-Opigno-3-dark.svg';
$variables['logo'] = file_exists($logo) ? file_url_transform_relative(base_path() . $logo) : '';
$variables['awarded_to'] = $user
->getDisplayName();
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
$variables['style_certificate_edit_form'] = drupal_get_path('module', 'opigno_certificate') . '/css/opigno_certificate_edit_form.css';
}
/**
* Implements hook_form_alter().
*/
function opigno_certificate_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (in_array($form_id, [
'opigno_certificate_wysiwyg_add_form',
'opigno_certificate_wysiwyg_edit_form',
])) {
$form['body']['widget'][0]['#format'] = 'opigno_certificate_wysiwyg';
$form['field-comments'] = [
'#type' => 'details',
'#title' => t('Body tokens'),
'#open' => TRUE,
];
$form['field-comments']['tokens'] = [
'#type' => 'item',
'#title' => t('Tokens'),
'#markup' => '<p>The following tokens are available, and make possible to have some information about user data, training\'s name, completion date automatically inserted into the certificate when it is issued.</p>
<ul>
<li>Training title - [opigno_certificate:referencing_entity]</li>
<li>Training completed on date - [opigno_certificate:created]</li>
<li>Training certificate expiration date - [group:expiration_date]</li>
<li>User who completed training - [current-user:display-name]</li>
<li>Certificate title - [opigno_certificate:label]</li>
<li>Certificate author - [opigno_certificate:uid:entity:display-name]</li>
</ul>',
];
}
// Make field uid required.
$array_form_ids = [
'opigno_certificate_template_add_form',
'opigno_certificate_template_edit_form',
'opigno_certificate_wysiwyg_edit_form',
'opigno_certificate_wysiwyg_add_form',
];
if (in_array($form_id, $array_form_ids)) {
$form['uid']['widget'][0]['target_id']['#required'] = TRUE;
}
unset($form["paper_orientation"]["widget"]["#options"]["_none"]);
$form["actions"]["#weight"] = 125;
}
/**
* Implements hook_filter_info_alter().
*/
function opigno_certificate_preprocess_filter_tips(&$variables) {
// @todo: the filter tips don't appear to be available in a regular alter
// hook, but if there is one that would be a better place to alter them. On
// the other hand, swapping out the plugin to change the filter tips seems
// overly intrusive for a text change.
if (isset($variables['tips']['Certificate WYSIWYG']) && !$variables['long']) {
// @todo: a more complete list of tokens here.
$variables['tips']['Certificate WYSIWYG']['list']['token_filter']['tip'] = t('Use tokens like [opigno_certificate:label] for the title for the opigno_certificate and [opigno_certificate:referencing_entity:label] for the training title.');
}
}
/**
* Implements hook_ckeditor_css_alter().
*/
function opigno_certificate_ckeditor_css_alter(array &$css, Editor $editor) {
$css[] = drupal_get_path('module', 'opigno_certificate') . '/css/opigno_certificate_edit_form.css';
}
Functions
Name | Description |
---|---|
opigno_certificate_ckeditor_css_alter | Implements hook_ckeditor_css_alter(). |
opigno_certificate_entity_bundle_field_info | Implements hook_entity_bundle_field_info(). |
opigno_certificate_entity_bundle_info | Implements hook_entity_bundle_info(). |
opigno_certificate_entity_field_storage_info | Implements hook_entity_field_storage_info(). |
opigno_certificate_entity_view_mode_alter | Implements hook_entity_view_mode_alter(). |
opigno_certificate_entity_view_mode_info_alter | Implements hook_entity_view_mode_info_alter(). |
opigno_certificate_form_alter | Implements hook_form_alter(). |
opigno_certificate_form_entity_view_display_edit_form_alter | Implements hook_form_FORM_ID_alter(). |
opigno_certificate_preprocess_filter_tips | Implements hook_filter_info_alter(). |
opigno_certificate_theme | Implements hook_theme(). |
opigno_certificate_theme_suggestions_opigno_certificate | Implements hook_theme_suggestions_HOOK(). |
template_preprocess_opigno_certificate | Implements template_preprocess_HOOK(). |