crm_case-1.0.x-dev/crm_case_external_id/crm_case_external_id.module
crm_case_external_id/crm_case_external_id.module
<?php
/**
* @file
* Contains crm_case_external_id.module.
*/
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_entity_bundle_field_info_alter().
*/
function crm_case_external_id_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
if ($entity_type->id() === 'crm_case') {
if (isset($fields['external_id'])) {
// Use the ID as defined in the annotation of the constraint definition.
$fields['external_id']->addConstraint('CrmCaseExternalId', []);
}
}
}
/**
* Implements hook_form_FORM_ID_alter() for 'field_config_edit_form'.
*/
function crm_case_external_id_form_field_config_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$field = $form_state->getFormObject()->getEntity();
if ($field->getName() !== 'external_id' || $field->getTargetEntityTypeId() !== 'crm_case') {
return;
}
$crm_case_bundles = \Drupal::entityTypeManager()->getStorage('crm_case_type')->loadMultiple();
$options = [];
foreach ($crm_case_bundles as $crm_case_bundle) {
$options[$crm_case_bundle->id()] = $crm_case_bundle->label();
}
$form['third_party_settings']['external_id'] = [
'#type' => 'details',
'#title' => t('External Id settings'),
'#open' => TRUE,
'#group' => 'advanced',
'#weight' => 100,
];
$form['third_party_settings']['external_id']['bundles'] = [
'#type' => 'checkboxes',
'#title' => t('Bundles'),
'#options' => $options,
'#default_value' => $field->getThirdPartySetting('external_id', 'bundles', []),
];
$form['third_party_settings']['external_id']['negate'] = [
'#type' => 'radios',
'#title' => t('Negate'),
'#options' => [
0 => t('Include'),
1 => t('Exclude'),
],
'#default_value' => $field->getThirdPartySetting('external_id', 'negate', 0),
];
$form['#validate'][] = 'crm_case_external_id_form_field_config_form_validate';
}
/**
* Validation for 'field_config_edit_form'.
*/
function crm_case_external_id_form_field_config_form_validate(&$form, FormStateInterface $form_state) {
$third_party_settings = $form_state->getValue('third_party_settings');
$bundles = $third_party_settings['external_id']['bundles'];
$bundles = array_filter($bundles);
if (empty($bundles)) {
return;
}
$field = $form_state->getFormObject()->getEntity();
$bundle = $field->getTargetBundle();
$in_array = in_array($bundle, $bundles);
$negate = $third_party_settings['external_id']['negate'];
if ($negate && $in_array) {
$form_state->setErrorByName('third_party_settings][external_id][bundles', t('The bundle %bundle is selected and negate is enabled.', ['%bundle' => $bundle]));
}
elseif (!$negate && !$in_array) {
$form_state->setErrorByName('third_party_settings][external_id][bundles', t('The bundle %bundle is not selected and negate is disabled.', ['%bundle' => $bundle]));
}
}
