StaticPageSettingsForm.php in Static Page 8
File
src/Form/StaticPageSettingsForm.php
View source
<?php
namespace Drupal\static_page\Form;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\NodeType;
class StaticPageSettingsForm extends ConfigFormBase {
protected $entityFieldManager;
public function __construct(EntityFieldManagerInterface $entity_field_manager) {
$this->entityFieldManager = $entity_field_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_field.manager'));
}
public function getFormId() {
return 'static_page_config_form';
}
protected function getEditableConfigNames() {
return [
'static_page.fields',
];
}
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this
->config('static_page.fields');
$types = NodeType::loadMultiple();
$fields_config = $config
->get('fields');
$form['help'] = [
'#markup' => $this
->t('Select which field, if any, to use for static page content.'),
];
$form['fields'] = [
'#tree' => TRUE,
];
$valid_field_types = [
'string_long',
'text_long',
'text_with_summary',
];
foreach ($types as $key => $node_type) {
$field_options = [
'' => $this
->t('-- None --'),
];
$fields = $this->entityFieldManager
->getFieldDefinitions('node', $key);
foreach ($fields as $machine_name => $field) {
if ($field
->getName() != 'revision_log' && in_array($field
->getType(), $valid_field_types)) {
$field_options[$machine_name] = $field
->getLabel() . ' (' . $field
->getName() . ')';
}
}
$form['fields'][$key] = [
'#title' => $node_type
->label(),
'#type' => 'select',
'#options' => $field_options,
'#default_value' => !empty($fields_config[$key]) ? $fields_config[$key] : '',
];
}
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this
->config('static_page.fields')
->set('fields', array_filter($form_state
->getValue('fields')))
->save();
parent::submitForm($form, $form_state);
}
}