Drupal-Konfigurationsformular
Teil IV des Praxisleitfadens zur Erstellung grundlegender Drupal 8-Module
Von .info bis Tests, nur die Grundlagen
Bis jetzt ist alles ziemlich ordentlich, aber wie können wir ändern, was wir sehen? Mit einigen Formularen natürlich.
Einfache Anwendungsfälle finden Sie im Abschnitt „Website-Einstellungen und Labels“.
/src/Form/LoremIpsumForm.php
<?php namespace Drupal\loremipsum\Form; use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; class LoremIpsumForm extends ConfigFormBase { /** * {@inheritdoc} */ public function getFormId() { return 'loremipsum_form'; }
Wir beginnen unsere Einstellungsdatei, die ConfigFormBase erweitert. Die Klasse LoremIpsumForm ist die Klasse, die in der routing.yml-Datei angegeben ist.
Als nächstes folgt die Methode, die tatsächlich das Einstellungsformular erstellt:
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { // Formular-Konstruktor. $form = parent::buildForm($form, $form_state); // Standard-Einstellungen. $config = $this->config('loremipsum.settings');
Die Variable $config ist der Ort, an dem wir unsere aktuellen Einstellungen speichern.
Dann definieren wir unsere Formularfelder und geben das Formular zurück:
// Feld für Seitentitel. $form['page_title'] = array( '#type' => 'textfield', '#title' => $this->t('Lorem Ipsum Generator Seitentitel:'), '#default_value' => $config->get('loremipsum.page_title'), '#description' => $this->t('Geben Sie Ihrer Lorem Ipsum Generator Seite einen Titel.'), ); // Feld für Quelltext. $form['source_text'] = array( '#type' => 'textarea', '#title' => $this->t('Quelltext für Lorem Ipsum Generierung:'), '#default_value' => $config->get('loremipsum.source_text'), '#description' => $this->t('Schreiben Sie einen Satz pro Zeile. Diese Sätze werden zur Generierung des Zufallstextes verwendet.'), ); return $form; }
Wir müssen auch die Methoden validateForm(), submitForm() und getEditableConfigNames() deklarieren, auch wenn wir sie nicht benutzen:
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $config = $this->config('loremipsum.settings'); $config->set('loremipsum.source_text', $form_state->getValue('source_text')); $config->set('loremipsum.page_title', $form_state->getValue('page_title')); $config->save(); return parent::submitForm($form, $form_state); } /** * {@inheritdoc} */ protected function getEditableConfigNames() { return [ 'loremipsum.settings', ]; } }
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.