You are here

public static function MailWithTypeItem::validateMailTypes in CRM Core 8.2

#element_validate callback for possible mail types.

1 call to MailWithTypeItem::validateMailTypes()
MailWithTypeItemTest::testMailWithTypeItem in modules/crm_core_contact/tests/src/Kernel/MailWithTypeItemTest.php
Tests 'mail_with_type' field type.

File

modules/crm_core_contact/src/Plugin/Field/FieldType/MailWithTypeItem.php, line 106

Class

MailWithTypeItem
Defines the 'mail_with_type' field type.

Namespace

Drupal\crm_core_contact\Plugin\Field\FieldType

Code

public static function validateMailTypes($element, FormStateInterface $form_state) {
  $values = static::extractMailTypes($element['#value']);
  if (!is_array($values)) {
    $form_state
      ->setError($element, t('Email types list: invalid input.'));
  }
  else {

    // Check that keys are valid for the field type.
    foreach ($values as $key => $value) {
      if (Unicode::strlen($key) > 32) {
        $form_state
          ->setError($element, 'Email types list: each key must be a string at most 32 characters long.');
        break;
      }
      if (preg_match('/[^a-z0-9]/', $key)) {
        $form_state
          ->setError($element, 'Email types list: only international alphanumeric characters are allowed for keys.');
        break;
      }
    }

    // Prevent removing values currently in use.
    if ($element['#field_has_data']) {
      $lost_keys = array_keys(array_diff_key($element['#email_types'], $values));
      if (static::mailTypeInUse($element['#entity_type'], $element['#field_name'], $lost_keys)) {
        $form_state
          ->setError($element, t('Email types list: some values are being removed while currently in use.'));
      }
    }
    $form_state
      ->setValueForElement($element, $values);
  }
}