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,12 @@
langcode: en
status: true
dependencies:
enforced:
module:
- quantity
module:
- quantity
id: quantity.plain_text
label: Plain text
targetEntityType: quantity
cache: false
@@ -0,0 +1 @@
system_of_measurement: metric
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- quantity
id: quantity_delete_action
label: 'Delete quantity'
type: quantity
plugin: entity:delete_action:quantity
configuration: { }
@@ -0,0 +1,23 @@
quantity.settings:
type: config_object
label: 'Quantity settings'
mapping:
system_of_measurement:
type: string
label: 'System of measurement'
quantity.type.*:
type: config_entity
label: 'Quantity type'
mapping:
id:
type: string
label: 'Machine-readable name'
label:
type: label
label: 'Type'
description:
type: text
label: 'Description'
new_revision:
type: boolean
label: 'Create new revision'
@@ -0,0 +1,12 @@
name: Quantity
description: Provides an entity to store quantity measurements.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- entity:entity
- drupal:text
- drupal:user
- drupal:views
- farm:farm_unit
- fraction:fraction
@@ -0,0 +1,5 @@
quantity.settings:
base_route: farm_settings.settings_page
route_name: quantity.settings
title: 'Quantity'
weight: 3
@@ -0,0 +1,3 @@
quantity:
config_permissions:
- administer quantity
@@ -0,0 +1,211 @@
<?php
/**
* @file
* Quantity module.
*/
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Render\Element;
use Drupal\quantity\Entity\QuantityInterface;
use Drupal\quantity\Event\QuantityEvent;
/**
* Define information about available quantity measures.
*
* @return array
* Returns an array of measure information.
*/
function quantity_measures() {
return [
'count' => [
'label' => t('Count'),
],
'length' => [
'label' => t('Length/depth'),
],
'weight' => [
'label' => t('Weight'),
],
'area' => [
'label' => t('Area'),
],
'volume' => [
'label' => t('Volume'),
],
'time' => [
'label' => t('Time'),
],
'temperature' => [
'label' => t('Temperature'),
],
'pressure' => [
'label' => t('Pressure'),
],
'water_content' => [
'label' => t('Water content'),
],
'value' => [
'label' => t('Value'),
],
'rate' => [
'label' => t('Rate'),
],
'rating' => [
'label' => t('Rating'),
],
'ratio' => [
'label' => t('Ratio'),
],
'probability' => [
'label' => t('Probability'),
],
'speed' => [
'label' => t('Speed'),
],
];
}
/**
* Quantity measure options helper.
*
* @return array
* Returns an array of quantity measures for use in form select options.
*/
function quantity_measure_options() {
// Start an empty options array.
$options = [];
// Load information about measures.
$measures = quantity_measures();
// Iterate through the measures and build a list of options.
foreach ($measures as $measure => $data) {
$options[$measure] = $data['label'];
}
// Return the array of options.
return $options;
}
/**
* Allowed values callback function for the quantity measure 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 quantity_measure_field_allowed_values(FieldStorageDefinitionInterface $definition, ?ContentEntityInterface $entity = NULL, bool &$cacheable = TRUE) {
return quantity_measure_options();
}
/**
* Implements hook_farm_api_meta_alter().
*/
function quantity_farm_api_meta_alter(&$data) {
// Add the quantity system of measurement.
$data['system_of_measurement'] = \Drupal::config('quantity.settings')->get('system_of_measurement');
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function quantity_quantity_presave(QuantityInterface $quantity) {
// Dispatch an event on quantity presave.
// @todo Replace this with core event via https://www.drupal.org/node/2551893.
$event = new QuantityEvent($quantity);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, QuantityEvent::PRESAVE);
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function quantity_quantity_delete(QuantityInterface $quantity) {
// Dispatch an event on quantity delete.
// @todo Replace this with core event via https://www.drupal.org/node/2551893.
$event = new QuantityEvent($quantity);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, QuantityEvent::DELETE);
}
/**
* Implements hook_theme().
*/
function quantity_theme() {
return [
'quantity' => [
'render element' => 'elements',
],
'field__quantity__field' => [
'template' => 'field--quantity--field',
'base hook' => 'field',
],
];
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function quantity_theme_suggestions_field(array $variables) {
$suggestions = [];
// Add a theme hook suggestion for theming all fields on quantity entities.
// Note that the field__quantity theme hook is used for any entity with
// a field called "quantity", such as the log.quantity entity reference.
if ($variables['element']['#entity_type'] == 'quantity') {
$suggestions[] = 'field__quantity__field';
}
return $suggestions;
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function quantity_theme_suggestions_quantity(array $variables) {
$suggestions = [];
$quantity = $variables['elements']['#quantity'];
$sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
$suggestions[] = 'quantity__' . $sanitized_view_mode;
$suggestions[] = 'quantity__' . $quantity->bundle();
$suggestions[] = 'quantity__' . $quantity->bundle() . '__' . $sanitized_view_mode;
$suggestions[] = 'quantity__' . $quantity->id();
$suggestions[] = 'quantity__' . $quantity->id() . '__' . $sanitized_view_mode;
return $suggestions;
}
/**
* Prepares variables for quantity templates.
*
* Default template: quantity.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the quantity information and
* any fields attached to the quantity. Properties used:
* - #quantity: A \Drupal\quantity\Entity\Quantity object. Quantity entity.
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_quantity(array &$variables) {
$variables['quantity'] = $variables['elements']['#quantity'];
// Helpful $content variable for templates.
$variables['content'] = [];
foreach (Element::children($variables['elements']) as $key) {
if (!empty($variables['elements'][$key]['#items'])) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
}
@@ -0,0 +1,12 @@
administer quantity:
title: 'Administer quantity'
view all quantity revisions:
title: 'View all quantity revisions'
description: 'Allow viewing quantity entity revisions.'
restrict access: true
revert all quantity revisions:
title: 'Revert all quantity revisions'
description: 'Allow reverting to a previous quantity entity revision.'
restrict access: true
@@ -0,0 +1,51 @@
<?php
/**
* @file
* Post update hooks for the quantity module.
*/
use Drupal\Core\Entity\Entity\EntityViewMode;
use Drupal\system\Entity\Action;
/**
* Create plain text view mode for quantities.
*/
function quantity_post_update_plain_text_view_mode(&$sandbox) {
$view_mode = EntityViewMode::create([
'id' => 'quantity.plain_text',
'label' => 'Plain text',
'targetEntityType' => 'quantity',
'cache' => FALSE,
'dependencies' => [
'enforced' => [
'module' => [
'quantity',
],
],
'module' => [
'quantity',
],
],
]);
$view_mode->save();
}
/**
* Create quantity delete action.
*/
function quantity_post_update_delete_action(&$sandbox) {
$action = Action::create([
'id' => 'quantity_delete_action',
'label' => t('Delete quantity'),
'type' => 'quantity',
'plugin' => 'entity:delete_action:quantity',
'configuration' => [],
'dependencies' => [
'module' => [
'quantity',
],
],
]);
$action->save();
}
@@ -0,0 +1,7 @@
quantity.settings:
path: 'farm/settings/quantity'
defaults:
_form: '\Drupal\quantity\Form\QuantitySettingsForm'
_title: 'Quantity settings'
requirements:
_permission: 'administer quantity'
@@ -0,0 +1,7 @@
services:
quantity_event_subscriber:
class: Drupal\quantity\EventSubscriber\MapRenderEventSubscriber
arguments:
- '@config.factory'
tags:
- { name: 'event_subscriber' }
@@ -0,0 +1,268 @@
<?php
namespace Drupal\quantity\Entity;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\RevisionLogEntityTrait;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\entity\Revision\RevisionableContentEntityBase;
use Drupal\user\EntityOwnerTrait;
/**
* Defines the Quantity entity.
*
* @ingroup quantity
*
* @ContentEntityType(
* id = "quantity",
* label = @Translation("Quantity"),
* label_collection = @Translation("Quantities"),
* label_singular = @Translation("quantity"),
* label_plural = @Translation("quantities"),
* label_count = @PluralTranslation(
* singular = "@count quantity",
* plural = "@count quantities",
* ),
* handlers = {
* "storage" = "Drupal\Core\Entity\Sql\SqlContentEntityStorage",
* "access" = "\Drupal\entity\UncacheableEntityAccessControlHandler",
* "inline_form" = "\Drupal\quantity\Form\QuantityInlineForm",
* "list_builder" = "\Drupal\quantity\QuantityListBuilder",
* "permission_provider" = "\Drupal\entity\UncacheableEntityPermissionProvider",
* "view_builder" = "Drupal\quantity\QuantityViewBuilder",
* "views_data" = "Drupal\quantity\QuantityViewsData",
* "form" = {
* "default" = "Drupal\Core\Entity\ContentEntityForm",
* "add" = "Drupal\Core\Entity\ContentEntityForm",
* "edit" = "Drupal\Core\Entity\ContentEntityForm",
* "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
* "delete-multiple-confirm" = "Drupal\Core\Entity\Form\DeleteMultipleForm",
* },
* "route_provider" = {
* "default" = "Drupal\entity\Routing\AdminHtmlRouteProvider",
* "revision" = "\Drupal\entity\Routing\RevisionRouteProvider",
* },
* "local_task_provider" = {
* "default" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
* },
* },
* base_table = "quantity",
* revision_table = "quantity_revision",
* translatable = FALSE,
* revisionable = TRUE,
* show_revision_ui = FALSE,
* admin_permission = "administer quantity",
* permission_granularity = "bundle",
* entity_keys = {
* "id" = "id",
* "revision" = "revision_id",
* "bundle" = "type",
* "label" = "label",
* "owner" = "uid",
* "uuid" = "uuid",
* },
* bundle_entity_type = "quantity_type",
* common_reference_target = TRUE,
* links = {
* "delete-multiple-form" = "/quantity/delete",
* },
* revision_metadata_keys = {
* "revision_user" = "revision_user",
* "revision_created" = "revision_created",
* "revision_log_message" = "revision_log_message"
* },
* )
*/
class Quantity extends RevisionableContentEntityBase implements QuantityInterface {
use EntityChangedTrait;
use EntityOwnerTrait;
use RevisionLogEntityTrait;
/**
* {@inheritdoc}
*/
public function label() {
return $this->id->value;
}
/**
* {@inheritdoc}
*/
public function getCreatedTime() {
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function setCreatedTime($timestamp) {
$this->set('created', $timestamp);
return $this;
}
/**
* {@inheritdoc}
*/
public static function getCurrentUserId() {
return [\Drupal::currentUser()->id()];
}
/**
* {@inheritdoc}
*/
public static function getRequestTime() {
return \Drupal::time()->getRequestTime();
}
/**
* {@inheritdoc}
*/
public function getBundleLabel() {
/** @var \Drupal\quantity\Entity\QuantityTypeInterface $type */
$type = $this->entityTypeManager()
->getStorage('quantity_type')
->load($this->bundle());
return $type->label();
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::ownerBaseFieldDefinitions($entity_type);
$fields += static::revisionLogBaseFieldDefinitions($entity_type);
$fields['measure'] = BaseFieldDefinition::create('list_string')
->setLabel(t('Measure'))
->setDescription(t('The measure of the quantity.'))
->setRevisionable(TRUE)
->setSettings([
'allowed_values_function' => 'quantity_measure_field_allowed_values',
])
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'list_default',
'weight' => 0,
])
->setDisplayOptions('form', [
'type' => 'options_select',
'weight' => 0,
])
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('view', FALSE);
$fields['value'] = BaseFieldDefinition::create('fraction')
->setLabel(t('Value'))
->setDescription(t('Value of the quantity.'))
->setRevisionable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'fraction_decimal',
'weight' => 5,
'settings' => [
'precision' => 0,
'auto_precision' => TRUE,
'separator' => '/',
'prefix_suffix' => FALSE,
],
])
->setDisplayOptions('form', [
'type' => 'fraction_decimal',
'weight' => 5,
'settings' => [
'precision' => 0,
'auto_precision' => TRUE,
],
])
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('view', FALSE);
$fields['units'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Units'))
->setDescription(t('Units of the quantity.'))
->setSetting('target_type', 'taxonomy_term')
->setSetting('handler_settings', [
'target_bundles' => [
'unit' => 'unit',
],
'auto_create' => TRUE,
'auto_create_bundle' => 'unit',
])
->setSetting('handler', 'default')
->setRevisionable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'entity_reference_label',
'settings' => [
'link' => FALSE,
],
'weight' => 10,
])
->setDisplayOptions('form', [
'type' => 'entity_reference_autocomplete',
'weight' => 10,
])
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('view', FALSE);
$fields['label'] = BaseFieldDefinition::create('string')
->setLabel(t('Label'))
->setDescription(t('Label of the quantity.'))
->setRevisionable(TRUE)
->setDefaultValue('')
->setSetting('max_length', 255)
->setSetting('text_processing', 0)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => 15,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => 15,
])
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('view', FALSE);
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Authored by'))
->setDescription(t('The user ID of author of the quantity.'))
->setRevisionable(TRUE)
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setDefaultValueCallback('Drupal\quantity\Entity\Quantity::getCurrentUserId')
->setDisplayOptions('view', [
'region' => 'hidden',
])
->setDisplayOptions('form', [
'region' => 'hidden',
])
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('view', FALSE);
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Authored on'))
->setDescription(t('The time that the quantity was created.'))
->setRevisionable(TRUE)
->setDefaultValueCallback(static::class . '::getRequestTime')
->setDisplayOptions('view', [
'region' => 'hidden',
])
->setDisplayOptions('form', [
'region' => 'hidden',
])
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('view', FALSE);
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setDescription(t('The time the quantity was last edited.'))
->setRevisionable(TRUE);
return $fields;
}
}
@@ -0,0 +1,44 @@
<?php
namespace Drupal\quantity\Entity;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface for defining quantity entities.
*
* @ingroup quantity
*/
interface QuantityInterface extends ContentEntityInterface, EntityChangedInterface, RevisionLogInterface, EntityOwnerInterface {
/**
* Gets the quantity creation timestamp.
*
* @return int
* Creation timestamp of the quantity.
*/
public function getCreatedTime();
/**
* Sets the quantity creation timestamp.
*
* @param int $timestamp
* Creation timestamp of the quantity.
*
* @return \Drupal\quantity\Entity\QuantityInterface
* The quantity entity.
*/
public function setCreatedTime($timestamp);
/**
* Gets the label of the the quantity type.
*
* @return string
* The label of the quantity type.
*/
public function getBundleLabel();
}
@@ -0,0 +1,96 @@
<?php
namespace Drupal\quantity\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
/**
* Defines the quantity type entity.
*
* @ConfigEntityType(
* id = "quantity_type",
* label = @Translation("Quantity type"),
* label_collection = @Translation("Quantity types"),
* label_singular = @Translation("Quantity type"),
* label_plural = @Translation("Quantity types"),
* label_count = @PluralTranslation(
* singular = "@count quantity type",
* plural = "@count quantity types",
* ),
* handlers = {
* "access" = "\Drupal\entity\BundleEntityAccessControlHandler",
* },
* config_prefix = "type",
* bundle_of = "quantity",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* "uuid" = "uuid"
* },
* config_export = {
* "id",
* "label",
* "description",
* "new_revision",
* }
* )
*/
class QuantityType extends ConfigEntityBundleBase implements QuantityTypeInterface {
/**
* The quantity type ID.
*
* @var string
*/
protected $id;
/**
* The quantity type label.
*
* @var string
*/
protected $label;
/**
* A brief description of this quantity type.
*
* @var string
*/
protected $description;
/**
* Default value of the 'Create new revision' checkbox of the quantity type.
*
* @var bool
*/
protected $new_revision = TRUE;
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->description;
}
/**
* {@inheritdoc}
*/
public function setDescription($description) {
return $this->set('description', $description);
}
/**
* {@inheritdoc}
*/
public function shouldCreateNewRevision() {
return $this->new_revision;
}
/**
* {@inheritdoc}
*/
public function setNewRevision($new_revision) {
return $this->set('new_revision', $new_revision);
}
}
@@ -0,0 +1,14 @@
<?php
namespace Drupal\quantity\Entity;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Entity\EntityDescriptionInterface;
use Drupal\Core\Entity\RevisionableEntityBundleInterface;
/**
* Provides an interface for defining quantity type entities.
*/
interface QuantityTypeInterface extends ConfigEntityInterface, EntityDescriptionInterface, RevisionableEntityBundleInterface {
}
@@ -0,0 +1,33 @@
<?php
namespace Drupal\quantity\Event;
use Drupal\quantity\Entity\QuantityInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Event that is fired by hook_quantity_OPERATION().
*/
class QuantityEvent extends Event {
const PRESAVE = 'quantity_presave';
const DELETE = 'quantity_delete';
/**
* The Quantity entity.
*
* @var \Drupal\quantity\Entity\QuantityInterface
*/
public QuantityInterface $quantity;
/**
* Constructs the object.
*
* @param \Drupal\quantity\Entity\QuantityInterface $quantity
* The Quantity entity.
*/
public function __construct(QuantityInterface $quantity) {
$this->quantity = $quantity;
}
}
@@ -0,0 +1,61 @@
<?php
namespace Drupal\quantity\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\farm_map\Event\MapRenderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* An event subscriber for the MapRenderEvent.
*
* Adds the quantity.system_of_measurement setting to maps.
*/
class MapRenderEventSubscriber implements EventSubscriberInterface {
/**
* The config factory service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
private $configFactory;
/**
* Constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory service.
*/
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
MapRenderEvent::EVENT_NAME => 'onMapRender',
];
}
/**
* React to the MapRenderEvent.
*
* @param \Drupal\farm_map\Event\MapRenderEvent $event
* The MapRenderEvent.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function onMapRender(MapRenderEvent $event) {
// Set a cache tag on the quantity settings in case this ever changes.
$event->addCacheTags(['config:quantity.settings']);
// Add the system of measurement to drupalSettings.farm_map.units.
$measurement = $this->configFactory->get('quantity.settings')->get('system_of_measurement');
$event->element['#attached']['drupalSettings']['farm_map']['units'] = $measurement;
}
}
@@ -0,0 +1,60 @@
<?php
namespace Drupal\quantity\Form;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\inline_entity_form\Form\EntityInlineForm;
use Drupal\quantity\Entity\QuantityInterface;
/**
* Render the quantity entity in quantity inline entity forms.
*/
class QuantityInlineForm extends EntityInlineForm {
use DependencySerializationTrait;
/**
* {@inheritdoc}
*/
public function getTableFields($bundles) {
// Trick IEF into thinking there are two bundles.
// This will always render the "Quantity type" field in the table.
if (count($bundles) == 1) {
$bundles[] = $bundles[0];
}
// Get parent fields.
$fields = parent::getTableFields($bundles);
// Remove the label field.
unset($fields['label']);
// Add a field that renders the quantity entity.
$fields['quantity'] = [
'type' => 'callback',
'label' => $this->t('Quantity'),
'weight' => 1,
'callback' => [$this, 'renderQuantity'],
];
return $fields;
}
/**
* Callback that renders a quantity entity.
*
* @param \Drupal\quantity\Entity\QuantityInterface $quantity
* The quantity entity.
* @param array $theme
* Theme information.
*
* @return array
* The quantity render array.
*/
public function renderQuantity(QuantityInterface $quantity, array $theme) {
$view_builder = $this->entityTypeManager->getViewBuilder($quantity->getEntityTypeId());
return $view_builder->view($quantity);
}
}
@@ -0,0 +1,67 @@
<?php
namespace Drupal\quantity\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a quantity settings form.
*/
class QuantitySettingsForm extends ConfigFormbase {
/**
* Config settings.
*
* @var string
*/
const SETTINGS = 'quantity.settings';
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'quantity_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
static::SETTINGS,
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateinterface $form_state) {
$config = $this->config(static::SETTINGS);
$form['system_of_measurement'] = [
'#type' => 'radios',
'#title' => $this->t('System of measurement'),
'#description' => $this->t('Select the system of measurement you would like to use in farmOS. Changing this setting after data has been entered is not recommended.'),
'#options' => [
'metric' => $this->t('Metric'),
'us' => $this->t('US/Imperial'),
],
'#default_value' => $config->get('system_of_measurement'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->configFactory->getEditable(static::SETTINGS)
->set('system_of_measurement', $form_state->getValue('system_of_measurement'))
->save();
parent::submitForm($form, $form_state);
}
}
@@ -0,0 +1,101 @@
<?php
namespace Drupal\quantity\Plugin\migrate\process;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateSkipRowException;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Create quantity entities.
*
* This is an alternative to using the entity_generate process plugin which
* requires a "lookup" to happen before creating the entity. Since the quantity
* value field is a Fraction field, it is easier to use our own process plugin.
*
* @MigrateProcessPlugin(
* id = "create_quantity",
* handle_multiples = TRUE
* )
*
* @internal
*/
class CreateQuantity extends ProcessPluginBase implements ContainerFactoryPluginInterface {
/**
* Quantity entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $quantityStorage;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = new static(
$configuration,
$plugin_id,
$plugin_definition
);
$instance->quantityStorage = $container->get('entity_type.manager')->getStorage('quantity');
return $instance;
}
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$return = [];
if (is_array($value) || $value instanceof \Traversable) {
foreach ($value as $i => $new_value) {
// Start array of entity values.
$entity_values = [];
// Gather any static default values for properties/fields.
if (isset($this->configuration['default_values']) && is_array($this->configuration['default_values'])) {
foreach ($this->configuration['default_values'] as $key => $value) {
$entity_values[$key] = $value;
}
}
// Gather any additional properties/fields.
if (isset($this->configuration['values']) && is_array($this->configuration['values'])) {
foreach ($this->configuration['values'] as $key => $property) {
$new_row = new Row($new_value);
$source_value = $new_row->get($property) ?? $row->get($property);
NestedArray::setValue($entity_values, explode(Row::PROPERTY_SEPARATOR, $key), $source_value, TRUE);
}
}
// Create the entity.
/** @var \Drupal\quantity\Entity\QuantityInterface $entity */
$entity = $this->quantityStorage->create($entity_values);
// Validate the entity.
/** @var \Symfony\Component\Validator\ConstraintViolationInterface[] $violations */
$violations = $entity->validate();
if (!empty($violations)) {
foreach ($violations as $violation) {
throw new MigrateSkipRowException($violation->getPropertyPath() . '=' . $violation->getMessage());
}
}
// Save the entity so it has an ID.
$entity->save();
// Add entity to the return array.
$return[$i] = $entity;
}
}
return $return;
}
}
@@ -0,0 +1,34 @@
<?php
namespace Drupal\quantity;
use Drupal\Core\Entity\EntityInterface;
use Drupal\entity\BulkFormEntityListBuilder;
/**
* Defines a class to build a listing of Quantity entities.
*
* @ingroup quantity
*/
class QuantityListBuilder extends BulkFormEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['id'] = $this->t('ID');
$header['label'] = $this->t('Label');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/** @var \Drupal\quantity\Entity\QuantityInterface $entity */
$row['id'] = ['#markup' => $entity->id()];
$row['name'] = $entity->toLink($entity->label(), 'canonical')->toRenderable();
return $row + parent::buildRow($entity);
}
}
@@ -0,0 +1,54 @@
<?php
namespace Drupal\quantity;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityViewBuilder;
use Drupal\Core\Security\TrustedCallbackInterface;
/**
* Quantity entity view builder.
*/
class QuantityViewBuilder extends EntityViewBuilder implements TrustedCallbackInterface {
/**
* {@inheritdoc}
*/
public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
$build = parent::view($entity, $view_mode, $langcode);
// If the view mode is plain_text, add a post render callback to strip tags
// and whitespace.
if ($view_mode == 'plain_text') {
$build['#post_render'][] = [$this, 'plainText'];
}
return $build;
}
/**
* {@inheritdoc}
*/
public static function trustedCallbacks() {
return array_merge(parent::trustedCallbacks(), ['plainText']);
}
/**
* Strips HTML, newlines, and whitespace from rendered entity.
*
* @param string $value
* A string of rendered content for the Quantity entity.
*
* @return string
* The updated content.
*/
public static function plainText(string $value) {
$value = Html::decodeEntities($value);
$value = strip_tags($value);
$value = trim($value);
$value = preg_replace('/\s+/', ' ', $value);
return $value;
}
}
@@ -0,0 +1,45 @@
<?php
namespace Drupal\quantity;
use Drupal\entity\EntityViewsData;
/**
* Provides the views data for the quantity entity type.
*/
class QuantityViewsData extends EntityViewsData {
/**
* {@inheritdoc}
*/
public function getViewsData() {
$data = parent::getViewsData();
// Create a value field, filter, and sort using fraction decimal handlers.
$fraction_fields = [
'numerator' => 'value__numerator',
'denominator' => 'value__denominator',
];
$data['quantity']['value'] = [
'title' => $this->t('Value'),
'help' => $this->t('Value of the quantity, in decimal format.'),
'real field' => 'value__numerator',
'field' => [
'id' => 'fraction',
'additional fields' => $fraction_fields,
'click sortable' => TRUE,
],
'sort' => [
'id' => 'fraction',
'additional fields' => $fraction_fields,
],
'filter' => [
'id' => 'fraction',
'additional fields' => $fraction_fields,
],
];
return $data;
}
}
@@ -0,0 +1,44 @@
{#
/**
* @file
* Theme override for quantity entity fields.
*
* Available variables:
* - attributes: HTML attributes for the containing element.
* - label_hidden: Whether to show the field label or not.
* - title_attributes: HTML attributes for the title.
* - label: The label for the field.
* - multiple: TRUE if a field can contain multiple items.
* - items: List of all the field items. Each item contains:
* - attributes: List of HTML attributes for each item.
* - content: The field item's content.
* - entity_type: The entity type to which the field belongs.
* - field_name: The name of the field.
* - field_type: The type of the field.
* - label_display: The display settings for the label.
*
*/
#}
{%
set classes = [
'field',
'field--name-' ~ field_name|clean_class,
'field--type-' ~ field_type|clean_class,
'field--label-' ~ label_display,
'inline',
]
%}
{%
set quantity_base_fields = ['label', 'measure', 'value', 'units']
%}
<span{{ attributes.addClass(classes) }}>
{% if label_display != 'hidden' and field_name not in quantity_base_fields %}
<span><strong>{{ label }}</strong></span>
{% endif %}
{% for item in items %}
{{ item.content }}
{% endfor %}
</span>
@@ -0,0 +1,33 @@
{#
/**
* @file quantity.html.twig
* Default theme implementation to present quantity data.
*
* This template is used when viewing quantity entities.
*
*
* Available variables:
* - quantity: The quantity entity.
* - content: A list of content items. Use 'content' to print all content, or
* - attributes: HTML attributes for the container element.
*
* @see template_preprocess_quantity()
*
* @ingroup themeable
*/
#}
{# Filter content items into arrays to be rendered before and after the standard quantity fields. #}
{% set custom_fields = content|without('label', 'measure', 'value', 'units') %}
{% set prefix_fields = custom_fields|filter((field) => field['#weight'] and field['#weight'] < 0) %}
{% set suffix_fields = custom_fields|filter((field) => not field['#weight'] or field['#weight'] >= 0) %}
<div{{ attributes.addClass('quantity') }}>
{% if content %}
{{ prefix_fields }}
{% if content.label %}<strong>{{ content.label }}</strong>{% endif %}
{% if content.measure %}({{ content.measure }}){% endif %}
{{ content.value }} {{ content.units }}
{{ suffix_fields }}
{% endif %}
</div>