farm-2.x-dev/modules/log/birth/farm_birth.module
modules/log/birth/farm_birth.module
<?php
/**
* @file
* Contains farm_birth.module.
*/
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function farm_birth_form_log_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Only proceed if the mother and asset fields exist.
if (empty($form['mother']) || empty($form['asset'])) {
return;
}
// Rename the asset field to Children.
$form['asset']['widget']['#title'] = t('Children');
}
/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function farm_birth_log_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
// Only alter birth logs.
if ($entity->bundle() != 'birth') {
return;
}
// Rename the asset field to Children.
if (!empty($build['asset'])) {
$build['asset']['#title'] = t('Children');
}
}
/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function farm_birth_asset_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
// Only alter animal assets.
if ($entity->bundle() != 'animal') {
return;
}
// Add a link to the asset's birth log.
if (!empty($build['birthdate'])) {
/** @var \Drupal\Core\Entity\EntityStorageInterface $log_storage */
$log_storage = \Drupal::service('entity_type.manager')->getStorage('log');
/** @var \Drupal\Core\Entity\Query\QueryInterface $query */
$query = $log_storage->getQuery()
->accessCheck(TRUE)
->condition('type', 'birth')
->condition('asset', $entity->id());
$ids = $query->execute();
if (!empty($ids)) {
$log = $log_storage->load(reset($ids));
$build['birthdate'][0]['#markup'] = '<a href="' . $log->toUrl()->toString() . '">' . $build['birthdate'][0]['#markup'] . '</a>';
}
}
}
/**
* Implements hook_entity_base_field_info_alter().
*/
function farm_birth_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
/** @var \Drupal\field\Entity\FieldConfig[] $fields */
// Validate that only one birth log references an asset.
if ($entity_type->id() == 'log' && !empty($fields['asset'])) {
$fields['asset']->addConstraint('UniqueBirthLog');
}
}
