knowledge-8.x-1.x-dev/src/Form/GovernanceForm.php
src/Form/GovernanceForm.php
<?php
declare(strict_types=1);
namespace Drupal\knowledge\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Configure Knowledge settings for this site.
*/
final class GovernanceForm extends ConfigFormBase {
/**
* The user role storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $roleStorage;
/**
* The Governance settings.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) {
$this->setConfigFactory($config_factory);
$this->roleStorage = $entity_type_manager->getStorage('user_role');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('entity_type.manager'),
);
}
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'knowledge_governance';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames(): array {
return ['knowledge.governance.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$settings = $this->config('knowledge.governance.settings');
$roles = $this->roleStorage->loadMultiple();
$options = [];
$skip_roles = ['anonymous', 'authenticated'];
foreach ($roles as $machine_name => $role) {
if (in_array($machine_name, $skip_roles)) {
continue;
}
$options[$machine_name] = $role->label();
}
$form['roles'] = [
'#type' => 'checkboxes',
'#title' => $this->t('When the user has one of these roles'),
'#default_value' => $settings->get('roles') ?? [],
'#options' => $options,
'#multiple' => TRUE,
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->config('knowledge.governance.settings')
->set('roles', $form_state->getValue('roles'))
->save();
parent::submitForm($form, $form_state);
}
}
