-
Notifications
You must be signed in to change notification settings - Fork 0
/
unique_field_ajax.module
493 lines (438 loc) · 16.2 KB
/
unique_field_ajax.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
<?php
/**
* @file
* Unique value for cck fields check module.
*/
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\ContentEntityType;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\Entity\BaseFieldOverride;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\Core\Cache\CacheableMetadata;
/**
* Implements hook_help().
*/
function unique_field_ajax_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the unique_field_ajax module.
case 'help.page.unique_field_ajax':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Unique Field module allows administrators to require that content supplied for specified fields is unique.') . '</p>';
return $output;
default:
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function unique_field_ajax_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$field = $form_state->getFormObject()->getEntity();
$unique_field_ajax_types = [
'string',
'list_string',
'text',
'email',
'entity_reference',
'path',
'uri',
'link',
];
if (!$field->getFieldStorageDefinition()->isMultiple()) {
if (in_array($field->getType(), $unique_field_ajax_types)) {
$form['third_party_settings']['unique_field_ajax'] = array(
'#type' => 'details',
'#group' => 'additional_settings',
'#title' => t('Unique title settings'),
'#open' => TRUE,
'#tree' => TRUE,
);
$fields = _unique_field_ajax_form_fields($field, 'third_party_settings[unique_field_ajax]');
if(!empty($fields)) {
foreach ($fields as $name => $details) {
$form['third_party_settings']['unique_field_ajax'][$name] = $details;
}
}
}
}
}
/**
* Alter forms to add unique title checkbox
* - node type add/edit.
*
* @param [type] $form
* @param FormStateInterface $form_state
* @param [type] $form_id
*
* @return void
*/
function unique_field_ajax_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (_unique_field_ajax_is_config_form($form_id)) {
$entity = $form_state->getFormObject()->getEntity();
$form['unique_field_ajax'] = array(
'#type' => 'details',
'#group' => 'additional_settings',
'#title' => t('Unique title settings'),
'#open' => TRUE,
'#tree' => TRUE,
);
$fields = _unique_field_ajax_form_fields($entity, 'unique_field_ajax');
if(!empty($fields)) {
foreach ($fields as $name => $details) {
$form['unique_field_ajax'][$name] = $details;
}
}
$form['#entity_builders'][] = '_unique_field_ajax_entity_form_builder';
}
}
/**
* Save the third party settings
*
* @param $entity_type
* @param EntityInterface $entity
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function _unique_field_ajax_entity_form_builder($entity_type, EntityInterface $entity, &$form, FormStateInterface $form_state) {
$fields = ['unique','per_lang','use_ajax','message'];
foreach ($fields as $field){
$value = $form_state->getValue(['unique_field_ajax', $field]);
if ($value) {
$entity->setThirdPartySetting('unique_field_ajax', $field, $value);
}else{
$entity->unsetThirdPartySetting('unique_field_ajax', $field);
}
}
}
/**
* Attaching data to unique fields.
*
* @param $element
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $context
*/
function unique_field_ajax_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
$field_definition = $context['items']->getFieldDefinition();
$name = $field_definition->getFieldStorageDefinition()->getName();
$label = $field_definition->getLabel();
// alter field widgets to enable unique settings
if ($field_definition instanceof FieldConfig) {
$is_unique_per_lang = NULL;
if ((\Drupal::moduleHandler()
->moduleExists('language')) && \Drupal::languageManager()
->getCurrentLanguage()
->getId()
) {
$is_unique_per_lang = $field_definition->getThirdPartySetting('unique_field_ajax', 'per_lang');
}
if ($field_definition->getThirdPartySetting('unique_field_ajax', 'unique')) {
$main_property_name = $field_definition->getFieldStorageDefinition()->getMainPropertyName();
$element[$main_property_name]['#unique_field_ajax_settings'] = [
'per_lang' => $is_unique_per_lang,
'field_definition' => $field_definition,
'field_name' => $name,
'field_label' => $label,
'message' => $field_definition->getThirdPartySetting('unique_field_ajax', 'message')
];
$element[$main_property_name]['#element_validate'][] = 'unique_field_ajax_validate_unique';
if ($field_definition->getThirdPartySetting('unique_field_ajax', 'use_ajax')) {
$element['#process'] = ['_unique_field_ajax_process'];
}
}
}
// alter title to enable unique settings
if ($field_definition instanceof BaseFieldDefinition || $field_definition instanceof BaseFieldOverride) {
$entity = NULL;
if (isset($context['form']) && isset($context['form']['#type']) && $context['form']['#type'] == 'inline_entity_form') {
$entity = $context['form']['#default_value'];
} else { $form_object = $form_state->getFormObject();
if (method_exists($form_object, 'getEntity')) {
$entity = $form_object->getEntity();
}
}
if (!$entity) {
return;
}
$entity_type = $entity->getEntityType();
if (!($entity_type instanceof ContentEntityType) || !$entity_type->hasKey('label')) {
return;
}
$entity_label = $entity_type->getKey('label');
if ($entity_label !== $name) {
return;
}
$bundle_def_id = $entity_type->getBundleEntityType();
if (!$bundle_def_id) {
return;
}
$bundle_def = \Drupal::service('entity_type.manager')->getStorage($bundle_def_id)->load($entity->bundle());
if (!$bundle_def->getThirdPartySetting('unique_field_ajax', 'unique')) {
return;
}
$is_unique_per_lang = NULL;
if ((\Drupal::moduleHandler()
->moduleExists('language')) && \Drupal::languageManager()
->getCurrentLanguage()
->getId()
) {
$is_unique_per_lang = $field_definition->getThirdPartySetting('unique_field_ajax', 'per_lang');
}
$use_ajax = $bundle_def->getThirdPartySetting('unique_field_ajax', 'use_ajax');
$element['value']['#unique_field_ajax_settings'] = [
'per_lang' => $is_unique_per_lang,
'field_definition' => $field_definition,
'field_name' => $name,
'field_label' => $entity_label,
'message' => $bundle_def->getThirdPartySetting('unique_field_ajax', 'message')
];
$element['value']['#element_validate'][] = 'unique_field_ajax_validate_unique';
if ($use_ajax) {
$element['#process'] = ['_unique_field_ajax_process'];
}
}
}
/**
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @return mixed
*/
function _unique_field_ajax(array &$form, FormStateInterface $form_state) {
$element = $form_state->getTriggeringElement();
return NestedArray::getValue($form, $element['#array_parents']);
}
/**
* Attach ajax to unique field.
*
* @param $element
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form
*
* @return mixed
*/
function _unique_field_ajax_process($element, FormStateInterface &$form_state, &$form) {
foreach (Element::children($element) as $property) {
if (isset($element[$property]) && isset($element[$property]['#unique_field_ajax_settings'])) {
$field_name = $element[$property]['#unique_field_ajax_settings']['field_name'];
$unique_field_ajax_settings = $element[$property]['#unique_field_ajax_settings'];
if ($unique_field_ajax_settings) {
$field_label = $unique_field_ajax_settings['field_label'];
$wrapper = 'unique-' . $field_name;
$form['#attached']['library'][] = 'unique_field_ajax/unique_event';
$settings = ['id' => '#' . $wrapper . ' input'];
$form['#attached']['drupalSettings']['unique_field_ajax'][] = $settings;
$element[$property]['#ajax'] = [
'callback' => '_unique_field_ajax',
'event' => 'finishedinput',
'wrapper' => $wrapper,
'progress' => [
'type' => 'throbber',
'message' => t('Verifying @field_label...',
['@field_label' => $field_label]),
],
];
$element[$property]['#prefix'] = '<div id="' . $wrapper . '">';
$element[$property]['#suffix'] = '</div>';
$value = $form_state->getValue($field_name);
$value = !empty($value) ? $value[0][$property] : NULL;
if(!isset($value)) {
return $element;
}
$entity = $form_state->getFormObject()->getEntity();
$entity_type = $entity->getEntityTypeId();
$langcode = (!empty($form_state->getValues()['langcode'][0][$property])) ?
$form_state->getValues()['langcode'][0][$property] : '0';
$valid = unique_field_ajax_is_unique($entity_type, $langcode,
$field_name,
$value, $entity->bundle(),
$element[$property]['#unique_field_ajax_settings']['per_lang'],
$entity);
$message = unique_field_ajax_custom_message($entity, $element, $valid, $property, TRUE);
if ($valid !== TRUE) {
$element[$property]['#attributes']['class'][] = 'error';
$element[$property]['#attributes']['aria-invalid'] = 'true';
$element[$property]['#suffix'] = '<div class="error">' . $message . '</div>' . $element[$property]['#suffix'];
}
}
}
}
return ($element);
}
/**
* Determine if this is a form for title-able entity config.
*
* @param string $form_id
*
* @return bool
*/
function _unique_field_ajax_is_config_form($form_id) {
$entity_config_forms = array(
'node_type_edit_form',
'node_type_add_form',
);
return in_array($form_id, $entity_config_forms);
}
function _unique_field_ajax_form_fields($field, $inputLookup = '') {
$fields['unique'] = array(
'#type' => 'checkbox',
'#title' => t("Unique"),
'#default_value' => $field->getThirdPartySetting('unique_field_ajax', 'unique'),
'#weight' => -10,
);
$fields['per_lang'] = array(
'#type' => 'checkbox',
'#title' => t("Per Language"),
'#description' => t("Do not allow duplicated content per language"),
'#default_value' => $field->getThirdPartySetting('unique_field_ajax', 'per_lang'),
'#weight' => -9,
'#states' => array(
'visible' => array(
':input[name="'.$inputLookup.'[unique]"]' => array('checked' => TRUE)
),
),
);
$fields['use_ajax'] = array(
'#type' => 'checkbox',
'#title' => t("Use Ajax"),
'#description' => t("Use ajax for validation."),
'#default_value' => $field->getThirdPartySetting('unique_field_ajax', 'use_ajax'),
'#weight' => -8,
'#states' => array(
'visible' => array(
':input[name="'.$inputLookup.'[unique]"]' => array('checked' => TRUE)
),
),
);
$description = t("The message when the value is not unique. The following tokens that can be used:");
$description .= "<br/>" . t("The placeholder <em>%link</em> can be used to display a link to the entity matching the unique value.");
$description .= "<br/>" . t("The placeholder <em>%label</em> can be used to display the field label.");
$fields['message'] = array(
'#type' => 'textarea',
'#title' => t("Error message"),
'#description' => $description,
'#default_value' => $field->getThirdPartySetting('unique_field_ajax', 'message'),
'#weight' => -7,
'#states' => array(
'visible' => array(
':input[name="'.$inputLookup.'[unique]"]' => array('checked' => TRUE)
),
),
);
return $fields;
}
/**
* Creates the default or custom message.
*
* @param $entity
* @param $element
* @param $valid
* @param $property
* @param $isAjax
*
* @return \Drupal\Component\Render\MarkupInterface|string
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityMalformedException
*/
function unique_field_ajax_custom_message($entity, $element, $valid, $property, $isAjax) {
$unique_field_ajax_settings = $isAjax ? $element[$property]['#unique_field_ajax_settings'] : $element['#unique_field_ajax_settings'];
$field_label = $unique_field_ajax_settings['field_label'];
$message = $unique_field_ajax_settings['message'];
$hasNid = $valid !== TRUE && $valid !== "0";
// default message if nothing set.
if (empty($message)) {
$message = t('The field "@field_label" has to be unique.', ['@field_label' => $field_label]);
}
// if message contains the string %link look up the matching entities.
if (strpos($message, '%link') !== FALSE ) {
$replacement = '<em>' . t('Unknown entity') . '</em>';
if($hasNid) {
$entity_with_value = \Drupal::entityTypeManager()
->getStorage($entity->getEntityTypeId())
->load($valid);
if ($entity_with_value && $entity_with_value->access('view')) {
$link = $entity_with_value->toLink(NULL, 'canonical', [
'attributes' => [
'_target' => 'blank',
],
]);
$replacement = $link->toString();
$link
->getUrl()
->toString(TRUE)
->applyTo($element);
CacheableMetadata::createFromObject($entity_with_value)
->applyTo($element);
}
}
$message = str_replace('%link', $replacement, $message);
}
// replace %label with the field label.
if (strpos($message, '%label') !== FALSE) {
$message = str_replace('%label', $field_label, $message);
}
return \Drupal\Core\Render\Markup::create($message);
}
/**
* Element Validate callback to validate a field.
*/
function unique_field_ajax_validate_unique($element, FormStateInterface $form_state, array $form) {
$field_definition = $element['#unique_field_ajax_settings']['field_definition'];
$property = $field_definition->getFieldStorageDefinition()->getMainPropertyName();
$entity = $form_state->getFormObject()->getEntity();
// If !isset langcode set it to 0.
$langcode = (
!empty($form_state->getValues()['langcode'][0]['value']) &&
$form_state->getValues()['langcode'][0]['value']) ?
$form_state->getValues()['langcode'][0]['value'] : '0';
$field_name = $element['#unique_field_ajax_settings']['field_name'];
$value = $form_state->getValue($field_name);
$entity_type = $entity->getEntityTypeId();
$per_lang = $element['#unique_field_ajax_settings']['per_lang'];
// If field is not unique set error.
$valid = unique_field_ajax_is_unique($entity_type, $langcode, $field_name, $value[0][$property], $entity->bundle(), $per_lang, $entity);
$message = unique_field_ajax_custom_message($entity, $element, $valid, $property, FALSE);
if ($valid !== TRUE) {
$form_state->setErrorByName($field_name, $message);
$form_state->setRebuild();
}
}
/**
* Test if the field value already exist in the database.
*
* @param $entity_type
* @param $langcode
* @param $field_name
* @param $field_value
* @param $bundle
* @param $is_unique_per_lang
*
* @return bool|string
* Boolean TRUE if the value is unique. In any other case, the entity ID of
* the entity that has the same value.
*/
function unique_field_ajax_is_unique($entity_type, $langcode, $field_name, $field_value, $bundle, $is_unique_per_lang, $entity) {
$entity_type_definition = Drupal::entityTypeManager()
->getDefinition($entity_type);
$query = Drupal::entityQuery($entity_type)
->range(0, 1)
->condition($field_name, $field_value, '=');
if (!$entity->isNew()) {
$query->condition($entity_type_definition->getKey('id'), $entity->id(), '<>');
}
// Test if the entity has a bundle.
if (!empty($entity_type_definition->getKey('bundle'))) {
$query->condition($entity_type_definition->getKey('bundle'), $bundle, '=');
}
// Test unique per language.
if ($is_unique_per_lang) {
$query->condition('langcode', $langcode);
}
$entities = $query->execute();
if (!empty($entities)) {
return array_shift($entities);
}
return TRUE;
}