You are here

class ConfigPermListForm in Custom Permissions 8.2

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

Class ConfigPermListForm.

@package Drupal\config_perms\Form

Hierarchy

Expanded class hierarchy of ConfigPermListForm

1 string reference to 'ConfigPermListForm'
config_perms.routing.yml in ./config_perms.routing.yml
config_perms.routing.yml

File

src/Form/ConfigPermListForm.php, line 17

Namespace

Drupal\config_perms\Form
View source
class ConfigPermListForm extends FormBase {

  /**
   * Router Provider service.
   *
   * @var \Drupal\Core\Routing\RouteProvider
   */
  protected $routerProvider;

  /**
   * Router Builder service.
   *
   * @var \Drupal\Core\Routing\RouteBuilder
   */
  protected $routerBuilder;

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\Routing\RouteProviderInterface $router_provider
   *   The router provider service.
   * @param \Drupal\Core\Routing\RouteBuilderInterface $router_builder
   *   The router builder service.
   */
  public function __construct(RouteProviderInterface $router_provider, RouteBuilderInterface $router_builder) {
    $this->routerProvider = $router_provider;
    $this->routerBuilder = $router_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    // Instantiates this form class.
    return new static($container
      ->get('router.route_provider'), $container
      ->get('router.builder'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['perms'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Custom Permissions'),
      '#description' => '<p>' . $this
        ->t("Please note that the order in which permissions are granted are as follows:") . '</p>' . "<ul>\n       <li>" . $this
        ->t("Custom permissions only support routes") . "</li>\n\n       <li>" . $this
        ->t("User 1 still maintains full control") . "</li>\n\n       <li>" . $this
        ->t("Remove the permission 'Administer site configuration' from roles you wish to give access to only specified custom site configuration permissions") . "</li>\n\n      </ul>",
      '#collapsible' => 1,
      '#collapsed' => 0,
    ];
    $perms = CustomPermsEntity::loadMultiple();
    $header = [
      $this
        ->t('Enabled'),
      $this
        ->t('Name'),
      $this
        ->t('Route(s)'),
      '',
      '',
    ];
    $form['perms']['local'] = [
      '#type' => 'table',
      '#header' => $header,
      '#prefix' => '<div id="config_perms-wrapper">',
      '#suffix' => '</div>',
    ];

    /** @var \Drupal\config_perms\Entity\CustomPermsEntity $perm */
    foreach ($perms as $key => $perm) {
      $form['perms']['local'][$key] = [
        '#tree' => TRUE,
      ];
      $form['perms']['local'][$key]['status'] = [
        '#type' => 'checkbox',
        '#default_value' => $perm
          ->status(),
      ];
      $form['perms']['local'][$key]['name'] = [
        '#type' => 'textfield',
        '#default_value' => $perm
          ->label(),
        '#size' => 30,
      ];
      $form['perms']['local'][$key]['route'] = [
        '#type' => 'textarea',
        '#default_value' => $perm
          ->getRoute(),
        '#size' => 50,
        '#rows' => 1,
      ];

      // Delete link.
      $delete_link = $perm
        ->toLink($this
        ->t('Delete'), 'delete-form');
      $form['perms']['local'][$key]['delete'] = $delete_link
        ->toRenderable();
      $form['perms']['local'][$key]['id'] = [
        '#type' => 'hidden',
        '#default_value' => $perm
          ->id(),
      ];
    }
    $num_new = $form_state
      ->getValue('num_new');
    if (empty($num_new)) {
      $form_state
        ->setValue('num_new', '0');
    }
    for ($i = 0; $i < $form_state
      ->getValue('num_new'); $i++) {
      $form['perms']['local']['new']['status'] = [
        '#type' => 'checkbox',
        '#default_value' => '',
      ];
      $form['perms']['local']['new']['name'] = [
        '#type' => 'textfield',
        '#default_value' => '',
        '#size' => 30,
      ];
      $form['perms']['local']['new']['route'] = [
        '#type' => 'textarea',
        '#default_value' => '',
        '#rows' => 2,
        '#size' => 50,
      ];
    }
    $form['perms']['add']['status'] = [
      '#name' => 'status',
      '#id' => 'edit-local-status',
      '#type' => 'submit',
      '#value' => $this
        ->t('Add permission'),
      '#submit' => [
        '::configPermsAdminFormAddSubmit',
      ],
      '#ajax' => [
        'callback' => '::configPermsAdminFormAddCallback',
        'wrapper' => 'config_perms-wrapper',
      ],
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    ];
    return $form;
  }

  /**
   * Callback for add button.
   */
  public function configPermsAdminFormAddCallback($form, $form_state) {
    return $form['perms']['local'];
  }

  /**
   * Submit for add button.
   */
  public function configPermsAdminFormAddSubmit($form, &$form_state) {
    $form_state
      ->setValue('num_new', $form_state
      ->getValue('num_new') + 1);
    $form_state
      ->setRebuild();
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $perms = CustomPermsEntity::loadMultiple();
    foreach ($values['local'] as $key => $perm) {
      if (empty($perm['name']) && empty($perm['route']) && $key != 'new') {
        $entity = CustomPermsEntity::load($perm['id']);
        $entity
          ->delete();
      }
      else {
        if (empty($perm['name'])) {
          $form_state
            ->setErrorByName("local][" . $key . "", $this
            ->t("The name cannot be empty."));
        }
        if (empty($perm['route'])) {
          $form_state
            ->setErrorByName("local][" . $key . "", $this
            ->t("The route cannot be empty."));
        }
        if (array_key_exists($this
          ->configPermsGenerateMachineName($perm['name']), $perms) && !isset($perm['id'])) {
          $form_state
            ->setErrorByName("local][" . $key . "", $this
            ->t("A permission with that name already exists."));
        }
        if (!empty($perm['route'])) {
          $routes = config_perms_parse_path($perm['route']);
          foreach ($routes as $route) {
            if (count($this->routerProvider
              ->getRoutesByNames([
              $route,
            ])) < 1) {
              $form_state
                ->setErrorByName("local][" . $key . "", $this
                ->t("The route @route is invalid.", [
                '@route' => $perm['route'],
              ]));
            }
          }
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $perms = CustomPermsEntity::loadMultiple();
    foreach ($values['local'] as $key => $data) {

      // If new permission.
      if ($key == 'new') {
        $entity = CustomPermsEntity::create();
        $entity
          ->set('id', $this
          ->configPermsGenerateMachineName($data['name']));
      }
      else {

        // Update || Insert.
        $entity = $perms[$data['id']];
      }
      $entity
        ->set('label', $data['name']);
      $entity
        ->set('route', $data['route']);
      $entity
        ->set('status', $data['status']);
      $entity
        ->save();
    }
    $this->routerBuilder
      ->rebuild();
    $this
      ->messenger()
      ->addMessage($this
      ->t('The permissions have been saved.'));
  }

  /**
   * Generate a machine name given a string.
   */
  public function configPermsGenerateMachineName($string) {
    return strtolower(preg_replace('/[^a-zA-Z0-9_]+/', '_', $string));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigPermListForm::$routerBuilder protected property Router Builder service.
ConfigPermListForm::$routerProvider protected property Router Provider service.
ConfigPermListForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ConfigPermListForm::configPermsAdminFormAddCallback public function Callback for add button.
ConfigPermListForm::configPermsAdminFormAddSubmit public function Submit for add button.
ConfigPermListForm::configPermsGenerateMachineName public function Generate a machine name given a string.
ConfigPermListForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ConfigPermListForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ConfigPermListForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ConfigPermListForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ConfigPermListForm::__construct public function Class constructor.
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.
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.