You are here

public function ILTForm::save in Opigno Instructor-led Trainings 8

Same name and namespace in other branches
  1. 3.x src/Form/ILTForm.php \Drupal\opigno_ilt\Form\ILTForm::save()

Form submission handler for the 'save' action.

Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

int Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.

Overrides EntityForm::save

File

src/Form/ILTForm.php, line 220

Class

ILTForm
Provides a form for creating/editing a opigno_ilt entity.

Namespace

Drupal\opigno_ilt\Form

Code

public function save(array $form, FormStateInterface $form_state) {

  /** @var \Drupal\opigno_ilt\ILTInterface $entity */
  $entity = $this->entity;
  $date = $form_state
    ->getValue('date');
  $current_members_ids = [];
  $current_members = $form['members']['#default_value'];
  foreach ($current_members as $current_member) {
    list($type, $id) = explode('_', $current_member);
    $current_members_ids[] = $id;
  }
  if (isset($date[0]['value_wrapper'])) {
    $start_date = OpignoDateRangeWidget::createDateTimeFromWrapper($date[0]['value_wrapper']);
  }
  if (isset($date[0]['end_value_wrapper'])) {
    $end_date = OpignoDateRangeWidget::createDateTimeFromWrapper($date[0]['end_value_wrapper']);
  }
  $start_date_value = isset($start_date) ? $start_date
    ->setTimezone(new \DateTimeZone(date_default_timezone_get()))
    ->format(DrupalDateTime::FORMAT) : NULL;
  $end_date_value = isset($end_date) ? $end_date
    ->setTimezone(new \DateTimeZone(date_default_timezone_get()))
    ->format(DrupalDateTime::FORMAT) : NULL;
  $date_range = [
    'value' => $start_date_value,
    'end_value' => $end_date_value,
  ];
  $entity
    ->setDate($date_range);

  // Load added users & classes from the form_state.
  $users_ids = [];
  $classes_ids = [];
  $owner_id = $entity
    ->getOwnerId();
  $options = $form_state
    ->getValue('members');
  if (count($options)) {
    $options['user_' . $owner_id] = 'user_' . $owner_id;
  }
  foreach ($options as $option) {
    list($type, $id) = explode('_', $option);
    if ($type === 'user') {
      $users_ids[] = $id;
    }
    elseif ($type === 'class') {
      $classes_ids[] = $id;
    }
  }
  $classes = Group::loadMultiple($classes_ids);
  foreach ($classes as $class) {

    // Add class members to the users.

    /** @var \Drupal\group\Entity\Group $class */
    $members = $class
      ->getMembers();
    foreach ($members as $member) {

      /** @var \Drupal\group\GroupMembership $member */
      $user = $member
        ->getUser();
      $users_ids[] = $user
        ->id();
    }
  }
  $entity
    ->setMembersIds($users_ids);
  $trainer_name = $form_state
    ->getValue('trainer');
  if ($trainer_name != '') {
    $users = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
      'name' => $trainer_name,
    ]);
    $trainer = $users ? reset($users) : FALSE;
    if ($trainer) {
      $entity
        ->setTrainerId($trainer
        ->id());
    }
  }

  // Save entity.
  $status = parent::save($form, $form_state);

  // Prepare email notifications.
  $mail_service = \Drupal::service('plugin.manager.mail');
  $params = [];
  $params['subject'] = $params['message'] = t('Created new Instructor Led Training %meeting', [
    '%meeting' => $entity
      ->getTitle(),
  ]);
  if (\Drupal::hasService('opigno_calendar_event.iCal')) {
    $params['attachments'] = opigno_ilt_ical_prepare($entity);
  }
  $module = 'opigno_ilt';
  $key = 'upcoming_ilt_notify';

  // Set status message.
  $link = $entity
    ->toLink()
    ->toString();
  if ($status == SAVED_UPDATED) {
    $message = $this
      ->t('The Instructor-Led Training %ilt has been updated.', [
      '%ilt' => $link,
    ]);

    // Send email notifications
    // about the Instructor-Led Training for added users.
    $users = User::loadMultiple($users_ids);
    foreach ($users as $user) {
      if (!in_array($user
        ->id(), $current_members_ids)) {
        $to = $user
          ->getEmail();
        $langcode = $user
          ->getPreferredLangcode();
        $mail_service
          ->mail($module, $key, $to, $langcode, $params, NULL, TRUE);
      }
    }
  }
  else {
    $message = $this
      ->t('The Instructor-Led Training %ilt has been created.', [
      '%ilt' => $link,
    ]);
    if (empty($options) && ($training = $entity
      ->getTraining())) {
      $memberships = $training
        ->getMembers();
      if ($memberships) {
        foreach ($memberships as $membership) {
          $uid = $membership
            ->getUser()
            ->id();
          if ($uid != $entity
            ->getOwner()
            ->id()) {
            $users_ids[] = $uid;
          }
        }
      }
    }

    // Send email notifications
    // about the new Instructor-Led Training for users.
    $users = User::loadMultiple($users_ids);
    foreach ($users as $user) {
      $to = $user
        ->getEmail();
      $langcode = $user
        ->getPreferredLangcode();
      $mail_service
        ->mail($module, $key, $to, $langcode, $params, NULL, TRUE);
    }
  }
  $this
    ->messenger()
    ->addMessage($message);

  // Set redirect.
  $form_state
    ->setRedirect('entity.opigno_ilt.canonical', [
    'opigno_ilt' => $entity
      ->id(),
  ]);
  return $status;
}