You are here

function unique_field_ajax_custom_message in Unique field ajax 2.x

Creates the default or custom message.

Parameters

\Drupal\Core\Entity\EntityBase $entity: Entity object.

array $element: Element array.

bool|int $valid: Is valid state.

string $property: Property value.

bool $isAjax: Is ajax.

Return value

\Drupal\Component\Render\MarkupInterface Returns the custom message.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityMalformedException

2 calls to unique_field_ajax_custom_message()
unique_field_ajax_validate_unique in ./unique_field_ajax.module
Element Validate callback to validate a field.
_unique_field_ajax_process in ./unique_field_ajax.module
Attach ajax to unique field.

File

./unique_field_ajax.module, line 423
Unique value for cck fields check module.

Code

function unique_field_ajax_custom_message(EntityBase $entity, array $element, $valid, string $property, bool $isAjax) : MarkupInterface {
  $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 Markup::create($message);
}