You are here

class DeleteAchievementsForm in Opigno Learning path 3.x

Same name and namespace in other branches
  1. 8 src/Form/DeleteAchievementsForm.php \Drupal\opigno_learning_path\Form\DeleteAchievementsForm

Class LearningPathAdminSettingsForm.

Hierarchy

Expanded class hierarchy of DeleteAchievementsForm

File

src/Form/DeleteAchievementsForm.php, line 19

Namespace

Drupal\opigno_learning_path\Form
View source
class DeleteAchievementsForm extends ConfirmFormBase {

  /**
   * Group.
   *
   * @var \Drupal\group\Entity\Group
   */
  protected $group;

  /**
   * Database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * DeleteAchievementsForm constructor.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('database'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'opigno_learning_path_delete_achievements';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $group = NULL) {
    $form = parent::buildForm($form, $form_state);
    if (isset($group)) {
      $this->group = $group;
      $form['group'] = [
        '#type' => 'hidden',
        '#value' => $group
          ->id(),
      ];
    }
    $form['actions']['submit']['#name'] = 'submit';
    $form['actions']['cancel']['#type'] = 'submit';
    $form['actions']['cancel']['#name'] = 'cancel';
    $form['actions']['cancel']['#value'] = $this
      ->getCancelText();
    $is_ajax = $this
      ->getRequest()
      ->isXmlHttpRequest();
    if ($is_ajax) {
      $form['actions']['cancel']['#ajax'] = [
        'callback' => [
          $this,
          'closeModal',
        ],
        'event' => 'click',
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this
      ->t('The contents of that training has changed. If you start again that training, your previous achievements for it will be deleted. Do you want to continue?');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    if (isset($this->group)) {
      return $this->group
        ->toUrl();
    }
    else {
      return Url::fromRoute('<front>');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('Yes');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelText() {
    return $this
      ->t('No');
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $element = $form_state
      ->getTriggeringElement();
    if (isset($element['#name'])) {
      if ($element['#name'] === 'submit') {
        $uid = $this
          ->currentUser()
          ->id();
        $gid = $form_state
          ->getValue('group');
        if (isset($gid)) {
          $this->database
            ->delete('opigno_learning_path_step_achievements')
            ->condition('uid', $uid)
            ->condition('gid', $gid)
            ->execute();
          $this->database
            ->delete('opigno_learning_path_achievements')
            ->condition('uid', $uid)
            ->condition('gid', $gid)
            ->execute();
          $group = Group::load($gid);
          if (isset($group)) {

            // Load modules of a LP group.
            $modules = $group
              ->getContentEntities('opigno_module_group');

            // Delete all answers connected to this user and LP.
            $this
              ->deleteAnswers((int) $group
              ->id(), $uid, $modules);
            $module = reset($modules);
            if (!empty($module)) {

              // Create new unfinished user module attempt on the first module
              // of training to disable the training resume.
              $attempt = UserModuleStatus::create([]);
              $attempt
                ->setModule($module);
              $attempt
                ->setFinished(0);
              $attempt
                ->save();
            }
          }
          $form_state
            ->setRedirect('opigno_learning_path.steps.start', [
            'group' => $gid,
          ]);
        }
      }
      elseif ($element['#name'] === 'cancel') {
        $form_state
          ->setRedirectUrl($this
          ->getCancelUrl());
      }
    }
  }

  /**
   * Delete answers.
   */
  private function deleteAnswers(int $group_id, int $uid, array $modules) {
    foreach ($modules as $module) {
      if (!$module instanceof OpignoModule) {
        continue;
      }
      $user_module_statuses = \Drupal::entityTypeManager()
        ->getStorage('user_module_status')
        ->loadByProperties([
        'learning_path' => $group_id,
        'user_id' => $uid,
        'module' => $module
          ->id(),
      ]);
      foreach ($user_module_statuses as $status) {
        if (!$status instanceof UserModuleStatus) {
          continue;
        }
        $answers = $status
          ->getAnswers();
        foreach ($answers as $answer) {
          $answer
            ->delete();
        }
      }
    }
  }

  /**
   * Returns ajax response.
   */
  public function closeModal(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response
      ->addCommand(new CloseModalDialogCommand());
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
DeleteAchievementsForm::$database protected property Database connection.
DeleteAchievementsForm::$group protected property Group.
DeleteAchievementsForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
DeleteAchievementsForm::closeModal public function Returns ajax response.
DeleteAchievementsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DeleteAchievementsForm::deleteAnswers private function Delete answers.
DeleteAchievementsForm::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormBase::getCancelText
DeleteAchievementsForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
DeleteAchievementsForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
DeleteAchievementsForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
DeleteAchievementsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DeleteAchievementsForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
DeleteAchievementsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DeleteAchievementsForm::__construct public function DeleteAchievementsForm constructor.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 72
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.