You are here

public static function YamlFormElementBase::validateUnique in YAML Form 8

Form API callback. Validate #unique value.

File

src/YamlFormElementBase.php, line 783

Class

YamlFormElementBase
Provides a base class for a form element.

Namespace

Drupal\yamlform

Code

public static function validateUnique(array &$element, FormStateInterface $form_state) {
  $yamlform_id = $element['#yamlform'];
  $sid = $element['#yamlform_submission'];
  $name = $element['#name'];
  $value = $element['#value'];

  // Skip empty unique fields.
  if ($value == '') {
    return;
  }

  // Using range() is more efficient than using countQuery() for data checks.
  $query = Database::getConnection()
    ->select('yamlform_submission_data')
    ->fields('yamlform_submission_data', [
    'sid',
  ])
    ->condition('yamlform_id', $yamlform_id)
    ->condition('name', $name)
    ->condition('value', $value)
    ->range(0, 1);
  if ($sid) {
    $query
      ->condition('sid', $sid, '<>');
  }
  $count = $query
    ->execute()
    ->fetchField();
  if ($count) {
    $form_state
      ->setError($element, t('The value %value has already been submitted once for the %title field. You may have already submitted this form, or you need to use a different value.', [
      '%value' => $element['#value'],
      '%title' => $element['#title'],
    ]));
  }
}