Skip to content

Instantly share code, notes, and snippets.

@mattschaff
Last active April 1, 2019 14:25
Show Gist options
  • Save mattschaff/10f5f7717248cf32a14229bd5fac14c4 to your computer and use it in GitHub Desktop.
Save mattschaff/10f5f7717248cf32a14229bd5fac14c4 to your computer and use it in GitHub Desktop.
Drupal 8: Admin Form Example
<?php
namespace Drupal\my_module\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Builds the example admin form
*/
class AdminFormExample extends ConfigFormBase {
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'my_module.admin_form_example',
];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'admin_form_example';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$options = [
1 => 'Option 1',
2 => 'Option 2',
];
// Add options to select form element
$config = $this->config('my_module.admin_form_example');
$item_selected = $config->get('items');
$form['items'] = [
'#type' => 'select',
'#title' => $this->t('Title'),
'#options' => $options,
'#default_value' => empty($item_selected) ? false : $item_selected,
];
// Set node to feature in a view
$config = $this->config('my_module.featured_node');
$featured_node = $config->get('featured_node');
$form['featured_node'] = array(
'#type' => 'entity_autocomplete',
'#title' => $this->t('Set Featured Node'),
'#target_type' => 'node',
'#selection_settings' => ['target_bundles' => ['my_content_type']],
'#default_value' => empty($featured_node) ? false : Node::load($featured_node),
);
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Final submit
parent::submitForm($form, $form_state);
// get submitted values
$values = $form_state->getValues();
// add to config
$this->config('my_module.admin_form_example')
->set('items', $values['items'])
->set('featured_node', $values['featured_node'])
->save();
}
}
my_module.admin_form_example:
path: '/admin/config/admin-form-example'
defaults:
_form: '\Drupal\my_module\Form\AdminFormExample'
_title: 'Admin Form Example'
requirements:
_permission: 'administer content'
options:
_admin_route: TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment