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小节:

评论 (写第一个评论)