You are here

public function EnrollRequestModalForm::submitModalFormAjax in Open Social 10.2.x

Same name and namespace in other branches
  1. 8.9 modules/social_features/social_event/src/Form/EnrollRequestModalForm.php \Drupal\social_event\Form\EnrollRequestModalForm::submitModalFormAjax()
  2. 10.3.x modules/social_features/social_event/src/Form/EnrollRequestModalForm.php \Drupal\social_event\Form\EnrollRequestModalForm::submitModalFormAjax()
  3. 10.0.x modules/social_features/social_event/src/Form/EnrollRequestModalForm.php \Drupal\social_event\Form\EnrollRequestModalForm::submitModalFormAjax()
  4. 10.1.x modules/social_features/social_event/src/Form/EnrollRequestModalForm.php \Drupal\social_event\Form\EnrollRequestModalForm::submitModalFormAjax()

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

File

modules/social_features/social_event/src/Form/EnrollRequestModalForm.php, line 82

Class

EnrollRequestModalForm
SendToDestinationsForm class.

Namespace

Drupal\social_event\Form

Code

public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  if ($form_state
    ->getErrors()) {

    // If there are errors, we can show the form again with the errors in
    // the status_messages section.
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
    $form_state
      ->setRebuild();
    return $response
      ->addCommand(new OpenModalDialogCommand($this
      ->t('Request to enroll'), $form, static::getDataDialogOptions()));
  }

  // Refactor this into a service or helper.
  $message = $form_state
    ->getValue('message');
  $current_user = \Drupal::currentUser();
  $uid = $current_user
    ->id();
  $nid = $form_state
    ->getValue('event');

  // Default event enrollment field set.
  $fields = [
    'user_id' => $uid,
    'field_event' => $nid,
    'field_enrollment_status' => '0',
    'field_account' => $uid,
    'field_request_or_invite_status' => EventEnrollmentInterface::REQUEST_PENDING,
    'field_request_message' => $message,
  ];

  // Create a new enrollment for the event.
  $enrollment = EventEnrollment::create($fields);
  $enrollment
    ->save();

  // On success leave a message and reload the page.
  \Drupal::messenger()
    ->addStatus(t('Your request has been sent successfully'));
  return $response
    ->addCommand(new CloseDialogCommand());
}