7.2 创建表单

1龵龱龯龮龭

龪龧龤龢龮龭龟龜龘龔龒龑

  • getFormId: 齶齴齲齮龟龔龒齬齩齦龮龭齣齢齞齚

  • buildForm: 齶齴齲齮龟齬齌齩齦齈龘齆齂齁鼽齬鼻鼹 hook_form齚

  • validateForm: 鼦鼤鼡龟齬鼝鼙鼖鼔齬鼻鼹 hook_form_validate齚

  • submitForm: 鼑鼙鼍鼊鼆鼂齬鼻鼹 hook_form_submit齚

鼀src\Form黸黶黵龱龯齈龘黳黱HelloWorldForm.php齬黥黣黠黵龑

<?php

/** 
 * @file 
 * Contains \Drupal\hello_world\Form\HelloWorldForm. 
 */ 

namespace Drupal\hello_world\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class HelloWorldForm extends FormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'example_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['email'] = [
      '#type' => 'email',
      '#title' => $this->t('Your .com email address.')
    ];
    $form['show'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) { 
    if (strpos($form_state->getValue('email'), '.com') === FALSE) {
      $form_state->setErrorByName('email', $this->t('This is not a .com email address.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Your email address is @email', ['@email' => $form_state->getValue('email')]));
  }
}

龮龭麉麆齈龘鼻龤齲齮齬麅麁鹾\Drupal\Core\Form\FormInterface鹻鹸齚鹶 \Drupal\Core\Form\FormBase鼦龮龭龟鹲鼻齚form鹮textarea,textfield鹪鼻鹨齚

2龵齲齮鹤鹣

鹤鹣鹡鹞鹜hello_world.routing.yml鹙齬黥黣黠黵龑

hello_world.form:  
  path: '/hello/form'
  defaults:
    _form: '\Drupal\hello_world\Form\HelloWorldForm'
    _title: 'Demo Form'
  requirements:
    _permission: 'access simple page'

鹕鹑龑鹐鹏鹋_controller鹇鹄鹾_form,龮鹁鸽麆齈龘form鼻齚

drush cr鸻鸹鸷鸳齬鸲鸮鸫鸩/hello/form鸨龢鸥鸡齚

3龵黠鸙鼀controller鹙鸽麆form鸖

鼤鸔鸒鸐formBuilder龔龒龤鸽麆齚

黥黣黠黵龑

$form = \Drupal::formBuilder()->getForm('Drupal\hello_world\Form\HelloWorldForm');

本书共79小节:

评论 (写第一个评论)