user_dashboard_bootstrap-1.0.2/src/Form/UserDashboardByRole.php

src/Form/UserDashboardByRole.php
<?php

namespace Drupal\user_dashboard_bootstrap\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user_dashboard_bootstrap\UserDashboardBlocks;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Set show block dashboard by role.
 */
class UserDashboardByRole extends ConfigFormBase {

  /**
   * Name of the form.
   *
   * @var string
   */
  public static string $formName = 'user_dashboard_bootstrap.role';

  /**
   * Roles list.
   *
   * @var array
   */
  protected mixed $roles;

  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typedConfigManager
   *   The Type config manager service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\user_dashboard_bootstrap\UserDashboardBlocks $userDashboardBlocks
   *   The service of userdashboard.
   * @param \Drupal\Core\Database\Connection $database
   *   Service database.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(ConfigFactoryInterface $config_factory, protected TypedConfigManagerInterface $typedConfigManager, protected EntityTypeManagerInterface $entityTypeManager, protected UserDashboardBlocks $userDashboardBlocks, protected Connection $database) {
    parent::__construct($config_factory, $typedConfigManager);
    $this->roles = $this->entityTypeManager->getStorage('user_role');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new self(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('entity_type.manager'),
      $container->get('user_dashboard_bootstrap.blocks'),
      $container->get('database'),
    );
  }

  /**
   * Configuration name.
   *
   * @inheritDoc
   */
  protected function getEditableConfigNames() {
    return [self::$formName];
  }

  /**
   * Form ID.
   *
   * @inheritDoc
   */
  public function getFormId() {
    return 'user_dashboard_role_form';
  }

  /**
   * Build form.
   *
   * @inheritDoc
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config(self::$formName);
    $blocks = $this->userDashboardBlocks->listBlocks();
    $blocksAvailable = $this->config('user_dashboard_bootstrap.settings')->get('user_dashboard_available_blocks');
    if (!empty($blocksAvailable)) {
      foreach ($blocks as $delta => $block) {
        if (empty($blocksAvailable[$delta])) {
          unset($blocks[$delta]);
        }
      }
    }
    $regions = $this->userDashboardBlocks->getRegions();
    $moduleConfig = $this->config('user_dashboard_bootstrap.settings');
    if ($moduleConfig->get('gridstack')) {
      $main['main']['user_dashboard_main'] = $regions['main']['user_dashboard_main'];
      $regions = $main;
    }
    $roles = $this->roles->loadMultiple();
    // Remove role anonymous.
    unset($roles['anonymous']);
    $numRow = [1 => [12], 2 => [8, 4]];
    $form['link'] = [
      '#type' => 'link',
      '#title' => $this->t('Back to configuration'),
      '#url' => Url::fromRoute('user_dashboard_bootstrap.settings'),
      '#attributes' => ['class' => ['btn', 'btn-success']],
    ];
    $form['layout'] = [
      '#type' => 'link',
      '#title' => $this->t('Set user dashboard layout by role'),
      '#url' => Url::fromRoute('user_dashboard_bootstrap.user_role_layout'),
      '#attributes' => ['class' => ['btn', 'btn-warning', 'ms-2']],
    ];
    $form['lock'] = [
      '#type' => 'link',
      '#title' => $this->t('Lock user layout'),
      '#url' => Url::fromRoute('user_dashboard_bootstrap.user_lock_block'),
      '#attributes' => ['class' => ['btn', 'btn-info', 'ms-2']],
    ];
    $form['#attached']['library'] = ['user_dashboard_bootstrap/user_dashboard'];
    foreach ($roles as $role) {
      $roleBlock = 'dashboard-' . $role->id();
      $form[$roleBlock] = [
        '#type' => 'details',
        '#title' => $role->label(),
        '#summary' => $role->label(),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#attributes' => ['class' => ['clearfix']],
        '#id' => 'dashboard',
      ];
      foreach ($regions as $index => $row) {
        $countRow = count($row);
        $i = 0;

        $form[$roleBlock][$index] = [
          '#type' => 'container',
          '#attributes' => ['class' => ['row', 'layout-row']],
        ];
        foreach ($row as $id => $region) {
          $col = $numRow[$countRow][$i++];
          $layoutCol = 'layout-column--half';
          if ($col == 8) {
            $layoutCol = 'layout-column--three-quarter';
          }
          if ($col == 4) {
            $layoutCol = 'layout-column--quarter';
          }
          $configName = $id . '-' . $role->id();
          $valuesBlock = $config->get($configName);
          $form[$roleBlock][$index][$configName] = [
            '#title' => $region['name'],
            '#type' => 'checkboxes',
            '#multiple' => TRUE,
            '#options' => $blocks,
            '#default_value' => !empty($valuesBlock) ? $valuesBlock : [],
            '#prefix' => '<div class="user-dashboard-checkbox layout-column ' . $layoutCol . ' col-' . $col . '">',
            '#suffix' => '</div>',
          ];
        }
      }

    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * Submit form.
   *
   * @inheritDoc
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      if (stripos($key, 'user_dashboard') !== 0) {
        continue;
      }
      $value = array_diff($value, [0]);
      if (!empty($value)) {
        $this->config(self::$formName)->set($key, $value)->save();
        [$region, $role] = explode('-', $key);
        foreach ($value as $blockId) {
          // Get all user by role.
          $uidRoles = $this->entityTypeManager->getStorage('user')
            ->getQuery()
            ->accessCheck(TRUE)
            ->condition('status', 1)
            ->condition('roles', $role)
            ->execute();
          if (!empty($uidRoles)) {
            foreach ($uidRoles as $user) {
              $query = $this->database->select('user_dashboard_block', 'b')
                ->fields('b', ['bid'])
                ->condition('delta', $blockId)
                ->condition('uid', $user);
              $bid = $query->execute()->fetchField();
              if (empty($bid)) {
                $this->database->insert('user_dashboard_block')
                  ->fields(['delta', 'status', 'weight', 'region', 'uid'])
                  ->values([$blockId, 1, 0, $region, $user])
                  ->execute();
              }
            }
          }
        }
      }
    }
    parent::submitForm($form, $form_state);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc