Last active
April 1, 2019 14:25
-
-
Save mattschaff/10f5f7717248cf32a14229bd5fac14c4 to your computer and use it in GitHub Desktop.
Drupal 8: Admin Form Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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