Commit 095bc9e7 authored by logickal's avatar logickal Committed by Mateu Aguiló Bosch

fix(Form): Enforce unicity of form elements (#2892024 by logickal, mkolar, vpeltot)

parent 9a67e446
...@@ -161,6 +161,57 @@ class JsonapiResourceConfigForm extends EntityForm { ...@@ -161,6 +161,57 @@ class JsonapiResourceConfigForm extends EntityForm {
return $form; return $form;
} }
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$form_values = $form_state->getValues();
$resourceFields = $form_values['resourceFields'];
$overrides = [];
// Get the field values
foreach ($resourceFields as $field => $data) {
// Only get the overridden fields.
if ($data['fieldName'] != $data['publicName']) {
// Store the publicName for comparison.
$overrides[$field] = $data['publicName'];
}
}
// Compare the overrides and find any duplicate values.
$deduped_overrides = array_unique($overrides);
$dupes = array_diff_assoc($overrides, $deduped_overrides);
// Set an error if there are duplicates.
if ($dupes) {
foreach ($dupes as $field => $value) {
$form_state->setErrorbyName('resourceFields][' . $field . '][publicName', $this->t('The override must be unique.'));
}
}
// Now compare the overrides with the default names to validate no dupes exist.
foreach ($overrides as $field => $override) {
if (array_key_exists($override, $resourceFields)) {
$form_state->setErrorByName('resourceFields][' . $field . '][publicName', $this->t('The override must be unique.'));
}
}
// Validate URL and resource type
$resource_types = $this->entityTypeManager
->getStorage('jsonapi_resource_config')
->loadByProperties(['disabled' => FALSE]);
foreach ($resource_types as $id => $resource_type) {
if ($this->entity->id() == $id) {
continue;
}
if ($resource_type->get('resourceType') == $form_values['resourceType']) {
$form_state->setErrorByName('resourceType', $this->t('There is already resource (:name) with this override.', [':name' => $resource_type->id()]));
}
if ($resource_type->get('path') == $form_values['path']) {
$form_state->setErrorByName('path', $this->t('There is already resource (:name) with this path.', [':name' => $resource_type->id()]));
}
}
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment