clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,14 @@
langcode: en
status: true
dependencies:
module:
- farm_log
enforced:
module:
- farm_activity
id: activity
label: Activity
description: ''
name_pattern: 'Activity log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,8 @@
name: Activity log
description: Adds an Activity log type.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- log:log
@@ -0,0 +1,17 @@
<?php
namespace Drupal\farm_activity\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the activity log type.
*
* @LogType(
* id = "activity",
* label = @Translation("Activity"),
* )
*/
class Activity extends FarmLogType {
}
@@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- log.type.birth
id: log.birth.asset
field_name: asset
entity_type: log
bundle: birth
label: Children
description: 'Which child assets were born?'
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
handler: views
handler_settings:
view:
view_name: farm_asset_reference
display_name: entity_reference
field_type: entity_reference
@@ -0,0 +1,14 @@
langcode: en
status: true
dependencies:
module:
- farm_log
enforced:
module:
- farm_birth
id: birth
label: Birth
description: ''
name_pattern: 'Birth log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,9 @@
name: Birth log
description: Adds a Birth log type for Animal assets.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_animal
- farm:farm_entity
- log:log
@@ -0,0 +1,64 @@
<?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\Field\Entity\BaseFieldOverride;
use Drupal\Core\Url;
/**
* 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'][0])) {
/** @var \Drupal\Core\Entity\EntityStorageInterface $log_storage */
$log_storage = \Drupal::service('entity_type.manager')->getStorage('log');
$log_ids = $log_storage->getQuery()
->accessCheck(TRUE)
->condition('type', 'birth')
->condition('asset', $entity->id())
->execute();
// Render a link to the log with a title of the timestamp field value.
if (!empty($log_ids)) {
$title = $build['birthdate'][0];
$build['birthdate'][0] = [
'#type' => 'link',
'#title' => $title,
'#url' => Url::fromRoute('entity.log.canonical', ['log' => reset($log_ids)]),
];
}
}
}
/**
* Implements hook_entity_bundle_field_info().
*/
function farm_birth_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
$fields = [];
// Add the UniqueBirthLog validation constraint to the asset field of birth
// logs. We need to do this via hook_entity_bundle_field_info() instead of
// hook_entity_field_info_alter() because this module also provides a
// BaseFieldOverride for the asset field, and there is a Drupal core issue
// that prevents these from working together normally.
// @see https://www.drupal.org/project/drupal/issues/3193351
if ($entity_type->id() == 'log' && $bundle == 'birth') {
$fields['asset'] = BaseFieldOverride::loadByName($entity_type->id(), $bundle, 'asset') ?: clone $base_field_definitions['asset'];
$fields['asset']->addConstraint('UniqueBirthLog');
}
return $fields;
}
@@ -0,0 +1,23 @@
<?php
/**
* @file
* Post update hooks for the farm_birth module.
*/
/**
* Override the birth log asset label and description.
*/
function farm_birth_post_update_override_birth_asset_label_description(&$sandbox) {
// Override the asset field label and description on birth logs to make it
// clear that it should be used to reference the child assets that were born.
// This also checks to make sure they haven't been overridden already first.
/** @var \Drupal\Core\Field\Entity\BaseFieldOverride $config */
$config = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('log')['asset']->getConfig('birth');
if ($config->isNew()) {
$config->set('label', 'Children');
$config->set('description', 'Which child assets were born?');
$config->save();
}
}
@@ -0,0 +1,6 @@
services:
farm_birth.log_event_subscriber:
class: Drupal\farm_birth\EventSubscriber\LogEventSubscriber
arguments: [ '@messenger' ]
tags:
- { name: 'event_subscriber' }
@@ -0,0 +1,124 @@
<?php
namespace Drupal\farm_birth\EventSubscriber;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\log\Event\LogEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Sync child asset fields to reflect those saved in a birth log.
*/
class LogEventSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
/**
* The Messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* MyModuleService constructor.
*
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger service.
*/
public function __construct(MessengerInterface $messenger) {
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*
* @return array
* The event names to listen for, and the methods that should be executed.
*/
public static function getSubscribedEvents() {
return [
LogEvent::INSERT => 'syncBirthChildren',
LogEvent::UPDATE => 'syncBirthChildren',
];
}
/**
* Sync child asset fields to reflect those saved in a birth log.
*
* @param \Drupal\log\Event\LogEvent $event
* The log event.
*/
public function syncBirthChildren(LogEvent $event): void {
// Get the log entity from the event.
$log = $event->log;
// If this is not a birth log, bail.
if ($log->bundle() != 'birth') {
return;
}
// Load mother asset.
/** @var \Drupal\asset\Entity\AssetInterface $mother */
$mothers = $log->get('mother')->referencedEntities();
$mother = reset($mothers);
// Load children assets.
/** @var \Drupal\asset\Entity\AssetInterface[] $children */
$children = $log->get('asset')->referencedEntities();
// If the log doesn't reference any children, bail.
if (empty($children)) {
return;
}
// Iterate through the children.
foreach ($children as $child) {
$save = FALSE;
$revision_log = [];
// If the child is an animal, and their date of birth does not match the
// timestamp of the birth log, sync it.
if ($child->bundle() == 'animal' && $child->get('birthdate')->value != $log->get('timestamp')->value) {
$args = [
':child_url' => $child->toUrl()->toString(),
'%child_name' => $child->label(),
];
$message = $this->t('<a href=":child_url">%child_name</a> date of birth was updated to match their birth log.', $args);
$this->messenger->addMessage($message);
$revision_log[] = $message;
$child->birthdate = $log->get('timestamp')->value;
$save = TRUE;
}
// If a mother is specified, and the child does not have any parents,
// add the mother to the child's parent reference field.
if (!empty($mother)) {
$parents = $child->get('parent')->referencedEntities();
if (empty($parents)) {
$args = [
':mother_url' => $mother->toUrl()->toString(),
'%mother_name' => $mother->label(),
':child_url' => $child->toUrl()->toString(),
'%child_name' => $child->label(),
];
$message = $this->t('<a href=":mother_url">%mother_name</a> added as a parent of <a href=":child_url">%child_name</a>.', $args);
$this->messenger->addMessage($message);
$revision_log[] = $message;
$child->parent[] = ['target_id' => $mother->id()];
$save = TRUE;
}
}
// Save the child, if necessary.
if ($save) {
$revision_log[] = $this->t('Birth log saved: <a href=":birth_url">%birth_label</a>', [':birth_url' => $log->toUrl()->toString(), '%birth_label' => $log->label()]);
$child->setRevisionLogMessage(implode(" ", $revision_log));
$child->save();
}
}
}
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\farm_birth\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the birth log type.
*
* @LogType(
* id = "birth",
* label = @Translation("Birth"),
* )
*/
class Birth extends FarmLogType {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
// Mother.
$options = [
'type' => 'entity_reference',
'label' => $this->t('Mother'),
'target_type' => 'asset',
'target_bundle' => 'animal',
'weight' => [
'form' => 45,
'view' => -15,
],
];
$fields['mother'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Veterinarian.
$options = [
'type' => 'string',
'label' => $this->t('Veterinarian'),
'description' => $this->t('If a veterinarian was involved, enter their name here.'),
'weight' => [
'form' => -40,
'view' => -40,
],
];
$fields['vet'] = $this->farmFieldFactory->bundleFieldDefinition($options);
return $fields;
}
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\farm_birth\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Checks that only one birth log references an asset.
*
* @Constraint(
* id = "UniqueBirthLog",
* label = @Translation("Unique birth log", context = "Validation"),
* )
*/
class UniqueBirthLogConstraint extends Constraint {
/**
* The default violation message.
*
* @var string
*/
public $message = '%child already has a birth log. More than one birth log cannot reference the same child.';
}
@@ -0,0 +1,86 @@
<?php
namespace Drupal\farm_birth\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the UniqueBirthLog constraint.
*/
class UniqueBirthLogConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a UniqueBirthLogConstraintValidator object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $value */
/** @var \Drupal\farm_birth\Plugin\Validation\Constraint\UniqueBirthLogConstraint $constraint */
// Only continue if this is a birth log.
/** @var \Drupal\log\Entity\LogInterface $log */
$log = $value->getParent()->getValue();
if (!is_null($log) && $log->bundle() != 'birth') {
return;
}
// Iterate through referenced entities.
foreach ($value->referencedEntities() as $delta => $asset) {
// If the log is not new, skip validation.
// A birth log exits so there is no need to check if one can be created.
/** @var \Drupal\log\Entity\LogInterface $log */
$log = $value->getParent()->getValue();
if (!$log->isNew()) {
return;
}
// Query the number of birth logs that reference the asset.
// We do not check access to ensure that all matching logs are found.
$count = $this->entityTypeManager->getStorage('log')->getAggregateQuery()
->accessCheck(FALSE)
->condition('type', 'birth')
->condition('asset', $asset->id())
->count()
->execute();
// If more than 0 birth logs reference the asset, add a violation.
if ($count > 0) {
$this->context->buildViolation($constraint->message, ['%child' => $asset->label()])
->atPath((string) $delta . '.target_id')
->setInvalidValue($asset->id())
->addViolation();
}
}
}
}
@@ -0,0 +1,233 @@
<?php
namespace Drupal\Tests\farm_birth\Kernel;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\KernelTests\KernelTestBase;
use Drupal\asset\Entity\Asset;
use Drupal\log\Entity\Log;
use Drupal\taxonomy\Entity\Term;
/**
* Tests for farmOS birth log logic.
*
* @group farm
*/
class BirthTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'asset',
'log',
'entity',
'farm_animal',
'farm_animal_type',
'farm_birth',
'farm_entity',
'farm_entity_fields',
'farm_entity_views',
'farm_field',
'farm_id_tag',
'farm_log',
'farm_log_asset',
'farm_parent',
'file',
'geofield',
'image',
'options',
'state_machine',
'system',
'user',
'taxonomy',
'text',
'views',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('asset');
$this->installEntitySchema('log');
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('user');
$this->installConfig([
'farm_entity_views',
'farm_animal',
'farm_animal_type',
'farm_birth',
]);
}
/**
* Test that saving a birth log syncs data to children assets.
*/
public function testBirthLogChildrenSync() {
// Create a Cow animal type term.
/** @var \Drupal\taxonomy\TermInterface $cow */
$cow = Term::create([
'name' => 'Cow',
'vid' => 'animal_type',
]);
$cow->save();
// Create a mother animal asset.
/** @var \Drupal\asset\Entity\AssetInterface $mother */
$mother = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$mother->save();
// Create 2 children animal assets.
/** @var \Drupal\asset\Entity\AssetInterface $child1 */
$child1 = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$child1->save();
/** @var \Drupal\asset\Entity\AssetInterface $child2 */
$child2 = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$child2->save();
// Confirm that the children do not have parents or dates of birth.
$this->assertEmpty($child1->get('parent')->referencedEntities());
$this->assertEmpty($child2->get('parent')->referencedEntities());
$this->assertEmpty($child1->get('birthdate')->value);
$this->assertEmpty($child2->get('birthdate')->value);
// Get the current timestamp.
$timestamp = \Drupal::time()->getRequestTime();
// Create a birth log that references the mother and children.
$log = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => $timestamp,
'mother' => ['target_id' => $mother->id()],
'asset' => [
['target_id' => $child1->id()],
['target_id' => $child2->id()],
],
]);
$log->save();
// Reload children assets.
$child1 = Asset::load($child1->id());
$child2 = Asset::load($child2->id());
// Confirm that the children list the mother as their parent and have dates
// of birth equal to the birth log.
$this->assertNotEmpty($child1->get('parent')->referencedEntities());
$this->assertNotEmpty($child2->get('parent')->referencedEntities());
$this->assertEquals($mother->id(), $child1->get('parent')->referencedEntities()[0]->id());
$this->assertEquals($mother->id(), $child2->get('parent')->referencedEntities()[0]->id());
$this->assertEquals($timestamp, $child1->get('birthdate')->value);
$this->assertEquals($timestamp, $child2->get('birthdate')->value);
// Create another mother animal asset.
/** @var \Drupal\asset\Entity\AssetInterface $mother2 */
$mother2 = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$mother2->save();
// Create a birth log that references the second mother and one of the
// original children.
$log = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => $timestamp,
'mother' => ['target_id' => $mother2->id()],
'asset' => [
['target_id' => $child1->id()],
],
]);
$log->save();
// Reload the first child asset.
$child1 = Asset::load($child1->id());
// Confirm that the child's parent has NOT changed to the new mother. If a
// child already has parents they should not be changed.
$this->assertNotEmpty($child1->get('parent')->referencedEntities());
$this->assertNotEquals($mother2->id(), $child1->get('parent')->referencedEntities()[0]->id());
}
/**
* Test that only one birth log can reference an asset.
*/
public function testUniqueBirthLogConstraint() {
// Create a Cow animal type term.
/** @var \Drupal\taxonomy\TermInterface $cow */
$cow = Term::create([
'name' => 'Cow',
'vid' => 'animal_type',
]);
$cow->save();
// Create an asset.
/** @var \Drupal\asset\Entity\AssetInterface $asset */
$asset = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$asset->save();
// Create a birth log that references the asset.
$log1 = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => \Drupal::time()->getRequestTime(),
'asset' => [['target_id' => $asset->id()]],
]);
// Confirm that there are no validation errors.
$errors = $log1->validate();
$this->assertCount(0, $errors);
$log1->save();
// Create a second birth log that references the asset.
$log2 = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => \Drupal::time()->getRequestTime(),
'asset' => [['target_id' => $asset->id()]],
]);
// Confirm that validation fails.
$errors = $log2->validate();
$this->assertCount(1, $errors);
$this->assertEquals(new FormattableMarkup('%child already has a birth log. More than one birth log cannot reference the same child.', ['%child' => $asset->label()]), $errors[0]->getMessage());
$this->assertEquals('asset.0.target_id', $errors[0]->getPropertyPath());
// Try updating the original birth log.
$log1->set('name', $this->randomMachineName());
// Confirm there are no validation errors.
$errors = $log1->validate();
$this->assertCount(0, $errors);
$log1->save();
}
}
@@ -0,0 +1,14 @@
langcode: en
status: true
dependencies:
module:
- farm_log
enforced:
module:
- farm_harvest
id: harvest
label: Harvest
description: ''
name_pattern: 'Harvest log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,8 @@
name: Harvest log
description: Adds an Harvest log type.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- log:log
@@ -0,0 +1,38 @@
<?php
namespace Drupal\farm_harvest\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the harvest log type.
*
* @LogType(
* id = "harvest",
* label = @Translation("Harvest"),
* )
*/
class Harvest extends FarmLogType {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
// Lot number.
$options = [
'type' => 'string',
'label' => $this->t('Lot number'),
'description' => $this->t('If this harvest is part of a batch or lot, enter the lot number here.'),
'weight' => [
'form' => 20,
'view' => 20,
],
];
$fields['lot_number'] = $this->farmFieldFactory->bundleFieldDefinition($options);
return $fields;
}
}
@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- farm_log
- farm_log_quantity
enforced:
module:
- farm_input
third_party_settings:
farm_log_quantity:
default_quantity_type: material
id: input
label: Input
description: ''
name_pattern: 'Input log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,9 @@
name: Input log
description: Adds an Input log type.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- farm:farm_quantity_material
- log:log
@@ -0,0 +1,31 @@
<?php
/**
* @file
* Provides Views data for farm_input module.
*/
/**
* Implements hook_views_data().
*/
function farm_input_views_data() {
$data = [];
// Add a quantity_material_type pseudo field to the log_field_data table.
// This pseudo field only has a filter configured to support filtering logs
// by the quantity material type.
$data['log_field_data']['quantity_material_type'] = [
'description' => t('Filter by the material type of quantities referenced by this log.'),
'entity_type' => 'quantity',
'entity_field' => 'material_type',
'filter' => [
'title' => t('Quantity material type'),
'description' => t('Filter by the material type of quantities referenced by this log.'),
'id' => 'log_quantity_material_type',
'field_name' => 'material_type',
],
];
return $data;
}
@@ -0,0 +1,46 @@
<?php
/**
* @file
* Provides Views runtime hooks for farm_input module.
*/
use Drupal\views\ViewExecutable;
/**
* Implements hook_views_pre_view().
*/
function farm_input_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
// Alter the farm_log View.
if ($view->id() == 'farm_log') {
// Only alter the page_type and page_asset displays.
if (!in_array($display_id, ['page_type', 'page_asset'])) {
return;
}
// Bail if not a view of input logs.
if (!in_array('input', $args)) {
return;
}
// Add a filter for the quantity material type.
$table = 'log_field_data';
$field = 'quantity_material_type';
$filter_options = [
'id' => 'material_type_target_id',
'table' => $table,
'field' => $field,
'exposed' => TRUE,
'expose' => [
'label' => t('Material type'),
'identifier' => $field,
'multiple' => TRUE,
],
'type' => 'select',
'limit' => TRUE,
];
$view->addHandler($display_id, 'filter', $table, $field, $filter_options);
}
}
@@ -0,0 +1,74 @@
<?php
namespace Drupal\farm_input\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the input log type.
*
* @LogType(
* id = "input",
* label = @Translation("Input"),
* )
*/
class Input extends FarmLogType {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
// Lot number.
$options = [
'type' => 'string',
'label' => $this->t('Lot number'),
'description' => $this->t('If this harvest is part of a batch or lot, enter the lot number here.'),
'weight' => [
'form' => -45,
'view' => -45,
],
];
$fields['lot_number'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Method.
$options = [
'type' => 'string',
'label' => $this->t('Method'),
'description' => $this->t('How was this input applied?'),
'weight' => [
'form' => -30,
'view' => -30,
],
];
$fields['method'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Purchase date.
$options = [
'type' => 'timestamp',
'label' => $this->t('Purchase date'),
'description' => $this->t('When was this input purchased (if applicable)?'),
'weight' => [
'form' => -35,
'view' => -35,
],
];
$fields['purchase_date'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Source.
$options = [
'type' => 'string',
'label' => $this->t('Source'),
'description' => $this->t('Where was this input obtained? Who manufactured it?'),
'weight' => [
'form' => -40,
'view' => -40,
],
];
$fields['source'] = $this->farmFieldFactory->bundleFieldDefinition($options);
return $fields;
}
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\farm_input\Plugin\views\filter;
use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid;
/**
* Filter handler for log quantity material type terms.
*
* @ViewsFilter("log_quantity_material_type")
*/
class LogQuantityMaterialType extends TaxonomyIndexTid {
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
// Hard code the material_type vocabulary.
$options['vid'] = ['default' => 'material_type'];
return $options;
}
/**
* {@inheritdoc}
*/
public function buildExtraOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildExtraOptionsForm($form, $form_state);
// Remove the vocabulary form element, use the hard coded default.
unset($form['vid']);
}
/**
* {@inheritdoc}
*/
public function query() {
// Bail if there are no filter values.
if (count($this->value) == 0) {
return;
}
elseif (count($this->value) == 1) {
// Sometimes $this->value is an array with a single element so convert it.
// @see TaxonomyIndexTidDepth::query().
if (is_array($this->value)) {
$this->value = current($this->value);
}
$operator = '=';
}
else {
$operator = 'IN';
}
// Build a subquery to find logs that reference a quantity with the
// specified material type.
$subquery = Database::getConnection()->select('log', 'l');
$subquery->addField('l', 'id');
$subquery->innerJoin('log__quantity', 'lq', 'l.id = lq.entity_id');
$subquery->innerJoin('quantity__material_type', 'qmt', 'lq.quantity_target_id = qmt.entity_id AND lq.quantity_target_revision_id = qmt.revision_id');
$subquery->condition('qmt.material_type_target_id', $this->value, $operator);
// Get the table alias for log_field_data.
$this->tableAlias = $this->query->ensureTable($this->view->storage->get('base_table'));
// Use the subquery in a condition on the views query to prevent duplicates.
$this->query->addWhere($this->options['group'], "$this->tableAlias.id", $subquery, 'IN');
}
}
@@ -0,0 +1,195 @@
<?php
namespace Drupal\Tests\farm_input\Functional;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
use Drupal\log\Entity\Log;
use Drupal\quantity\Entity\Quantity;
use Drupal\taxonomy\Entity\Term;
/**
* Test material type filter functionality.
*
* @see \Drupal\farm_input\Plugin\views\filter\LogQuantityMaterialType
*
* @group farm
*/
class InputViewMaterialTypeTest extends FarmBrowserTestBase {
/**
* Test user.
*
* @var \Drupal\user\Entity\User
*/
protected $user;
/**
* Material type terms.
*
* @var \Drupal\taxonomy\Entity\Term[]
*/
protected array $materialTypes;
/**
* Logs for testing.
*
* @var \Drupal\log\Entity\Log[]
*/
protected array $testLogs;
/**
* {@inheritdoc}
*/
protected static $modules = [
'farm_ui',
'farm_quantity_standard',
'farm_input',
];
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
// Create and login a user with permission to view logs.
$this->user = $this->createUser(['view any log']);
$this->drupalLogin($this->user);
// Create material type terms.
$material_type_names = ['compost', 'fertilizer', 'spray'];
$this->materialTypes = [];
foreach ($material_type_names as $term_name) {
$term = Term::create(['vid' => 'material_type', 'name' => $term_name]);
$term->save();
$this->materialTypes[$term_name] = $term;
}
// Create logs with quantities.
$test_log_definitions = [
// Input log with no quantities.
[
'log' => ['type' => 'input'],
'quantities' => [],
],
// Input log with standard quantity.
[
'log' => ['type' => 'input'],
'quantities' => [
['type' => 'standard', 'measure' => 'count'],
],
],
// Input log with compost material type quantity.
[
'log' => ['type' => 'input'],
'quantities' => [
['type' => 'material', 'measure' => 'weight', 'material_type' => $this->materialTypes['compost']],
],
],
// Input log with fertilizer material type quantity.
[
'log' => ['type' => 'input'],
'quantities' => [
['type' => 'material', 'measure' => 'weight', 'material_type' => $this->materialTypes['fertilizer']],
],
],
// Input log with multiple quantities.
[
'log' => ['type' => 'input'],
'quantities' => [
['type' => 'standard', 'measure' => 'count'],
['type' => 'material', 'measure' => 'weight', 'material_type' => $this->materialTypes['compost']],
['type' => 'material', 'measure' => 'weight', 'material_type' => $this->materialTypes['fertilizer']],
],
],
];
$this->testLogs = [];
foreach ($test_log_definitions as $log_definition) {
$this->createLogWithQuantities($log_definition['log'], $log_definition['quantities']);
}
}
/**
* Test material type filter functionality.
*/
public function testMaterialTypeFilter() {
// Get the input logs view.
$this->drupalGet('/logs/input');
// Assert that the Material type exposed filter exists.
$this->assertSession()->pageTextContains('Material type');
$this->assertSession()->fieldExists('edit-quantity-material-type');
// Assert that each material type is an option.
foreach ($this->materialTypes as $material_type) {
$this->assertSession()->pageTextContains($material_type->label());
}
// No filter, assert that each log is visible.
foreach ($this->testLogs as $log) {
$this->assertSession()->pageTextContainsOnce($log->label());
}
// Collect all material type ids.
$material_type_ids = array_map(function ($term) {
return $term->id();
}, $this->materialTypes);
// Test each material type individually.
$test_filters = $material_type_ids;
// Test filtering by all material types.
$test_filters[] = $material_type_ids;
// Filter by each material type test.
foreach ($test_filters as $material_types) {
// Query expected logs.
$expected_logs = \Drupal::entityTypeManager()->getStorage('log')->loadByProperties([
'quantity.entity:quantity.material_type' => $material_types,
]);
// Filter to only include logs with the specified material type.
// Make sure the parameter is an array.
$material_types = is_array($material_types) ? $material_types : [$material_types];
$this->drupalGet('/logs/input', ['query' => ['quantity_material_type' => $material_types]]);
// Assert that each expected log exists.
foreach ($expected_logs as $log) {
$this->assertSession()->pageTextContainsOnce($log->label());
}
}
}
/**
* Helper function to create logs with quantities.
*
* @param array $log
* The log definition.
* @param array $quantities
* An array of quantity definitions.
*
* @return \Drupal\log\Entity\Log
* The log that was created.
*/
protected function createLogWithQuantities(array $log, array $quantities) {
// Create each quantity.
$quantity_entities = [];
foreach ($quantities as $definition) {
$quantity = Quantity::create($definition);
$quantity->save();
$quantity_entities[] = $quantity;
}
// Create the log and reference the quantities.
$log_entity = Log::create($log);
$log_entity->set('quantity', $quantity_entities);
$log_entity->save();
return $log_entity;
}
}
@@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
config:
- log.type.lab_test
enforced:
module:
- farm_lab_test
id: log.lab_test.timestamp
field_name: timestamp
entity_type: log
bundle: lab_test
label: 'Date sampled'
description: 'The date when the sample was collected.'
required: true
translatable: true
default_value: { }
default_value_callback: 'Drupal\log\Entity\Log::getRequestTime'
settings: { }
field_type: timestamp
@@ -0,0 +1,8 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_lab_test
id: soil
label: Soil test
@@ -0,0 +1,8 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_lab_test
id: tissue
label: Tissue test
@@ -0,0 +1,8 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_lab_test
id: water
label: Water test
@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- farm_log
- farm_log_quantity
enforced:
module:
- farm_lab_test
third_party_settings:
farm_log_quantity:
default_quantity_type: test
id: lab_test
label: 'Lab test'
description: ''
name_pattern: 'Lab test log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,11 @@
# Schema for lab_test_type config entity.
farm_lab_test.lab_test_type.*:
type: config_entity
label: 'Lab test type'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
@@ -0,0 +1,10 @@
name: Lab test log
description: Adds a Lab test log type.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- farm:farm_lab
- farm:farm_quantity_test
- log:log
@@ -0,0 +1,54 @@
<?php
/**
* @file
* The farmOS lab test log module.
*/
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Lab test type options helper.
*
* @return array
* Returns an array of lab test types for use in form select options.
*/
function farm_lab_test_type_options() {
/** @var \Drupal\farm_lab_test\Entity\FarmLabTestTypeInterface[] $lab_test_types */
$lab_test_types = \Drupal::entityTypeManager()->getStorage('lab_test_type')->loadMultiple();
$options = [];
foreach ($lab_test_types as $id => $lab_test_type) {
$options[$id] = $lab_test_type->getLabel();
}
return $options;
}
/**
* Allowed values callback function for the lab test type field.
*
* @param \Drupal\Core\Field\FieldStorageDefinitionInterface $definition
* The field definition.
* @param \Drupal\Core\Entity\ContentEntityInterface|null $entity
* The entity being created if applicable.
* @param bool $cacheable
* Boolean indicating if the allowed values can be cached. Defaults to TRUE.
*
* @return array
* Returns an array of allowed values for use in form select options.
*/
function farm_lab_test_type_field_allowed_values(FieldStorageDefinitionInterface $definition, ?ContentEntityInterface $entity = NULL, bool &$cacheable = TRUE) {
return farm_lab_test_type_options();
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function farm_lab_test_form_log_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Only show the "Soil texture" field if the lab test type is "soil".
if (isset($form['lab_test_type']) && isset($form['soil_texture'])) {
$form['soil_texture']['#states']['visible'] = [':input[name="lab_test_type"]' => ['value' => 'soil']];
}
}
@@ -0,0 +1,211 @@
<?php
/**
* @file
* Post update hooks for the farm_lab_test module.
*/
use Drupal\Core\Utility\UpdateException;
use Drupal\farm_lab_test\Entity\FarmLabTestType;
use Drupal\taxonomy\Entity\Term;
/**
* Add "Date received" and "Date processed" fields to lab test logs.
*/
function farm_lab_test_post_update_add_received_processed_date_fields(&$sandbox) {
// Date received.
$options = [
'type' => 'timestamp',
'label' => t('Date received'),
'description' => t('The date when the sample was received by the lab.'),
'weight' => [
'form' => -35,
'view' => -35,
],
];
$field_definition = \Drupal::service('farm_field.factory')->bundleFieldDefinition($options);
\Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('lab_received_date', 'log', 'farm_lab_test', $field_definition);
// Date processed.
$options = [
'type' => 'timestamp',
'label' => t('Date processed'),
'description' => t('The date when the sample was processed by the lab.'),
'weight' => [
'form' => -34,
'view' => -34,
],
];
$field_definition = \Drupal::service('farm_field.factory')->bundleFieldDefinition($options);
\Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('lab_processed_date', 'log', 'farm_lab_test', $field_definition);
}
/**
* Install the lab taxonomy module.
*/
function farm_lab_test_post_update_enable_farm_lab(&$sandbox) {
if (!\Drupal::service('module_handler')->moduleExists('farm_lab')) {
\Drupal::service('module_installer')->install(['farm_lab']);
}
}
/**
* Migrate laboratory names to taxonomy terms.
*/
function farm_lab_test_post_update_migrate_lab_terms(&$sandbox) {
// This function will be run as a batch operation to save the new term
// reference values on existing logs. On the first run, we will make
// preparations. This logic should only run once.
if (!isset($sandbox['current_log'])) {
// Query the database for all lab field data on logs.
// Save it to $sandbox for future reference.
$sandbox['log_map'] = \Drupal::database()->query('SELECT entity_id, lab_value FROM {log__lab} WHERE deleted = 0')->fetchCol();
// Create taxonomy terms for each of the labs.
// Add them to a term map in $sandbox for future reference.
$unique_labs = array_unique($sandbox['log_map']);
$sandbox['term_map'] = [];
foreach ($unique_labs as $lab_name) {
$term = Term::create(['vid' => 'lab', 'name' => $lab_name]);
$term->save();
$sandbox['term_map'][$lab_name] = $term->id();
}
// Get the Drupal entity definition update manager.
$update_manager = \Drupal::entityDefinitionUpdateManager();
// Delete the old lab field.
$storage_definition = $update_manager->getFieldStorageDefinition('lab', 'log');
$update_manager->uninstallFieldStorageDefinition($storage_definition);
// Install the new lab field.
$options = [
'type' => 'entity_reference',
'label' => t('Laboratory'),
'description' => t('What laboratory performed this test?'),
'target_type' => 'taxonomy_term',
'target_bundle' => 'lab',
'auto_create' => TRUE,
'weight' => [
'form' => -40,
'view' => -40,
],
];
$field_definition = \Drupal::service('farm_field.factory')->bundleFieldDefinition($options);
$update_manager->installFieldStorageDefinition('lab', 'log', 'farm_lab_test', $field_definition);
// If there are no lab test logs with lab field values, bail.
if (empty($sandbox['log_map'])) {
return NULL;
}
// Track progress.
$sandbox['current_log'] = 0;
$sandbox['#finished'] = 0;
}
// Iterate over logs, 10 at a time.
$log_ids = array_keys($sandbox['log_map']);
$log_count = count($log_ids);
$end_log = $sandbox['current_log'] + 10;
$end_log = $end_log > $log_count ? $log_count : $end_log;
for ($i = $sandbox['current_log']; $i < $end_log; $i++) {
// Iterate the global counter.
$sandbox['current_log']++;
// Get the log ID.
$id = $log_ids[$i];
// If there is no taxonomy term to assign, skip.
if (empty($sandbox['log_map'][$id]) || empty($sandbox['term_map'][$sandbox['log_map'][$id]])) {
continue;
}
// Load the log.
$log = \Drupal::service('entity_type.manager')->getStorage('log')->load($id);
// If the log didn't load, throw an update exception.
if (empty($log)) {
throw new UpdateException('Could not load log. ID: @id', ['@id' => $id]);
}
// Assign the new lab taxonomy term.
$log->set('lab', $sandbox['term_map'][$sandbox['log_map'][$id]]);
// Save a new revision of the log.
$log->setNewRevision(TRUE);
$log->setRevisionLogMessage(t('Automatically migrated laboratory name to taxonomy term in the new Lab vocabulary.'));
$log->save();
// Declare that the log has been fixed.
\Drupal::logger('farm_lab_test')->notice(t('Log @id lab has been migrated.', ['@id' => $id]));
}
// Update progress.
$sandbox['#finished'] = $sandbox['current_log'] / count($sandbox['log_map']);
return NULL;
}
/**
* Install the test quantity module.
*/
function farm_lab_test_post_update_enable_farm_quantity_test(&$sandbox) {
if (!\Drupal::service('module_handler')->moduleExists('farm_quantity_test')) {
\Drupal::service('module_installer')->install(['farm_quantity_test']);
}
}
/**
* Add tissue lab test type.
*/
function farm_lab_test_post_update_add_tissue_type(&$sandbox) {
$type = FarmLabTestType::create([
'id' => 'tissue',
'label' => 'Tissue test',
'dependencies' => [
'enforced' => [
'module' => [
'farm_lab_test',
],
],
],
]);
$type->save();
}
/**
* Override the lab_test log timestamp label and description.
*/
function farm_lab_test_post_update_override_lab_test_timestamp_label_description(&$sandbox) {
// Override the timestamp field label and description on lab_test logs to
// make it clear that it should be used for the date the sample was taken.
// This also checks to make sure they haven't been overridden already first.
/** @var \Drupal\Core\Field\Entity\BaseFieldOverride $config */
$config = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('log')['timestamp']->getConfig('lab_test');
if ($config->isNew()) {
$config->set('label', 'Date sampled');
$config->set('description', 'The date when the sample was collected.');
$config->save();
}
}
/**
* Add "Soil texture" field to lab test logs.
*/
function farm_lab_test_post_update_soil_texture(&$sandbox) {
$options = [
'type' => 'string',
'label' => t('Soil texture'),
'weight' => [
'form' => -45,
'view' => -45,
],
];
$field_definition = \Drupal::service('farm_field.factory')->bundleFieldDefinition($options);
\Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('soil_texture', 'log', 'farm_lab_test', $field_definition);
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\farm_lab_test\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBase;
/**
* Defines the FarmLabTestType entity.
*
* @ConfigEntityType(
* id = "lab_test_type",
* label = @Translation("Lab test type"),
* label_collection = @Translation("Lab test type"),
* handlers = { },
* admin_permission = "administer site configuration",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* },
* config_export = {
* "id",
* "label",
* },
* )
*
* @ingroup farm
*/
class FarmLabTestType extends ConfigEntityBase implements FarmLabTestTypeInterface {
/**
* The lab test type ID.
*
* @var string
*/
protected $id;
/**
* The lab test type label.
*
* @var string
*/
protected $label;
/**
* {@inheritdoc}
*/
public function getLabel() {
return $this->label;
}
}
@@ -0,0 +1,22 @@
<?php
namespace Drupal\farm_lab_test\Entity;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Provides an interface for defining FarmLabTestType config entities.
*
* @ingroup farm
*/
interface FarmLabTestTypeInterface extends ConfigEntityInterface {
/**
* Returns the lab test type label.
*
* @return string
* The lab test type label.
*/
public function getLabel();
}
@@ -0,0 +1,88 @@
<?php
namespace Drupal\farm_lab_test\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the lab test log type.
*
* @LogType(
* id = "lab_test",
* label = @Translation("LabTest"),
* )
*/
class LabTest extends FarmLogType {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
// Date received.
$options = [
'type' => 'timestamp',
'label' => $this->t('Date received'),
'description' => $this->t('The date when the sample was received by the lab.'),
'weight' => [
'form' => -70,
'view' => -70,
],
];
$fields['lab_received_date'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Date processed.
$options = [
'type' => 'timestamp',
'label' => $this->t('Date processed'),
'description' => $this->t('The date when the sample was processed by the lab.'),
'weight' => [
'form' => -60,
'view' => -60,
],
];
$fields['lab_processed_date'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Lab test type.
$options = [
'type' => 'list_string',
'label' => $this->t('Test type'),
'allowed_values_function' => 'farm_lab_test_type_field_allowed_values',
'weight' => [
'form' => -50,
'view' => -50,
],
];
$fields['lab_test_type'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Soil texture.
$options = [
'type' => 'string',
'label' => $this->t('Soil texture'),
'weight' => [
'form' => -45,
'view' => -45,
],
];
$fields['soil_texture'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Lab.
$options = [
'type' => 'entity_reference',
'label' => $this->t('Laboratory'),
'description' => $this->t('What laboratory performed this test?'),
'target_type' => 'taxonomy_term',
'target_bundle' => 'lab',
'auto_create' => TRUE,
'weight' => [
'form' => -40,
'view' => -40,
],
];
$fields['lab'] = $this->farmFieldFactory->bundleFieldDefinition($options);
return $fields;
}
}
@@ -0,0 +1,14 @@
langcode: en
status: true
dependencies:
module:
- farm_log
enforced:
module:
- farm_maintenance
id: maintenance
label: Maintenance
description: ''
name_pattern: 'Maintenance log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,8 @@
name: Maintenance log
description: Adds a Maintenance log type for Equipment assets.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- log:log
@@ -0,0 +1,17 @@
<?php
namespace Drupal\farm_maintenance\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the maintenance log type.
*
* @LogType(
* id = "maintenance",
* label = @Translation("Maintenance"),
* )
*/
class Maintenance extends FarmLogType {
}
@@ -0,0 +1,14 @@
langcode: en
status: true
dependencies:
module:
- farm_log
enforced:
module:
- farm_medical
id: medical
label: Medical
description: ''
name_pattern: 'Medical log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,9 @@
name: Medical log
description: Adds a Medical log type for Animal assets.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_animal
- farm:farm_entity
- log:log
@@ -0,0 +1,38 @@
<?php
namespace Drupal\farm_medical\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the medical log type.
*
* @LogType(
* id = "medical",
* label = @Translation("Medical"),
* )
*/
class Medical extends FarmLogType {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
// Veterinarian.
$options = [
'type' => 'string',
'label' => $this->t('Veterinarian'),
'description' => $this->t('If a veterinarian was involved, enter their name here.'),
'weight' => [
'form' => -40,
'view' => -40,
],
];
$fields['vet'] = $this->farmFieldFactory->bundleFieldDefinition($options);
return $fields;
}
}
@@ -0,0 +1,14 @@
langcode: en
status: true
dependencies:
module:
- farm_log
enforced:
module:
- farm_observation
id: observation
label: Observation
description: ''
name_pattern: 'Observation log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,8 @@
name: Observation log
description: Adds an Observation log type.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- log:log
@@ -0,0 +1,17 @@
<?php
namespace Drupal\farm_observation\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the observation log type.
*
* @LogType(
* id = "observation",
* label = @Translation("Observation"),
* )
*/
class Observation extends FarmLogType {
}
@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- farm_location
- farm_log
enforced:
module:
- farm_seeding
third_party_settings:
farm_location:
is_movement: true
id: seeding
label: Seeding
description: ''
name_pattern: 'Seeding log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,9 @@
name: Seeding log
description: Adds a Seeding log type for Plant assets.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- farm:farm_plant
- log:log
@@ -0,0 +1,62 @@
<?php
namespace Drupal\farm_seeding\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the seeding log type.
*
* @LogType(
* id = "seeding",
* label = @Translation("Seeding"),
* )
*/
class Seeding extends FarmLogType {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
// Lot number.
$options = [
'type' => 'string',
'label' => $this->t('Lot number'),
'description' => $this->t('If the seed is part of a batch or lot, enter the lot number here.'),
'weight' => [
'form' => 20,
'view' => 20,
],
];
$fields['lot_number'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Purchase date.
$options = [
'type' => 'timestamp',
'label' => $this->t('Purchase date'),
'description' => $this->t('When was the seed purchased (if applicable)?'),
'weight' => [
'form' => -35,
'view' => -35,
],
];
$fields['purchase_date'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Source.
$options = [
'type' => 'string',
'label' => $this->t('Source'),
'description' => $this->t('Where was the seed obtained? Who supplied it?'),
'weight' => [
'form' => -40,
'view' => -40,
],
];
$fields['source'] = $this->farmFieldFactory->bundleFieldDefinition($options);
return $fields;
}
}
@@ -0,0 +1,25 @@
langcode: en
status: true
dependencies:
config:
- field.storage.taxonomy_term.transplant_days
- taxonomy.vocabulary.plant_type
enforced:
module:
- farm_transplanting
id: taxonomy_term.plant_type.transplant_days
field_name: transplant_days
entity_type: taxonomy_term
bundle: plant_type
label: 'Days to transplant'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
min: 1
max: null
prefix: ''
suffix: ' day| days'
field_type: integer
@@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_transplanting
module:
- taxonomy
id: taxonomy_term.transplant_days
field_name: transplant_days
entity_type: taxonomy_term
type: integer
settings:
unsigned: true
size: normal
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false
@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- farm_location
- farm_log
enforced:
module:
- farm_transplanting
third_party_settings:
farm_location:
is_movement: true
id: transplanting
label: Transplanting
description: ''
name_pattern: 'Transplanting log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,10 @@
name: Transplanting log
description: Adds a Transplanting log type for Plant assets.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- farm:farm_plant
- farm:farm_plant_type
- log:log
@@ -0,0 +1,43 @@
<?php
/**
* @file
* Contains farm_transplanting.module.
*/
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
/**
* Implements hook_entity_form_display_alter().
*/
function farm_transplanting_entity_form_display_alter(EntityFormDisplayInterface $form_display, array $context) {
if ($context['entity_type'] == 'taxonomy_term' && $context['bundle'] == 'plant_type' && $form_display->getMode() == 'default' && $form_display->isNew()) {
$form_display->setComponent('transplant_days', [
'type' => 'number',
'settings' => [
'placeholder' => '',
],
'region' => 'content',
'weight' => 15,
]);
}
}
/**
* Implements hook_entity_view_display_alter().
*/
function farm_transplanting_entity_view_display_alter(EntityViewDisplayInterface $display, array $context) {
if ($context['entity_type'] == 'taxonomy_term' && $context['bundle'] == 'plant_type' && $display->getMode() == 'full' && $display->isNew()) {
$display->setComponent('transplant_days', [
'type' => 'number_integer',
'label' => 'inline',
'settings' => [
'thousand_separator' => '',
'prefix_suffix' => TRUE,
],
'region' => 'content',
'weight' => 15,
]);
}
}
@@ -0,0 +1,17 @@
<?php
namespace Drupal\farm_transplanting\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the transplanting log type.
*
* @LogType(
* id = "transplanting",
* label = @Translation("Transplanting"),
* )
*/
class Transplanting extends FarmLogType {
}