Form validation handler for widget elements.

@param array $element
The form element.
@param \Drupal\Core\Form\FormStateInterface $form_state
The form state.
960544
public static function validateElement(array $element, FormStateInterface $form_state) {
    if ($element['#required'] && $element['#value'] == '_none') {
      $form_state->setError($element, t('@name field is required.', ['@name' => $element['#title']]));
    }

    // Save the value in the element key_column.
    // Note: there is only one item because the field is not multiple value.
    $items = [$element['#key_column'] => $element['#value']];

    $form_state->setValueForElement($element, $items);
  }
932849
public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->configFactory()
      ->getEditable('openy_upgrade_tool.settings')
      ->set('force_mode', $form_state->getValue('force_mode'))
      ->save();
  }
976204
public static function el(array &$form, FormStateInterface $form_state) {
    $trigger = $form_state->getTriggeringElement();
    return NestedArray::getValue($form, array_slice($trigger['#array_parents'], 0, -1));
  }
673766
public function validateBlocks(ElementInterface $element)
    {
        /** @var Element $element */
        /** @var SuperTableBlockQuery $value */
        $value = $element->getFieldValue($this->handle);

        foreach ($value->all() as $i => $block) {
            /** @var SuperTableBlock $block */
            if ($element->getScenario() === Element::SCENARIO_LIVE) {
                $block->setScenario(Element::SCENARIO_LIVE);
            }

            if (!$block->validate()) {
                foreach ($block->getErrors() as $attribute => $errors) {
                    $element->addErrors([
                        "{$this->handle}[{$i}].{$attribute}" => $errors,
                    ]);
                }
            }
        }
    }
191984
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // If there are any form errors, re-display the form.
    if ($form_state->hasAnyErrors()) {
      $response->addCommand(new ReplaceCommand('#modal_openy_campaign_login_form', $form));

      return $response;
    }

    $storage = $form_state->getStorage();

    // For existed and logged in during validation members. All other cases were checked during validation.
    if ($storage['status'] === 'loggedin') {
      /** @var \Drupal\node\Entity\Node $campaign Campaign object. */
      $campaign = $storage['campaign'];

      // Get default values from settings.
      $config = $this->config('openy_campaign.general_settings');

      $msgSuccess = $config->get('successful_login');
      $modalMessage = check_markup($msgSuccess['value'], $msgSuccess['format']);
      // Get message from Campaign node.
      if (!empty($campaign->field_successful_login->value)) {
        $modalMessage = check_markup($campaign->field_successful_login->value, $campaign->field_successful_login->format);
      }

      // Login before Campaign start.
      $localeCampaignStartDate = OpenYLocaleDate::createDateFromFormat($campaign->get('field_campaign_start_date')->getString());
      if (!$localeCampaignStartDate->dateExpired()) {
        $msgNotStarted = $config->get('error_login_checkins_not_started');
        $modalMessage = check_markup($msgNotStarted['value'], $msgNotStarted['format']);
        // Get message from Campaign node.
        if (!empty($campaign->field_login_checkins_not_started->value)) {
          $modalMessage = check_markup($campaign->field_login_checkins_not_started->value, $campaign->field_login_checkins_not_started->format);
        }
      }

      $landingPageId = $form_state->getValue('landing_page_id');
      $queryParameters = [];
      if (!empty($landingPageId)) {
        $landingPage = $this->nodeStorage->load($landingPageId);
        $queryParameters = [trim($landingPage->toUrl()->toString(), "/")];
      }

      $response->addCommand(new ReplaceCommand('#modal_openy_campaign_login_form', $modalMessage));

      $response->addCommand(new InvokeCommand('#drupal-modal', 'closeDialog', $queryParameters));

      return $response;
    }

    return $response;
  }
42497
private function validate($element)
    {
        $violationList = $this->validator->validate($element, null, ['Generator']);
        if (0 < $violationList->count()) {
            $this->output->writeln('<error>Invalid element</error>');
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
            foreach ($violationList as $violation) {
                $this->output->writeln(sprintf('<error>%s : %s</error>', $violation->getPropertyPath(), $violation->getMessage()));
            }

            return false;
        }

        return true;
    }
355819
protected function addFormElements(\Zend_Form $form)
    {
        if ($this->user->hasEmailAddress()) {
            $order = count($form->getElements())-1;
            $createElement = new \MUtil_Form_Element_FakeSubmit('create_account');
            $createElement->setLabel($this->_('Create account mail'))
                        ->setAttrib('class', 'button')
                        ->setOrder($order++);

            $form->addElement($createElement);

            $resetElement = new \MUtil_Form_Element_FakeSubmit('reset_password');
            $resetElement->setLabel($this->_('Reset password mail'))
                        ->setAttrib('class', 'button')
                        ->setOrder($order++);
            $form->addElement($resetElement);
        }

        parent::addFormElements($form);
    }
714968
private function buildInputFilterFromForm(InputFilterInterface $inputFilter) : void
    {
        /** @var DOMElement $node */
        foreach ($this->getNodeList() as $name => $node) {
            if ($inputFilter->has($name)) {
                continue;
            }

            // Detect element type
            $type = $node->getAttribute('type');
            if ($node->tagName === 'textarea') {
                $type = 'textarea';
            } elseif ($node->tagName === 'select') {
                $type = 'select';
            }

            // Add validation
            if (array_key_exists($type, $this->formElements)) {
                $elementClass = $this->formElements[$type];
            } else {
                // Create a default validator
                $elementClass = $this->formElements['text'];
            }

            /** @var InputProviderInterface $element */
            $element = new $elementClass($node, $this->document);
            $input   = $this->factory->createInput($element);
            $inputFilter->add($input, $name);
        }
    }
948454
public function validateSegment($element, FormStateInterface $formState)
    {
        $originalValue = trim($formState->getValue('segment'));

        if (!empty($originalValue)) {

            $value = $this->seoService->normalizeSegment($originalValue);

            if ($originalValue !== $value) {
                $formState->setError(
                    $element,
                    $this->t(
                        "The alias '%alias' is invalid and has been normalized to: <strong>%normalized</strong>, please change the value below.",
                        ['%alias' => $originalValue, '%normalized' => $value]
                    )
                );
            }

            $formState->setValueForElement($element, $value);
        }
    }
186469
public function validateForm(FormEvent $event)
    {
        $form = $event->getForm();

        if ($form->isRoot()) {
            // Form groups are validated internally (FormValidator). Here we don't set groups as they are retrieved into the validator.
            foreach ($this->validator->validate($form) as $violation) {
                // Allow the "invalid" constraint to be put onto
                // non-synchronized forms
                // ConstraintViolation::getConstraint() must not expect to provide a constraint as long as Symfony\Component\Validator\ExecutionContext exists (before 3.0)
                $allowNonSynchronized = (null === $violation->getConstraint() || $violation->getConstraint() instanceof Form) && Form::NOT_SYNCHRONIZED_ERROR === $violation->getCode();

                $this->violationMapper->mapViolation($violation, $form, $allowNonSynchronized);
            }
        }
    }
1147882
public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $node = &$form_state->getTemporaryValue('node');
        $site = $this->siteManager->getContext();
        $site->home_nid = $node->id();

        $this->siteManager->getStorage()->save($site, ['home_nid']);

        $form_state->setRedirect('node/' . $node->nid);
    }
1187057
protected function registerElements() {
		$this->action_mode = self::ACTION_GET;
		
		$validatorBool = new \OWeb\utils\inputManagement\validators\Boolean();
		
		$jsString = new \OWeb\utils\inputManagement\validators\JsString();
		
		$this->setAction('refresh');
		
		$active = new \Controller\OWeb\Helpers\Form\Elements\Text();
		$active->init();
		$active->setName('active');
		$active->setTitle('Active');
		$active->setDescription("Which panel is currently open.");
		$active->addValidator(new \OWeb\utils\inputManagement\validators\Integer());
		$active->addValidator(new \OWeb\utils\inputManagement\validators\CanBeEmpty());
		$active->setVal(0);
		$this->addDisplayElement($active);
		
		$animate = new \Controller\OWeb\Helpers\Form\Elements\Text();
		$animate->init();
		$animate->setName('animate');
		$animate->setTitle('Animate');
		$animate->setVal('Animate');
		$animate->addValidator($jsString);
		$animate->setDescription("If and how to animate changing panels.");
		//$this->addDisplayElement($animate);
		
		$collapsible = new \Controller\OWeb\Helpers\Form\Elements\Radio();
		$collapsible->init();
		$collapsible->setName('collapsible');
		$collapsible->setTitle('Collapsible');
		$collapsible->add("true", "true");
		$collapsible->add("false", "false");
		$collapsible->addValidator($validatorBool);
		$collapsible->setVal('true');
		$collapsible->setDescription("hether all the sections can be closed at once. Allows collapsing the active section");
		$this->addDisplayElement($collapsible);
		
		$disabled = new \Controller\OWeb\Helpers\Form\Elements\Radio();
		$disabled->init();
		$disabled->setName('disabled');
		$disabled->setTitle('Disabled');
		$disabled->add("true", "true");
		$disabled->add("false", "false");
		$disabled->addValidator($validatorBool);
		$disabled->setVal('false');
		$disabled->setDescription("Disables the accordion if set to true.");
		$this->addDisplayElement($disabled);
		
		$event = new \Controller\OWeb\Helpers\Form\Elements\Text();
		$event->init();
		$event->setName('event');
		$event->setTitle('Event');
		$event->setVal('click');
		$event->addValidator($jsString);
		$event->setDescription("The event that accordion headers will react to in order to activate the associated panel. Multiple events can be specified, separated by a space.");
		$this->addDisplayElement($event);
		
		$heightStyle = new \Controller\OWeb\Helpers\Form\Elements\Select();
		$heightStyle->init();
		$heightStyle->setName('heightStyle');
		$heightStyle->setTitle('Height Style');
		$heightStyle->add("Auto", "auto");
		$heightStyle->add("Fill", "fill");
		$heightStyle->add("Content", "content");
		$heightStyle->addValidator($jsString);
		$heightStyle->setVal('auto');
		$heightStyle->setDescription("Controls the height of the accordion and each panel.");
		$this->addDisplayElement($heightStyle);
		
		$submit = new \Controller\OWeb\Helpers\Form\Elements\Submit();
		$submit->init();
		$submit->setVal("Refresh");
		$this->addDisplayElement($submit);
	}
741823
private function clearForm(array $values, FormStateInterface &$form_state) {
    $input = $form_state->getUserInput();

    foreach ($values as $value) {
      if ($form_state->hasValue($value)) {
        $form_state->unsetValue($value);
      }

      if (isset($input[$value])) {
        unset($input[$value]);
      }
    }

    $form_state->setUserInput($input);
  }
695767
protected function isElementHasError(ElementInterface $element, FormInterface $form)
    {
        if ($element->getMessages()) {
            return true;
        }

        $elementName = $this->normalizeElementName($element->getName());
        $elements = $this->getInvalidFieldsetElements($element, $form);
        if (isset($elements[$elementName]) && $elements[$elementName] === $element) {
            return true;
        }

        return false;
    }
206692
function renderElement(&$element, $required, $error)
    {
        $elAry = $this->_elementToArray($element, $required, $error);
        if (!empty($error)) {
            $this->_ary['errors'][$elAry['name']] = $error;
        }
        $this->_storeArray($elAry);
    }
637417
public function cancelSubmit(array &$form, FormStateInterface $form_state)
    {
        if ($this->manager->getPageContext()->isTemporary()) {
            $this->manager->getPageContext()->rollback();

            drupal_set_message($this->t("Changes have been dropped"), 'error');

            $form_state->setRedirect(
                current_path(),
                ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_PAGE_TOKEN])]
            );
        }
    }
167806
public function validate(FormEvent $event)
    {
        /** @var Alias $alias */
        $alias = $event->getData()->getNode()->alias;

        if ($alias instanceof ValueHolderInterface) {
            $alias = $alias->getWrappedValueHolderValue();
        }

        $violations = $this->validator->validate($alias);

        if (!$violations) {
            return;
        }

        $mapper = new ViolationMapper();
        /** @var ConstraintViolationInterface $violation */
        foreach ($violations as $violation) {
            $mapper->mapViolation($violation, $event->getForm(), true);
        }
    }