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

评论 (写第一个评论)