You are here

class UserDefaultPageConfigEntityForm in User Default Page 8

Same name and namespace in other branches
  1. 8.2 src/Form/UserDefaultPageConfigEntityForm.php \Drupal\user_default_page\Form\UserDefaultPageConfigEntityForm

Class UserDefaultPageConfigEntityForm.

@package Drupal\user_default_page\Form

Hierarchy

Expanded class hierarchy of UserDefaultPageConfigEntityForm

File

src/Form/UserDefaultPageConfigEntityForm.php, line 19

Namespace

Drupal\user_default_page\Form
View source
class UserDefaultPageConfigEntityForm extends EntityForm {
  protected $entityTypeManager;
  protected $linkGenerator;
  protected $pathValidator;

  /**
   * UserDefaultPageConfigEntityForm constructor.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, LinkGeneratorInterface $linkGenerator, PathValidatorInterface $pathValidator) {
    $this->entityTypeManager = $entityTypeManager;
    $this->linkGenerator = $linkGenerator;
    $this->pathValidator = $pathValidator;
  }

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

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $user_default_page_config_entity = $this->entity;
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $user_default_page_config_entity
        ->label(),
      '#description' => $this
        ->t("Label for the User default page."),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $user_default_page_config_entity
        ->id(),
      '#machine_name' => [
        'exists' => '\\Drupal\\user_default_page\\Entity\\UserDefaultPageConfigEntity::load',
      ],
      '#disabled' => !$user_default_page_config_entity
        ->isNew(),
    ];
    $form['roles_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('User / Role'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    ];
    $roles = [
      '' => '-Select-',
    ];
    foreach (user_roles(TRUE) as $role) {
      $roles[$role
        ->id()] = $role
        ->label();
    }
    $form['roles_fieldset']['user_roles'] = [
      '#title' => $this
        ->t('User Roles'),
      '#type' => 'select',
      '#description' => $this
        ->t("Select user roles"),
      '#options' => $roles,
      '#default_value' => $user_default_page_config_entity
        ->getUserRoles(),
      '#multiple' => TRUE,
    ];
    $form['roles_fieldset']['markup'] = [
      '#markup' => '<b>' . $this
        ->t('Select Role or User or both.') . '</b>',
    ];
    $user_values = $user_default_page_config_entity
      ->getUsers();
    $uids = explode(',', $user_values);
    $user_entity = $this->entityTypeManager
      ->getStorage('user');
    $default_users = $user_entity
      ->loadMultiple($uids);
    $form['roles_fieldset']['users'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#selection_settings' => [
        'include_anonymous' => FALSE,
      ],
      '#title' => $this
        ->t('Select User'),
      '#description' => $this
        ->t('Type Username here. Add multiple users as comma separated.'),
      '#tags' => TRUE,
      '#default_value' => $default_users,
    ];
    $weights = [
      -1 => '-None',
    ];
    for ($wi = 0; $wi <= 10; $wi++) {
      $weights[$wi] = $wi;
    }
    $form['roles_fieldset']['weight'] = [
      '#title' => $this
        ->t('Rule Weight'),
      '#type' => 'select',
      '#description' => $this
        ->t('The higher the value, the higher priority it receives.'),
      '#options' => $weights,
      '#default_value' => $user_default_page_config_entity
        ->getWeight(),
      '#multiple' => FALSE,
    ];
    $form['login_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Login'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $form['login_fieldset']['login_redirect'] = [
      '#title' => $this
        ->t('Redirect to URL'),
      '#type' => 'textfield',
      '#size' => 64,
      '#description' => $this
        ->t("Enter the internal path."),
      '#default_value' => $user_default_page_config_entity
        ->getLoginRedirect(),
    ];
    $form['login_fieldset']['login_redirect_message'] = [
      '#title' => $this
        ->t('Message'),
      '#type' => 'textarea',
      '#description' => $this
        ->t("Enter the message to be displayed."),
      '#default_value' => $user_default_page_config_entity
        ->getLoginRedirectMessage(),
    ];
    $form['logout_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Logout'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $form['logout_fieldset']['logout_redirect'] = [
      '#title' => $this
        ->t('Redirect to URL'),
      '#type' => 'textfield',
      '#size' => 64,
      '#description' => $this
        ->t("Enter the internal path."),
      '#default_value' => $user_default_page_config_entity
        ->getLogoutRedirect(),
    ];
    $form['logout_fieldset']['logout_redirect_message'] = [
      '#title' => $this
        ->t('Message'),
      '#type' => 'textarea',
      '#description' => $this
        ->t("Enter the message to be displayed."),
      '#default_value' => $user_default_page_config_entity
        ->getLogoutRedirectMessage(),
    ];
    return $form;
  }

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

    // Get Values.
    $values = $form_state
      ->getValues();
    $form_id = $values['form_id'];
    $roles = $values['user_roles'];
    $users = $values['users'];
    if ($roles == NULL && $users == NULL) {
      $form_state
        ->setErrorByName('user_roles', $this
        ->t("Select atleast one role / user"));
      $form_state
        ->setErrorByName('users', "");
    }
    if ($form_id != 'user_default_page_config_entity_edit_form') {

      // Load all entities belongs to "user_default_page_config_entity".
      $entities_load = $this->entityTypeManager
        ->getStorage('user_default_page_config_entity')
        ->loadMultiple();
      $user_roles = $values['user_roles'];
      $current_user = $users[0]['target_id'];

      // Check roles for any existence.
      foreach ($entities_load as $entity) {

        // Check users for any existence.
        $users_array = $entity
          ->getUsers();
        if (strstr($users_array, $current_user)) {
          $form_state
            ->setErrorByName('users', $this
            ->t("User is already present"));
        }

        // Check roles for any existence.
        if ($entity
          ->getUserRoles() == $user_roles && $user_roles == ' ') {
          global $base_url;
          $url = Url::fromUri($base_url . '/admin/config/user_default_page_config_entity/' . $entity
            ->id() . '/edit');
          $internal_link = Link::fromTextAndUrl($this
            ->t('edit'), $url)
            ->toString();
          $form_state
            ->setErrorByName('user_roles', $this
            ->t("The Role <b>'@user_roles'</b> is already present in @label. You can @edit here", [
            '@user_roles' => $user_roles,
            '@label' => $entity
              ->get('label'),
            '@edit' => $internal_link,
          ]));
        }
      }
    }
    if (!$this->pathValidator
      ->isValid($form_state
      ->getValue('logout_redirect'))) {
      $form_state
        ->setErrorByName('redirect_to', $this
        ->t("The Logout redirect path '@link_path' is either invalid or you do not have access to it.", [
        '@link_path' => $form_state
          ->getValue('logout_redirect'),
      ]));
    }
    if (!$this->pathValidator
      ->isValid($form_state
      ->getValue('login_redirect'))) {
      $form_state
        ->setErrorByName('redirect_to', $this
        ->t("The Login redirect path '@link_path' is either invalid or you do not have access to it.", [
        '@link_path' => $form_state
          ->getValue('login_redirect'),
      ]));
    }
    $login_redirect = $values['login_redirect'];
    $logout_redirect = $values['logout_redirect'];
    if ($login_redirect == NULL && $logout_redirect == NULL) {
      $form_state
        ->setErrorByName('login_redirect', $this
        ->t("Fill Login / Logout Redirection path(s)"));
      $form_state
        ->setErrorByName('logout_redirect', $this
        ->t("Fill Login / Logout Redirection path(s)"));
    }
    parent::validateForm($form, $form_state);
  }

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

    // Get User input values.
    $input = $form_state
      ->getUserInput();
    $user_default_page_config_entity = $this->entity;
    $user_input = $input['users'];
    if (!empty($user_input)) {
      $uids = explode(',', $user_input);
      $users_array = '';
      foreach ($uids as $uid) {
        preg_match('#\\((.*?)\\)#', $uid, $match);
        $users_array .= $match[1] . ',';
      }
      $user_default_page_config_entity
        ->setUsers($users_array);
    }
    $status = $user_default_page_config_entity
      ->save();
    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this
          ->t('Created the %label User default page.', [
          '%label' => $user_default_page_config_entity
            ->label(),
        ]));
        break;
      default:
        drupal_set_message($this
          ->t('Saved the %label User default page.', [
          '%label' => $user_default_page_config_entity
            ->label(),
        ]));
    }
    $form_state
      ->setRedirectUrl($user_default_page_config_entity
      ->urlInfo('collection'));
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
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.
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.
UserDefaultPageConfigEntityForm::$entityTypeManager protected property The entity type manager. Overrides EntityForm::$entityTypeManager
UserDefaultPageConfigEntityForm::$linkGenerator protected property The link generator. Overrides LinkGeneratorTrait::$linkGenerator
UserDefaultPageConfigEntityForm::$pathValidator protected property
UserDefaultPageConfigEntityForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UserDefaultPageConfigEntityForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
UserDefaultPageConfigEntityForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
UserDefaultPageConfigEntityForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
UserDefaultPageConfigEntityForm::__construct public function UserDefaultPageConfigEntityForm constructor.