I created a simple test module that adds a text banner to all nodes if a checkbox is checked in the form of the modules configuration. Currently it is working halfway as I want.
When the checkbox is checked and the configuration is exported the text banner displays on all nodes.
So far this is correct. But I don't want to have to export the configuration for the text banner to display. I want it to display immediately after checking the checkbox.
An example is in Devel. If you go to the admin area of Devel and check the box 'Display $page array' The page array displays on every node afterwards without having to export the configuration
To display a text banner on all nodes I am using hook_node_view. Then getting the checkbox value from my custom module settings.yml file.
function my_form_configy_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
$config = \Drupal::config('my_form_configy.settings')->get('checkbox');
if ($config === TRUE) {
$build['layout_test'] = [
'#markup' => '<h2> Extra, Extra read all about it.</h2>',
];
}
}
This is my form
namespace Drupal\my_form_configy\Form;
use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\ConfigFormBase;
class MyForm extends ConfigFormBase {
public function getFormId() {
return 'my_form_configy_1346';
}
const SETTINGS = 'my_form_configy.settings';
protected function getEditableConfigNames() {
return [
static::SETTINGS,
];
}
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config(static::SETTINGS);
$check = \Drupal::config('my_form_configy.settings')->get('checkbox');
$form['checkbox'] = [
'#type' => 'checkbox',
'#title' => $this->t('Do you want to add the text banner to all nodes? Checking this box will add a large h2 text banner to add nodes. You must export the config and reload a node page'),
'#default_value' => $check,
'#weight' => '0',
];
$form['#theme'] = 'my_form';
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->configFactory->getEditable(static::SETTINGS)
->set('checkbox', $form_state->getValue('checkbox'))
->save();
parent::submitForm($form, $form_state);
}
}
Devel is using the same method I am, but if you check the box 'Display $page array' the dpm feature works on nodes immediately without having to export the configuration.
function devel_page_attachments_alter(&$page) {
if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('page_alter')) {
dpm($page, 'page');
}
}
I have searched for ConfigFormBase in core and contrib modules and read this. https://www.drupal.org/docs/drupal-apis/configuration-api/working-with-configuration-forms and https://www.drupal.org/docs/8/api/form-api/configformbase-with-simple-configuration-api