You are here

public function FlaggingCollectionForm::validateForm in Flag Lists 8

Same name and namespace in other branches
  1. 4.0.x src/Form/FlaggingCollectionForm.php \Drupal\flag_lists\Form\FlaggingCollectionForm::validateForm()

Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level validation handler, otherwise an exception will be thrown.

Overrides ContentEntityForm::validateForm

File

src/Form/FlaggingCollectionForm.php, line 91

Class

FlaggingCollectionForm
Form controller for Flagging collection edit forms.

Namespace

Drupal\flag_lists\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {

  // Check that the name isn't empty.
  if (strlen($form_state
    ->getValue('name')[0]['value']) == 0) {
    $form_state
      ->setErrorByName('name', $this
      ->t('Please provide a name.'));
  }

  // Check if this is a new instance or if we are editing an existing.
  if ($form_state
    ->getFormObject() instanceof EntityFormInterface) {
    $entity_new = $form_state
      ->getFormObject()
      ->getEntity()
      ->isNew();
  }

  // Verify that the name is not longer than 32 charaters.
  if (strlen($form_state
    ->getValue('name')[0]['value']) > 32) {
    $form_state
      ->setErrorByName('name', $this
      ->t('Please provide a name that is maximum 32 characters long.'));
  }

  // Verify that the Flag doesn't already exist as that would
  // cause problem.
  $flagService = \Drupal::service('flag');

  // Create the machineId.
  $machineId = strtolower($form_state
    ->getValue('name')[0]['value']);
  $machineId = preg_replace("/[^a-z0-9_]/", "_", $machineId);
  $exists = $flagService
    ->getFlagById($machineId);

  // Check if this is a new instance.
  if (!empty($exists) && $entity_new) {
    $form_state
      ->setErrorByName('name', $this
      ->t('The Name is already in use. Please provide a unique name.'));
  }
  parent::validateForm($form, $form_state);
}