You are here

class MeetingScoreForm in Opigno Moxtra 8

Same name and namespace in other branches
  1. 3.x src/Form/MeetingScoreForm.php \Drupal\opigno_moxtra\Form\MeetingScoreForm

Provides a form for scoring a opigno_moxtra_meeting entity.

Hierarchy

Expanded class hierarchy of MeetingScoreForm

1 string reference to 'MeetingScoreForm'
opigno_moxtra.routing.yml in ./opigno_moxtra.routing.yml
opigno_moxtra.routing.yml

File

src/Form/MeetingScoreForm.php, line 17

Namespace

Drupal\opigno_moxtra\Form
View source
class MeetingScoreForm extends FormBase {

  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Moxtra service.
   *
   * @var \Drupal\opigno_moxtra\MoxtraServiceInterface
   */
  protected $moxtraService;

  /**
   * The keyvalue storage.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueFactory
   */
  protected $keyValueStorage;

  /**
   * Creates a WorkspaceForm object.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, MoxtraServiceInterface $moxtra_service, KeyValueFactory $key_value) {
    $this->entityTypeManager = $entity_type_manager;
    $this->moxtraService = $moxtra_service;
    $this->keyValueStorage = $key_value
      ->get('opigno_moxtra');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('opigno_moxtra.moxtra_api'), $container
      ->get('keyvalue'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\opigno_moxtra\MeetingInterface $entity */
    $entity = $this
      ->getRequest()
      ->get('opigno_moxtra_meeting');
    if (!isset($entity)) {
      throw new NotFoundHttpException();
    }
    $training = $entity
      ->getTraining();
    if (!isset($training)) {
      $message = $this
        ->t('The meeting should has related training to save the presences.');
      $this
        ->messenger()
        ->addError($message);
      return $form;
    }
    $owner_id = $entity
      ->getOwnerId();
    $session_key = $entity
      ->getSessionKey();
    $info = $this->moxtraService
      ->getMeetingInfo($owner_id, $session_key);
    $status = !empty($info['data']) ? $info['data']['status'] : FALSE;
    if ($status !== 'SESSION_ENDED') {
      $message = $this
        ->t('The meeting has to be ended in order to save the presences.');
      $this
        ->messenger()
        ->addError($message);
      return $form;
    }
    $form['submit_scores'] = [
      '#type' => 'table',
      '#title' => $this
        ->t('Participants for @training', [
        '@training' => $training
          ->label(),
      ]),
      '#header' => [
        $this
          ->t('Name'),
        $this
          ->t('Attendance'),
        $this
          ->t('Score'),
      ],
    ];
    $scores =& $form['submit_scores'];

    // Load the meeting members
    // or the related training members, if there is no member restriction.
    $users = $entity
      ->getMembers();
    if (empty($users)) {
      $members = $training
        ->getMembers();
      $users = array_map(function ($member) {

        /** @var \Drupal\group\GroupMembership $member */
        return $member
          ->getUser();
      }, $members);
    }
    uasort($users, function ($user1, $user2) {

      /** @var \Drupal\user\Entity\User $user1 */

      /** @var \Drupal\user\Entity\User $user2 */
      return strcasecmp($user1
        ->getDisplayName(), $user2
        ->getDisplayName());
    });

    // Load the existing meeting results.

    /** @var \Drupal\opigno_moxtra\MeetingResultInterface[] $results */
    $results = $this->entityTypeManager
      ->getStorage('opigno_moxtra_meeting_result')
      ->loadByProperties([
      'meeting' => $entity
        ->id(),
    ]);

    // Reindex results by the user ID.
    $results_by_user = [];
    array_walk($results, function ($result) use (&$results_by_user) {

      /** @var \Drupal\opigno_moxtra\MeetingResultInterface $result */
      $results_by_user[$result
        ->getUserId()] = $result;
    });

    // Get the user IDs of the actual participants of the meeting.
    $participants = !empty($info['data']) ? array_map(function ($participant) {
      $prefix = $this->keyValueStorage
        ->get('prefix');
      $prefix = empty($prefix) ? '' : $prefix;
      $replace_pattern = [
        'm_' . $prefix,
        $prefix . '_',
        $prefix,
        'm_',
      ];
      return empty($participant['unique_id']) ? 1 : str_replace($replace_pattern, '', $participant['unique_id']);
    }, $info['data']['participants']) : [];
    foreach ($users as $user) {
      $id = $user
        ->id();
      if (isset($results_by_user[$id])) {

        // If result for this meeting and user is exists, use it.

        /** @var \Drupal\opigno_moxtra\MeetingResultInterface $result */
        $result = $results_by_user[$id];
        $attendance = $result
          ->getStatus();
        $score = $result
          ->getScore();
      }
      else {

        // Else get the default values.
        if (in_array($id, $participants)) {
          $attendance = 1;
          $score = 100;
        }
        else {
          $attendance = 0;
          $score = 0;
        }
      }
      $scores[$id]['name'] = $user
        ->toLink()
        ->toRenderable();
      $scores[$id]['attendance'] = [
        '#type' => 'select',
        '#options' => [
          0 => $this
            ->t('Absent'),
          1 => $this
            ->t('Attended'),
        ],
        '#default_value' => $attendance,
      ];
      $scores[$id]['score'] = [
        '#type' => 'number',
        '#min' => 0,
        '#max' => 100,
        '#step' => 1,
        '#default_value' => $score,
      ];
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save attendances'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    /** @var \Drupal\opigno_moxtra\MeetingInterface $entity */
    $entity = $this
      ->getRequest()
      ->get('opigno_moxtra_meeting');
    $scores = $form_state
      ->getValue('submit_scores');
    foreach ($scores as $user_id => $values) {
      $status = $values['attendance'];
      $score = $values['score'];

      // Try load existing result.

      /** @var \Drupal\opigno_moxtra\MeetingResultInterface[] $results */
      $results = $this->entityTypeManager
        ->getStorage('opigno_moxtra_meeting_result')
        ->loadByProperties([
        'meeting' => $entity
          ->id(),
        'user_id' => $user_id,
      ]);
      $result = current($results);
      if ($result === FALSE) {

        // Create new result.
        $result = MeetingResult::create();
        $result
          ->setMeeting($entity);
        $result
          ->setUserId($user_id);
      }

      // Update values.
      $result
        ->setStatus($status);
      $result
        ->setScore($score);
      $result
        ->save();

      // Update user achievements.
      $gid = $entity
        ->getTrainingId();
      if (isset($gid)) {
        $step = opigno_learning_path_get_meeting_step($gid, $user_id, $entity);
        opigno_learning_path_save_step_achievements($gid, $user_id, $step, 0);
        opigno_learning_path_save_achievements($gid, $user_id, TRUE);
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
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. 1
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. Overrides UrlGeneratorTrait::redirect
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 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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.
MeetingScoreForm::$entityTypeManager protected property Entity type manager.
MeetingScoreForm::$keyValueStorage protected property The keyvalue storage.
MeetingScoreForm::$moxtraService protected property Moxtra service.
MeetingScoreForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MeetingScoreForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MeetingScoreForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MeetingScoreForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MeetingScoreForm::__construct public function Creates a WorkspaceForm object.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.