3
0
Fork 0
mirror of https://github.com/farmOS/farmOS.git synced 2024-02-23 11:37:38 +01:00
farmOS/modules/core/log/farm_log.module

89 lines
2.4 KiB
PHP

<?php
/**
* @file
* Contains farm_log.module.
*/
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_entity_prepare_form().
*/
function farm_log_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {
// If not adding a new entity, bail.
if ($operation !== 'add' || !$entity->isNew()) {
return;
}
// If the entity is not a log, bail.
if ($entity->getEntityTypeId() !== 'log') {
return;
}
// Save the current user.
$user = \Drupal::currentUser();
// Save the request query params.
$query = \Drupal::request()->query;
// Prepopulate the log asset field.
$asset_ids = $query->get('asset');
if (!empty($asset_ids)) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $asset_field */
$asset_field = $entity->get('asset');
// Wrap in an array, if necessary.
if (!is_array($asset_ids)) {
$asset_ids = [$asset_ids];
}
// Add each asset the user has view access to.
$assets = \Drupal::entityTypeManager()->getStorage('asset')->loadMultiple($asset_ids);
foreach ($assets as $asset) {
if ($asset->access('view', $user)) {
$asset_field->appendItem($asset);
}
}
$entity->set('asset', $asset_ids);
}
}
/**
* Generate a summary of asset names for use in a log name.
*
* Note that this function does NOT sanitize the asset names. This is the
* responsibility of downstream code, if it is printing the text to the page.
*
* @param \Drupal\asset\Entity\AssetInterface[] $assets
* An array of assets.
* @param int $cutoff
* The number of asset names to include before summarizing the rest.
* If the number of assets exceeds the cutoff, only the first asset's
* name will be included, and the rest will be summarized as "(+ X more)".
* If the number of assets is less than or equal to the cutoff, or if the
* cutoff is 0, all asset names will be included.
*
* @return string
* Returns a string summarizing the assets.
*/
function farm_log_asset_names_summary(array $assets, $cutoff = 3) {
/** @var \Drupal\asset\Entity\AssetInterface[] $assets */
$names = [];
foreach ($assets as $asset) {
$names[] = $asset->label();
}
$count = count($names);
if ($cutoff == 0 || count($names) <= $cutoff) {
$output = implode(', ', $names);
}
else {
$output = $names[0] . ' (+' . ($count - 1) . ' ' . t('more') . ')';
}
return $output;
}