OneOfSeveralValidationRule.php in Field Validation 8
File
src/Plugin/FieldValidationRule/OneOfSeveralValidationRule.php
View source
<?php
namespace Drupal\field_validation\Plugin\FieldValidationRule;
use Drupal\Core\Field\Plugin\Field\FieldType\StringItem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field_validation\ConfigurableFieldValidationRuleBase;
use Drupal\field_validation\ConfigurableFieldValidationRuleInterface;
use Drupal\field_validation\FieldValidationRuleSetInterface;
class OneOfSeveralValidationRule extends ConfigurableFieldValidationRuleBase {
public function addFieldValidationRule(FieldValidationRuleSetInterface $field_validation_rule_set) {
return TRUE;
}
public function getSummary() {
$summary = [
'#theme' => 'field_validation_rule_summary',
'#data' => $this->configuration,
];
$summary += parent::getSummary();
return $summary;
}
public function defaultConfiguration() {
return [
'data' => '',
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['data'] = [
'#type' => 'textfield',
'#title' => $this
->t('Group name'),
'#description' => $this
->t('Specify the group name for those fields, it should be the same across those fields. Validation rules with the same group name work together.'),
'#default_value' => $this->configuration['data'] ?? '',
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$this->configuration['data'] = $form_state
->getValue('data');
}
public function validate($params) {
$flag = FALSE;
$rule = $params['rule'] ?? NULL;
$ruleset = $params['ruleset'] ?? NULL;
$context = $params['context'];
$field_values = $this
->getFieldColumnValue($params['items'], $rule->column);
$field_values = array_flip($field_values);
if (count($field_values) > 0) {
$flag = TRUE;
}
if (!$flag) {
$group_name = $rule->configuration['data'];
foreach ($ruleset
->getFieldValidationRules() as $other_group_rule) {
if ($other_group_rule
->getPluginId() !== $rule
->getPluginId() || $other_group_rule
->getUuid() === $rule
->getUuid()) {
continue;
}
$configuration = $other_group_rule
->getConfiguration();
if ($configuration['data']['data'] !== $group_name) {
continue;
}
$entity = $context
->getRoot()
->getValue();
$other_items = $entity->{$other_group_rule
->getFieldName()};
$other_field_values = $this
->getFieldColumnValue($other_items, $other_group_rule
->getColumn());
$other_field_values = array_flip($other_field_values);
if (count($other_field_values) > 0) {
$flag = TRUE;
break;
}
}
}
if (!$flag) {
$context
->addViolation($rule
->getErrorMessage());
}
return TRUE;
}
private function getFieldColumnValue($items, $column = 'value') : array {
$field_values = [];
foreach ($items as $delta => $item) {
if ($item instanceof StringItem) {
$item = $item
->getValue();
}
if (isset($item[$column]) && $item[$column] != '') {
$field_values[] = $item[$column];
}
}
return $field_values;
}
}