knowledge-8.x-1.x-dev/src/Form/CompetencyRoleForm.php

src/Form/CompetencyRoleForm.php
<?php

namespace Drupal\knowledge\Form;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\Config;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\knowledge\KnowledgeCompetencyServiceInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Role for the Competency entity.
 *
 * @ingroup knowledge
 */
class CompetencyRoleForm extends FormBase {

  /**
   * The user role storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $roleStorage;

  /**
   * The knowledge settings config.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $settings;

  /**
   * The competency service.
   *
   * @var \Drupal\knowledge\KnowledgeCompetencyServiceInterface
   */
  protected $competency;

  /**
   * The Competency Role settings.
   *
   * @param \Drupal\Core\Config\Config $settings
   *   The settings.
   * @param \Drupal\Core\Entity\EntityStorageInterface $role_storage
   *   The role storage.
   * @param \Drupal\knowledge\KnowledgeCompetencyServiceInterface $competency
   *   The competency service.
   */
  public function __construct(Config $settings, EntityStorageInterface $role_storage, KnowledgeCompetencyServiceInterface $competency) {
    $this->settings = $settings;
    $this->roleStorage = $role_storage;
    $this->competency = $competency;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory')->getEditable('knowledge.competency.settings'),
      $container->get('entity_type.manager')->getStorage('user_role'),
      $container->get('knowledge.competency'),
    );
  }

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'knowledge_competency_role_settings';
  }

  /**
   * Defines the settings form for Competency entities.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   Form definition array.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $all_roles = $this->getRoles(TRUE);
    $competency = $this->competency->get();
    $competency_roles = $this->competency->getRoleIds();

    $roles = $this->roleStorage->loadMultiple($competency_roles);
    $form['roles'] = [
      '#type' => 'select',
      '#title' => $this->t('Roles'),
      '#options' => $all_roles,
      '#multiple' => TRUE,
      '#default_value' => $competency_roles,
    ];

    $form['role_weight'] = [
      '#type' => 'table',
      '#title' => $this->t('Fields'),
      '#header' => [
        $this->t('Role'),
        $this->t('Weight'),
        $this->t('Action'),
        $this->t('Promote'),
      ],
      '#tabledrag' => [[
        'action' => 'order',
        'relationship' => 'sibling',
        'group' => 'draggable-weight',
      ],
      ],
    ];
    $weight_delta = round(count($competency_roles) / 2);
    $promote_options = [
      '_none' => $this->t('None'),
      '_self' => $this->t('Promote to this role'),
      '_next' => $this->t('Promote next role'),
    ];
    $promote_options = array_merge($promote_options, $competency_roles);
    foreach ($competency as $info) {
      $role = $info['role'];
      $title = $roles[$role]?->label() ?? $role ?? $this->t('Unknown role');
      $form['role_weight']['#tabledrag'][] = [
        'action' => 'match',
        'relationship' => 'sibling',
        'group' => 'field-role-select',
        'subgroup' => 'field-role-' . $role,
        'hidden' => FALSE,
      ];
      $form['role_weight']['#tabledrag'][] = [
        'action' => 'order',
        'relationship' => 'sibling',
        'group' => 'field-weight',
        'subgroup' => 'field-weight-' . $role,
      ];

      $form['role_weight'][$role] = [
        '#attributes' => [
          'class' => ['role-title', 'role-title-' . $role, 'draggable'],
          'no_striping' => TRUE,
        ],
      ];

      $form['role_weight'][$role]['title'] = [
        '#theme_wrappers' => [
          'container' => [
            '#attributes' => ['class' => 'role-title__action'],
          ],
        ],
        '#prefix' => $title,
        '#type' => 'link',
        '#title' => $this->t('Place block <span class="visually-hidden">in the %region region</span>', ['%region' => $title]),
        '#wrapper_attributes' => [
          // 'colspan' => 5,
        ],
        '#attributes' => [
          'class' => ['use-ajax', 'button', 'button--small'],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => Json::encode([
            'width' => 880,
          ]),
        ],
      ];
      $form['role_weight'][$role]['weight'] = [
        '#type' => 'weight',
        '#default_value' => $info['weight'] ?? 0,
        '#delta' => $weight_delta,
        '#title' => $this->t('Weight for @block block', ['@block' => $title]),
        '#title_display' => 'invisible',
        '#attributes' => [
          'class' => ['draggable-weight', 'field-weight', 'field-weight-' . $role],
        ],
      ];

      $form['role_weight'][$role]['action'] = [
        '#type' => 'select',
        '#options' => [
          '_none' => $this->t('Do nothing'),
          'auto' => $this->t('Promote automatically'),
          'leader' => $this->t('Promote with leadership approval'),
        ],
        '#default_value' => $info['action'] ?? '_none',
        '#title' => $this->t('Action for @field field', ['@field' => $title]),
        '#title_display' => 'invisible',
        '#parents' => ['role_weight', $role, 'action'],
      ];

      $form['role_weight'][$role]['promote'] = [
        '#type' => 'select',
        '#options' => [
          'self' => $this->t('Promote to this role'),
          'next' => $this->t('Promote next role'),
        ],
        '#default_value' => $info['promote'] ?? '_none',
        '#title' => $this->t('Promote for @field field', ['@field' => $title]),
        '#title_display' => 'invisible',
        '#parents' => ['role_weight', $role, 'promote'],
        '#states' => [
          'invisible' => [
            ':input[name="role_weight[' . $role . '][action]"]' => ['value' => '_none'],
          ],
        ],
      ];
    }

    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
      '#submit' => ['::submitForm'],
    ];

    return $form;
  }

  /**
   * Get all roles.
   *
   * @return array
   *   The roles.
   */
  private function getRoles() {
    $roles = [];
    foreach ($this->roleStorage->loadMultiple() as $role) {
      $roles[$role->id()] = $role->label();
    }
    unset($roles['anonymous']);
    unset($roles['authenticated']);
    unset($roles['administrator']);
    unset($roles['knowledge_coach']);
    unset($roles['knowledge_leader']);

    return $roles;
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $roles = [];
    $role_weight = $form_state->getValue('role_weight');
    foreach ($form_state->getValue('roles') as $role) {
      $weight = isset($role_weight[$role]['weight']) ? (int) $role_weight[$role]['weight'] : 0;
      $action = $role_weight[$role]['action'] ?? '_none';
      $promote = $role_weight[$role]['promote'] ?? '_none';
      if ($action === '_none') {
        $promote = '_none';
      }
      $roles[] = [
        'role' => $role,
        'weight' => $weight,
        'action' => $action,
        'promote' => $promote,
      ];
    }

    $this->settings
      ->set('roles', $roles)
      ->save();
  }

}

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

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