knowledge-8.x-1.x-dev/src/Form/CompetencySettingsForm.php
src/Form/CompetencySettingsForm.php
<?php
namespace Drupal\knowledge\Form;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Html;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\knowledge\KnowledgeCompetencyServiceInterface;
use Drupal\knowledge_field\Helper\CompetencyField;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Settings for the KnowledgeCompetency entity.
*
* @ingroup knowledge
*/
class CompetencySettingsForm 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 $competencyService;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The entity display repository.
*
* @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
*/
protected $entityDisplayRepository;
/**
* The Competency settings form.
*
* @param \Drupal\Core\Config\ImmutableConfig $settings
* The settings.
* @param \Drupal\Core\Entity\EntityStorageInterface $role_storage
* The role storage.
* @param \Drupal\knowledge\KnowledgeCompetencyServiceInterface $competency_service
* The competency service.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
* The entity display repository.
*/
public function __construct(
ImmutableConfig $settings,
EntityStorageInterface $role_storage,
KnowledgeCompetencyServiceInterface $competency_service,
EntityFieldManagerInterface $entity_field_manager,
EntityDisplayRepositoryInterface $entity_display_repository,
) {
$this->settings = $settings;
$this->roleStorage = $role_storage;
$this->competencyService = $competency_service;
$this->entityFieldManager = $entity_field_manager;
$this->entityDisplayRepository = $entity_display_repository;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory')->get('knowledge.competency.settings'),
$container->get('entity_type.manager')->getStorage('user_role'),
$container->get('knowledge.competency'),
$container->get('entity_field.manager'),
$container->get('entity_display.repository'),
);
}
/**
* Returns a unique string identifying the form.
*
* @return string
* The unique string identifying the form.
*/
public function getFormId() {
return 'knowledge_competency_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) {
$competency_roles = $this->competencyService->getRoleIds();
$role_options = [];
$role_options['_none'] = $this->t('No role');
foreach ($this->roleStorage->loadMultiple($competency_roles) as $role) {
$role_options[$role->id()] = $role->label();
}
$fields = [];
$items = $this->getFields();
$weight_delta = round(count($items) / 2);
$placement = FALSE;
foreach ($items as $field_id => $field) {
$fields[$field['role']][$field_id] = [
'label' => $field['label'],
'entity_id' => $field_id,
'weight' => $field['weight'],
'entity' => $field,
'status' => 1,
];
}
$form['fields'] = [
'#type' => 'table',
'#title' => $this->t('Fields'),
'#header' => [
$this->t('Field'),
$this->t('Role'),
$this->t('Weight'),
],
'#tabledrag' => [[
'action' => 'order',
'relationship' => 'sibling',
'group' => 'draggable-weight',
],
],
'#empty' => $this->t('No items.'),
'#tableselect' => FALSE,
];
$weight = 0;
$competency_roles[] = '_none';
foreach ($competency_roles as $role) {
$title = $role_options[$role];
$form['fields']['#tabledrag'][] = [
'action' => 'match',
'relationship' => 'sibling',
'group' => 'field-role-select',
'subgroup' => 'field-role-' . $role,
'hidden' => FALSE,
];
$form['fields']['#tabledrag'][] = [
'action' => 'order',
'relationship' => 'sibling',
'group' => 'field-weight',
'subgroup' => 'field-weight-' . $role,
];
$form['fields']['role-' . $role] = [
'#attributes' => [
'class' => ['role-title', 'role-title-' . $role],
'no_striping' => TRUE,
],
];
$form['fields']['role-' . $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['fields']['role-' . $role . '-message'] = [
'#attributes' => [
'class' => [
'role-message',
'role-' . $role . '-message',
empty($fields[$role]) ? 'role-empty' : 'role-populated',
],
],
];
$form['fields']['role-' . $role . '-message']['message'] = [
'#markup' => '<em>' . $this->t('No competencies in this role') . '</em>',
'#wrapper_attributes' => [
'colspan' => 5,
],
];
if (isset($fields[$role])) {
foreach ($fields[$role] as $info) {
$field_id = $info['entity_id'];
$form['fields'][$field_id] = [
'#attributes' => [
'class' => ['draggable'],
],
];
$form['fields'][$field_id]['#attributes']['class'][] = $info['status'] ? 'fields-enabled' : 'fields-disabled';
if ($placement && $placement == Html::getClass($field_id)) {
$form['fields'][$field_id]['#attributes']['class'][] = 'color-success';
$form['fields'][$field_id]['#attributes']['class'][] = 'js-fields-placed';
}
$form['fields'][$field_id]['info'] = [
'#wrapper_attributes' => [
'class' => ['field'],
],
];
// Ensure that the label is always rendered as plain text. Render
// array #plain_text key is essentially treated same as @ placeholder
// in translatable markup.
if ($info['status']) {
$form['fields'][$field_id]['info']['#plain_text'] = $info['label'];
}
else {
$form['fields'][$field_id]['info']['#markup'] = $this->t('@label (disabled)', ['@label' => $info['label']]);
}
$form['fields'][$field_id]['role-theme']['role'] = [
'#type' => 'select',
'#default_value' => $role,
'#required' => TRUE,
'#title' => $this->t('Role for @field field', ['@field' => $info['label']]),
'#title_display' => 'invisible',
'#options' => $role_options,
'#attributes' => [
'class' => ['field-role-select', 'field-role-' . $role],
],
'#parents' => ['fields', $field_id, 'role'],
];
$form['fields'][$field_id]['weight'] = [
'#type' => 'weight',
'#default_value' => $info['weight'],
'#delta' => $weight_delta,
'#title' => $this->t('Weight for @block block', ['@block' => $info['label']]),
'#title_display' => 'invisible',
'#attributes' => [
'class' => ['draggable-weight', 'field-weight', 'field-weight-' . $role],
],
];
}
}
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#button_type' => 'primary',
'#submit' => ['::submitForm'],
];
$form['#attached']['library'][] = 'core/drupal.tableheader';
$form['#attached']['library'][] = 'knowledge/competency.admin';
return $form;
}
/**
* 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) {
// Empty implementation of the abstract submit class.
$fields = $form_state->getValue('fields');
$fields_definitions = $this->entityFieldManager->getFieldDefinitions('knowledge_competency', 'knowledge_competency');
foreach ($fields as $field_id => $field) {
$role = $field['role'];
$fields_definitions[$field_id]->setThirdPartySetting('knowledge', 'competency_role', $role);
$fields_definitions[$field_id]->save();
}
}
/**
* Get all fields.
*/
protected function getFields() {
$form = $this->entityDisplayRepository->getFormDisplay('knowledge_competency', 'knowledge_competency', 'default');
$fields_definitions = $form->get('fieldDefinitions');
$content = $form->get('content');
$fields = [];
$role_fields = CompetencyField::roleFields($fields_definitions);
foreach ($role_fields as $role => $field_names) {
foreach ($field_names as $field_name) {
if (!array_key_exists($field_name, $content)) {
continue;
}
$fields[$field_name] = [
'label' => $fields_definitions[$field_name]->getLabel(),
'weight' => $content[$field_name]['weight'],
'role' => $role,
];
}
}
return $fields;
}
}
