View source
<?php
namespace Drupal\promote_disable\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\NodeType;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PromoteDisableForm extends ConfigFormBase {
protected $config;
protected $contentType;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->config = $config_factory
->getEditable('promote_disable.settings');
}
public static function create(ContainerInterface $container) {
return new static($container
->get('config.factory'));
}
public function getFormId() {
return 'promote_disable_form';
}
protected function getEditableConfigNames() {
return [
'promote_disable.settings',
];
}
public function buildForm(array $form, FormStateInterface $form_state) {
$node_types = $this
->promoteDisableNodeTypes();
$form['promote_to_front_page'] = [
'#type' => 'details',
'#title' => $this
->t('Promote to front page'),
'#open' => TRUE,
];
$form['promote_to_front_page']['promote_disable_node_types'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#size' => count($node_types),
'#title' => $this
->t('Content types'),
'#default_value' => $this->config
->get('promote_disable_node_types'),
'#options' => $node_types,
'#description' => $this
->t('Select the content types on which you would like to disable the "Promoted to front page" option.'),
];
$form['sticky'] = [
'#type' => 'details',
'#title' => $this
->t('Make content sticky'),
'#open' => TRUE,
];
$form['sticky']['promote_disable_sticky_node_types'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#size' => count($node_types),
'#title' => $this
->t('Content types'),
'#default_value' => $this->config
->get('promote_disable_sticky_node_types'),
'#options' => $node_types,
'#description' => $this
->t('Select the content types on which you would like to disable the "Sticky option.'),
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config
->set('promote_disable_node_types', $form_state
->getValue('promote_disable_node_types'));
$this->config
->set('promote_disable_sticky_node_types', $form_state
->getValue('promote_disable_sticky_node_types'));
$this->config
->save();
}
public function promoteDisableNodeTypes() {
$node_types = NodeType::loadMultiple();
$options = [];
foreach ($node_types as $node_type) {
$options[$node_type
->id()] = $node_type
->label();
}
asort($options);
return $options;
}
}