-
Notifications
You must be signed in to change notification settings - Fork 0
/
field_autovalue.module
70 lines (58 loc) · 2.14 KB
/
field_autovalue.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/**
* @file
* Field Autovalue module.
*/
declare(strict_types = 1);
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldConfigInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_form_alter().
*/
function field_autovalue_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id): void {
/** @var \Drupal\field\FieldConfigInterface $field_config */
$field_config = $form_state->getBuildInfo()['callback_object']->getEntity();
/** @var \Drupal\field_autovalue\Plugin\FieldAutovalueManager $plugin_manager */
$plugin_manager = \Drupal::service('plugin.manager.field_autovalue');
$options = $plugin_manager->getSelectOptionsForFieldType($field_config->getType());
if (!$options) {
return;
}
$form['third_party_settings']['field_autovalue']['autovalue'] = [
'#type' => 'select',
'#title' => t('Autovalue plugin'),
'#description' => t('Which autovalue plugin to use in order to generate automatic values for this field.'),
'#options' => $options,
'#default_value' => $field_config->getThirdPartySetting('field_autovalue', 'autovalue'),
'#empty_option' => t('No plugin'),
];
}
/**
* Implements hook_entity_presave().
*/
function field_autovalue_entity_presave(EntityInterface $entity): void {
if (!$entity instanceof ContentEntityInterface) {
return;
}
foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
if (!$definition instanceof FieldConfigInterface) {
continue;
}
$plugin = $definition->getThirdPartySetting('field_autovalue', 'autovalue');
if ($plugin === NULL || $plugin === '') {
continue;
}
try {
/** @var \Drupal\field_autovalue\Plugin\FieldAutovalueInterface $instance */
$instance = \Drupal::service('plugin.manager.field_autovalue')->createInstance($plugin);
$instance->setAutovalue($entity->get($field_name));
}
catch (PluginException $exception) {
// Something went wrong with the plugin instantiation, we do nothing.
continue;
}
}
}