You are here

class ApplyForRoleApplicationForm in Apply for role 8

Hierarchy

Expanded class hierarchy of ApplyForRoleApplicationForm

1 string reference to 'ApplyForRoleApplicationForm'
apply_for_role.routing.yml in ./apply_for_role.routing.yml
apply_for_role.routing.yml

File

src/Form/ApplyForRoleApplicationForm.php, line 17

Namespace

Drupal\apply_for_role\Form
View source
class ApplyForRoleApplicationForm extends FormBase {
  private $application_manager;

  /**
   * Constructor, loads application manager.
   */
  public function __construct() {
    $this->application_manager = new application_manager();
  }

  // Form ID.
  public function getFormId() {
    return 'apply_for_role_application_form';
  }

  /**
   * Form builder.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('apply_for_role.settings');
    $available_roles = $config
      ->get('apply_for_role_roles') ? $config
      ->get('apply_for_role_roles') : array();
    foreach ($this
      ->what_roles_does_user_have() as $current_user_role) {
      if ($key_to_remove = array_search($current_user_role, $available_roles)) {
        unset($available_roles[$key_to_remove]);
      }
    }

    // Go through all roles, find roles with a value of 0 and unset them
    foreach ($available_roles as $available_role_key => $available_role) {
      if ($available_role === 0) {
        unset($available_roles[$available_role_key]);
      }
    }

    // @TODO: Remove roles that the user is currently already applying for?
    if (!empty($available_roles)) {
      $form['application_roles'] = array(
        '#title' => t('Role to apply for'),
        '#options' => $available_roles,
        '#required' => TRUE,
      );
      if ($config
        ->get('allow_user_message_with_app')) {
        $form['application_message'] = array(
          '#title' => 'Application Message',
          '#type' => 'textarea',
        );
      }
      if ($config
        ->get('multiple_roles_per_app') && count($available_roles) > 1) {
        $form['application_roles']['#type'] = 'checkboxes';
        $form['#description'] = t('Select the role(s) that you wish to apply for.');
        if (isset($form['application_message'])) {
          $form['application_message']['#description'] = t('Optionally, you may provide an explenation of why you wish to be accepted for this/these role(s)');
        }
      }
      else {
        $form['application_roles']['#type'] = 'radios';
        $form['#description'] = t('Select the role that you wish to apply for.');
        if (isset($form['application_message'])) {
          $form['application_message']['#description'] = t('Optionally, you may provide an explenation of why you wish to be accepted for this role');
        }
      }
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Apply for Role',
      );
    }
    else {
      $form['no_roles_available'] = array(
        '#markup' => t('Currently there are no roles available or remaining for application.'),
      );
    }
    return $form;
  }

  /**
   * Form Submission handler
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('apply_for_role.settings');
    $submited_values = $form_state
      ->cleanValues()
      ->getValues();
    $current_user_uid = \Drupal::currentUser()
      ->id();

    // Handle RID's differently based on whether multiple roles per app are allowed.
    if ($config
      ->get('multiple_roles_per_app')) {
      $rids = $submited_values['application_roles'];
      foreach ($rids as $key => $value) {
        if (!$value) {
          unset($rids[$key]);
        }
      }
    }
    else {

      // Just grab the singular value and place it in an array to send onwards!
      $rids = array(
        $submited_values['application_roles'],
      );
    }
    $message = isset($submited_values['application_message']) ? $submited_values['application_message'] : NULL;

    // Creat an application with the above gathered information
    $this->application_manager
      ->create_application($current_user_uid, $rids, $message);
    drupal_set_message(t('Thank you for submitting an applicaton. Your requested is currently queued for review.'));
  }

  /**
   * Helper function that fetches the roles a user has.
   *
   * @return array
   *   Array of roles that a user has.
   */
  protected function what_roles_does_user_have() {
    $current_user = \Drupal::currentUser();
    $roles = $current_user
      ->getRoles();

    // Remove authenticated role.
    unset($roles[0]);
    return $roles;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ApplyForRoleApplicationForm::$application_manager private property
ApplyForRoleApplicationForm::buildForm public function Form builder. Overrides FormInterface::buildForm
ApplyForRoleApplicationForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ApplyForRoleApplicationForm::submitForm public function Form Submission handler Overrides FormInterface::submitForm
ApplyForRoleApplicationForm::what_roles_does_user_have protected function Helper function that fetches the roles a user has.
ApplyForRoleApplicationForm::__construct public function Constructor, loads application manager.
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
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.