You are here

protected function YamlFormEntityElementsValidator::validateSubmissions in YAML Form 8

Validate that element are not deleted when the form has submissions.

Return value

array|null If not valid, an array of error messages.

1 call to YamlFormEntityElementsValidator::validateSubmissions()
YamlFormEntityElementsValidator::validate in src/YamlFormEntityElementsValidator.php
Validate form elements.

File

src/YamlFormEntityElementsValidator.php, line 234

Class

YamlFormEntityElementsValidator
Defines a class to validate form elements.

Namespace

Drupal\yamlform

Code

protected function validateSubmissions() {
  if (!$this->yamlform
    ->hasSubmissions()) {
    return NULL;
  }
  $element_keys = [];
  if ($this->elements) {
    $this
      ->getElementKeysRecursive($this->elements, $element_keys);
  }
  $original_element_keys = [];
  if ($this->originalElements) {
    $this
      ->getElementKeysRecursive($this->originalElements, $original_element_keys);
  }
  if ($missing_element_keys = array_diff_key($original_element_keys, $element_keys)) {
    $messages = [];
    foreach ($missing_element_keys as $missing_element_key) {

      // Display an error message with 3 possible approaches to safely
      // deleting or hiding an element.
      $items = [];
      $items[] = $this
        ->t('<a href=":href">Delete all submissions</a> to this form.', [
        ':href' => $this->yamlform
          ->toUrl('results-clear')
          ->toString(),
      ]);
      if (\Drupal::moduleHandler()
        ->moduleExists('yamlform_ui')) {
        $items[] = $this
          ->t('<a href=":href">Delete this individual element</a> using the form UI.', [
          ':href' => Url::fromRoute('entity.yamlform_ui.element.delete_form', [
            'yamlform' => $this->yamlform
              ->id(),
            'key' => $missing_element_key,
          ])
            ->toString(),
        ]);
      }
      else {
        $items[] = $this
          ->t('<a href=":href">Enable the YAML Form UI module</a> and safely delete this element.', [
          ':href' => Url::fromRoute('system.modules_list')
            ->toString(),
        ]);
      }
      $items[] = $this
        ->t("Hide this element by setting its <code>'#access'</code> property to <code>false</code>.");
      $build = [
        'message' => [
          '#markup' => $this
            ->t('The %key element can not be removed because the %title form has <a href=":href">results</a>.', [
            '%title' => $this->yamlform
              ->label(),
            '%key' => $missing_element_key,
            ':href' => $this->yamlform
              ->toUrl('results-submissions')
              ->toString(),
          ]),
        ],
        'items' => [
          '#theme' => 'item_list',
          '#items' => $items,
        ],
      ];
      $messages[] = \Drupal::service('renderer')
        ->renderPlain($build);
    }
    return $messages;
  }
  return NULL;
}