AJAX callback handler that displays any errors or a success message.

@param array $form
@param \Drupal\Core\Form\FormStateInterface $form_state

@return \Drupal\Core\Ajax\AjaxResponse
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;
  }
1199026
public function buildForm(array $form, FormStateInterface $form_state, $course_esid = NULL) {
    $this->course_esid = (int) $course_esid;
    if ($this->course_esid) {
      $step = (object) $this->databaseCourses->loadStep($this->course_esid);
      $this->step = $step;
      $this->course_id = $step->course_id;
      $this->course_sid = $step->course_sid;
      $this->course_eid = $step->course_eid;
    }
    return parent::buildForm($form, $form_state);
  }
696368
public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $site    = &$form_state->getTemporaryValue('site');
        $values  = &$form_state->getValues();

        /** @var $site Site */
        $site->title          = $values['title'];
        $site->title_admin    = $values['title_admin'];
        $site->http_redirects = $values['http_redirects'];
        $site->replacement_of = $values['replacement_of'];
        $site->http_host      = $values['http_host'];
        $site->allowed_protocols = $values['allowed_protocols'];
        $site->theme          = $values['theme'];
        $attributes = $form_state->getValue('attributes', []);
        foreach ($attributes as $name => $attribute) {
            $site->setAttribute($name, $attribute);
        }

        $this->manager->getStorage()->save($site);
        drupal_set_message($this->t("Site modifications have been saved"));

        $this->dispatcher->dispatch('site:update', new SiteEvent($site, $this->currentUser()->uid));

        $form_state->setRedirect('admin/dashboard/site/' . $site->id);
    }
1347033
public function validate(Form $form) : void
    {
        if ($this->presenter->isAjax())
        {
            foreach ($form->getErrors() as $error)
            {
                $this->presenter->notificationAjax('Chyba', $error, 'error');
            }
        }
    }
5902
public function updateErrorBox($form, $result, $errors)
    {
        if (($form->isSubmitted() && $result !== true) || count($errors) > 0) {
            if (is_string($result)) {
                $this->addError(new Error(
                    Error::GENERAL_ERROR,
                    $result
                ));
            } else if (count($errors) > 0) {
                foreach ($errors as $error) {
                    $this->addError($error);
                }
            } else {
                $this->addError(new Error(
                    Error::UNKNOWN_ERROR,
                    ''
                ));
            }
        }
    }
46875
private function getErrorResponse(FormInterface $form)
    {
        $errors = $form->getErrors();
        $errorCollection = [];

        foreach ($errors as $error) {
            $errorCollection[] = $error->getMessage();
        }

        return new JsonResponse([
            'messages' => $errorCollection,
        ], 400);
    }
436464
def form_invalid(self, form, prefix=None):
        
        response = super(FormAjaxMixin, self).form_invalid(form)
        if self.request.is_ajax():
            data = {
                "errors_list": self.add_prefix(form.errors, prefix),
            }
            return self.json_to_response(status=400, json_data=data,
                                         json_status=AjaxResponseStatus.ERROR)
        return response
531161
public function submitForm(array &$form, FormStateInterface $form_state) {
    $entity = $this->getEntity();
    $entity->delete();

    \Drupal::logger('openy_campaign')->notice('@type: deleted %title.', [
      '@type' => $this->entity->bundle(),
      '%title' => $this->entity->label(),
    ]);
    $form_state->setRedirect('entity.openy_campaign_mapping_branch.collection');
  }
523137
public function saveTransversalSubmit(array &$form, FormStateInterface $form_state)
    {
        if ($this->manager->getSiteContext()->isTemporary()) {
            $this->manager->getSiteContext()->commit();

            drupal_set_message(t("Changed have been saved"));

            $form_state->setRedirect(
                current_path(),
                ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_SITE_TOKEN])]
            );
        }
    }
901231
private function stepOneValidation(array &$form, FormStateInterface $form_state) {
    $campaignID = $form_state->getValue('campaign_id');
    $membershipID = $form_state->getValue('membership_id');

    /** @var \Drupal\node\Entity\Node $campaign Current campaign. */
    $campaign = $this->nodeStorage->load($campaignID);
    $extended_registration = $campaign->field_campaign_ext_registration->value;

    $config = $this->config('openy_campaign.general_settings');
    $errorDefault = $config->get('error_msg_default');
    // Get error from Campaign node.
    if (!empty($campaign->field_error_default->value)) {
      $errorDefault = check_markup($campaign->field_error_default->value, $campaign->field_error_default->format);
    }

    // Check MemberCampaign entity.
    $memberCampaignID = MemberCampaign::findMemberCampaign($membershipID, $campaignID);

    // If the member is already registered, there will be a basic error message “This member has already registered”.
    if ($memberCampaignID) {
      $form_state->setErrorByName('membership_id', $this->t('This member has already registered.'));
      return;
    }

    /** @var \Drupal\openy_campaign\Entity\Member $member Load or create Temporary Member entity. Will be saved by submit. */
    $member = Member::loadMemberFromCRMData($membershipID);
    // Membership ID must be valid Personify entry only if extended registration is disabled.
    // Because for enabled extended registration it could be also invite code, not membership ID.
    if (!$extended_registration && (($member instanceof Member === FALSE) || empty($member))) {
      $form_state->setErrorByName('membership_id', $errorDefault);
      return;
    }

    // If member was found in Personify - process they as usual.
    if ($member instanceof Member) {
      $isInactiveMember = empty($member->order_number->value);
      if ($isInactiveMember) {
        $msgMemberInactive = $config->get('error_msg_member_is_inactive');
        $errorMemberInactive = check_markup($msgMemberInactive['value'], $msgMemberInactive['format']);
        // Get error from Campaign node.
        if (!empty($campaign->field_error_member_is_inactive->value)) {
          $errorMemberInactive = check_markup($campaign->field_error_member_is_inactive->value, $campaign->field_error_member_is_inactive->format);
        }
        $form_state->setErrorByName('membership_id', $errorMemberInactive);
        return;
      }

      // If User does not have an assigned branch he is now allowed to register.
      $isEmptyBranch = empty($member->branch->entity);
      if ($isEmptyBranch) {
        $msgAudienceMessages = $config->get('error_msg_target_audience_settings');
        $errorAudience = check_markup(
          $msgAudienceMessages['value'],
          $msgAudienceMessages['format']
        );
        // Get error from Campaign node.
        if (!empty($campaign->field_error_target_audience->value)) {
          $errorAudience = check_markup(
            $campaign->field_error_target_audience->value,
            $campaign->field_error_target_audience->format
          );
        }
        $form_state->setErrorByName('membership_id', $errorAudience);
        return;
      }
      else {
        $form_state->set('branch', $member->branch->entity);
      }

      /** @var \Drupal\openy_campaign\Entity\MemberCampaign $memberCampaign Create temporary MemberCampaign entity. Will be saved by submit. */
      $memberCampaign = MemberCampaign::createMemberCampaign($member, $campaign, 'portal');
      if (($memberCampaign instanceof MemberCampaign === FALSE) || empty($memberCampaign)) {
        $form_state->setErrorByName('membership_id', $errorDefault);
        return;
      }

      // Check Target Audience Settings from Campaign.
      $validateAudienceErrorMessages = $memberCampaign->validateTargetAudienceSettings();
      // Member is ineligible due to the Target Audience Setting.
      if (!empty($validateAudienceErrorMessages)) {
        $errorText = implode('<br>', $validateAudienceErrorMessages);
        $form_state->setErrorByName('membership_id',
          $this->t('This member is not eligible for the campaign for the following reasons:<br>@errors', ['@errors' => $errorText]));
        return;
      }

      $personifyEmail = $member->getPersonifyEmail();
      if (!empty($personifyEmail)) {
        $form_state->setTemporaryValue('personify_email', $personifyEmail);
      }
    }
    else {
      // This was an invite code.
      $member = Member::loadMemberFromInvite($membershipID);

      /** @var \Drupal\openy_campaign\Entity\MemberCampaign $memberCampaign Create temporary MemberCampaign entity. Will be saved by submit. */
      $memberCampaign = MemberCampaign::createMemberCampaign($member, $campaign, 'portal');
      if (($memberCampaign instanceof MemberCampaign === FALSE) || empty($memberCampaign)) {
        $form_state->setErrorByName('membership_id', $errorDefault);
        return;
      }
    }

    // Save Member and MemberCampaign entities in storage to save by submit.
    $form_state->set('member', $member);
    $form_state->set('campaign', $campaign);
    $form_state->set('member_campaign', $memberCampaign);
  }
951628
function (form) {
              // Special case: if the user is being redirected to this page for the
              // first time, don't display any error.
              if (form.data && !form.data.password && !form.data.passwordAgain) {
                return helpers.render(req, res, view, { form: form, organization: req.organization });
              }

              var formErrors = helpers.collectFormErrors(form);
              helpers.render(req, res, view, { form: form, formErrors: formErrors });
            }
1274947
public function editSubmit(array &$form, FormStateInterface $form_state)
    {
        if (!$this->manager->getPageContext()->isTemporary()) {

            // @todo Generate a better token (random).
            $token  = drupal_get_token();
            $layout = $this->manager->getPageContext()->getCurrentLayout();
            $this->manager->getPageContext()->setToken($token);

            // Saving the layout will force it be saved in the temporary storage.
            $this->manager->getPageContext()->getStorage()->save($layout);

            $form_state->setRedirect(
                current_path(),
                ['query' => [ContextManager::PARAM_PAGE_TOKEN => $token] + drupal_get_query_parameters()]
            );
        }
    }
181944
public function success(Form $form) : void
    {
        if ($this->presenter->isAjax())
        {
            $values = $form->getValues();

            try
            {
                $this->onPageManager->savePrimary($this->activePage, $values->title, $values->description, $values->indexingType, $values->isCanonical);

                $this->presenter->notificationAjax(
                    'On-Page faktory',
                    'On-Page faktory byly úspěšně upraveny.',
                    'success',
                    FALSE
                );

                $this->onSave();
            }
            catch (DatabaseException $exception)
            {
                $this->presenter->notificationAjax(
                    'Chyba',
                    $exception->getMessage(),
                    'error'
                );
            }
        }
    }
1340690
public function process(Request $request, FormInterface $form)
    {
        if ($request->isMethod('POST')) {
            $form->submit($request);
            if ($form->isValid()) {
                return true;
            }
        }

        return false;
    }
381561
public function rebuildAjaxCallback(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $state = $this->state;
    $location = !empty($values['location_select']) ? $values['location_select'] : $values['location'];
    $filter_date = !empty($values['date_select']) ? $values['date_select'] : $values['date'];
    $tz = \Drupal::config('system.date')->get('timezone.default');
    $date = new \DateTime($filter_date, new \DateTimeZone($tz));
    $filter_date = $date->format('n/d/y');

    $parameters = [
      'location' => $location,
      'filter_date' => $filter_date,
    ];
    $triggering_element = $form_state->getTriggeringElement();

    if (isset($triggering_element['#name']) && $triggering_element['#name'] == 'location') {
      $parameters['location'] = $triggering_element['#value'];
    }
    if (isset($triggering_element['#name']) && $triggering_element['#name'] == 'location_select' && $state['class'] != 'any') {
      $parameters['class'] = $state['class'];
      $parameters['filter_length'] = 'week';
      $parameters['category'] = $state['category'];
      $parameters['groupex_class'] = 'groupex_table_class_individual';
      $parameters['view_mode'] = 'class';
    }
    if (isset($triggering_element['#name']) && $triggering_element['#name'] == 'class_select' && $triggering_element['#value'] != 'any') {
      $parameters['class'] = $triggering_element['#value'];
      $parameters['filter_length'] = 'week';
      $parameters['category'] = $state['category'];
      $parameters['groupex_class'] = 'groupex_table_class_individual';
      $parameters['view_mode'] = 'class';
    }
    if (isset($triggering_element['#name']) && $triggering_element['#name'] == 'instructor_select') {
      $parameters['class'] = $state['class'];
      $parameters['filter_length'] = 'week';
      $parameters['category'] = $state['category'];
      $parameters['groupex_class'] = 'groupex_table_instructor_individual';
      if ($triggering_element['#value'] != 'any') {
        $parameters['instructor'] = $triggering_element['#value'];
      }
    }
    if (isset($triggering_element['#name']) && $triggering_element['#name'] == 'category_select' && $triggering_element['#value'] != 'any') {
      $parameters['class'] = $state['class'];
      $parameters['filter_length'] = 'week';
      $parameters['groupex_class'] = 'groupex_table_instructor_individual';
      if ($triggering_element['#value'] != 'any') {
        $parameters['category'] = $state['category'];;
      }
    }

    $formatted_results = self::buildResults($form, $form_state);
    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#groupex-full-form-wrapper .groupex-results', $formatted_results));
    $response->addCommand(new InvokeCommand(NULL, 'groupExLocationAjaxAction', [$parameters]));

    $link = [
      '#title' => $this->t('Download PDF'),
      '#type' => 'link',
      '#url' => $this->groupexHelper->getPdfLink($parameters['location']),
      '#attributes' => [
        'class' => [
          'btn',
          'btn-default',
          'pdf-link',
        ],
      ],
    ];
    $groupex_pdf_link = $link;

    $response->addCommand(new HtmlCommand('#groupex-full-form-wrapper .groupex-pdf-link-container', $groupex_pdf_link));

    $form_state->setRebuild();
    return $response;
  }
236280
public function render(FormInterface $form, $renderMode = null)
    {
        if (method_exists($form, 'prepare')) {
            $form->prepare();
        }

        $fieldsetHelper = $this->getFieldsetHelper();
        if (method_exists($fieldsetHelper, 'setForm')) {
            $fieldsetHelper->setForm($form);
        }

        if (null === $renderMode) {
            $renderMode = $form->getOption('render_mode');
        }

        $rollbackRenderMode = null;
        if ($renderMode && $fieldsetHelper instanceof FormCollection) {
            $elementHelper = $this->view->plugin($fieldsetHelper->getDefaultElementHelper());
            if ($elementHelper instanceof FormRow) {
                $rollbackRenderMode = $elementHelper->getRenderMode();
                if ($rollbackRenderMode !== $renderMode) {
                    $elementHelper->setRenderMode($renderMode);
                }
            }
        }

        $formMessagesHelper = $this->getFormMessagesHelper();

        $markup = $this->openTag($form)
            . $formMessagesHelper($form)
            . $fieldsetHelper($form, false, false)
            . $this->closeTag();

        if ($rollbackRenderMode) {
            $elementHelper->setRenderMode($rollbackRenderMode);
        }

        return $markup;
    }
870471
public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $node = $form_state->getTemporaryValue('node');
        $site = $this->siteManager->getContext();

        $this->nodeManager->deleteReferenceBulkFromSite($site->getId(), [$node->id()]);

        drupal_set_message($this->t("%title has been removed from site %site", [
            '%title'  => $node->title,
            '%site'   => $site->title,
        ]));

        $form_state->setRedirect('node/' . $node->id());
    }