Admin configuration form with dependency injection
When adding a form using Form API, best practice is to use dependency injection when possible. Admin form classes typically 'extend ConfigFormBase'. If you want to add to it, it'll look like this.
<?php
namespace Drupal\my_module\Form;
use Drupal\Core\Config\Config;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class myCustomAdminForm.
*
* @package Drupal\my_module\Form
*/
class myCustomAdminForm extends ConfigFormBase {
/**
* @var $configFactory
*/
protected $configFactory;
/**
* @var Config $myConfig
*/
protected $myConfig;
/**
* The Messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
public function __construct(
ConfigFactoryInterface $configFactory,
MessengerInterface $messenger
) {
parent::__construct($configFactory);
$this->myConfig = $this->config('my_config.settings.my_settings');
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('messenger')
);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'my_config.settings.my_settings',
];
}
/**
* This needs to return a string that is the unique ID of your form. Namespace the form ID based on your module's name.
*/
public function getFormId() {
return 'my_module_admin_form';
}
/**
* This returns a Form API array that defines each of the elements your form is composed of.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['text_input'] = [
'#type' => 'textfield',
'#description' => t('Enter data into this field'),
'#default_value' => $this->myConfig->get('my_config_values')
]
return parent::buildForm($form, $form_state);
}
/**
* Validate the form
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
if(empty($values['text_input']) {
$form_state->setErrorByName('text_input', t('You must enter data into this field.'));
}
}
/**
* Submit the form
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$this->myConfig->set('my_config_values', $values['text_input']);
$this->myConfig->save();
$this->messenger->addStatus('Your value has been saved.');
parent::submitForm($form, $form_state);
}
}