Konfiguraciona forma Drupala
Deo IV praktičnog vodiča za kreiranje osnovnih Drupal 8 modula
Od .info do testova, samo osnove
Za sada je sve prilično uredno, ali kako možemo promeniti ono što vidimo? Sa nekim formama, naravno.
Jednostavne scenarije korišćenja pogledajte u odeljku „Podešavanja sajta i etikete“.
/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'; }
Počinjemo naš konfiguracioni fajl proširujući ConfigFormBase. Klasa LoremIpsumForm je klasa navedena u fajlu routing.yml.
Sledeći metod zapravo gradi konfiguracionu formu:
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { // Konstruktor forme. $form = parent::buildForm($form, $form_state); // Podrazumevana podešavanja. $config = $this->config('loremipsum.settings');
Promenljiva $config je mesto gde čuvamo naše trenutne postavke.
Zatim definišemo naša polja forme i vraćamo formu:
// Polje za naslov stranice. $form['page_title'] = array( '#type' => 'textfield', '#title' => $this->t('Naslov stranice generatora Lorem ipsum:'), '#default_value' => $config->get('loremipsum.page_title'), '#description' => $this->t('Dajte naslov svojoj Lorem ipsum generator stranici.'), ); // Polje za izvorni tekst. $form['source_text'] = array( '#type' => 'textarea', '#title' => $this->t('Izvorni tekst za generisanje Lorem ipsum-a:'), '#default_value' => $config->get('loremipsum.source_text'), '#description' => $this->t('Napišite jednu rečenicu po liniji. Te rečenice će se koristiti za generisanje nasumičnog teksta.'), ); return $form; }
Takođe treba da definišemo metode validateForm(), submitForm() i getEditableConfigNames(), čak i ako ih ne koristimo:
/** * {@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.