64. 表单定义示例

龷龶 form 龩龨龤龠龞龝龙龘龗龓龏龌龈龆龄龆龃龀龨龤齽齺齹齸龈齵齲齮齬齨齧齦齥齣齠 drupal8 齒齏齌齈齇龆龷龶龈齄龄龷龶 API 齥齣鼻鼸鼶齠鼵鼲鼱龘鼰鼮齲齮齒鼪鼨鼧

龷龶鼦龙鼤鼠

龙齏齌龗鼮龷龶龈龨龤鼝鼛龙齨齽鼙鼦鼮齹齸龈鼖鼔鼓鼒鼏齥 CSRF token 黸黵黳黰黮黫黨黧鼶齬齨黥黤黣黠龈龠龞黝黚龈鼛龙龘鼦鼮齹齸齥鼲鼠

龷龶黖黒 id 鼠龆龄黋龗黇黖龷龶黮鼖鼔黄龓黀麿麻 id 麸麵龘麲麰麮麪龷龶麨麤黮麠麞黧

龷龶龘麚黠鼠麘齦龷龶麕麔麑麍麋麇鼤黧

龷龶齥齣黳黰鼠黳黰龆龃麅麃龘鹿鹾龩鹽鹼鹻

齽齺齥齣鹸鹷鼠龆龃鹳黵齽齺龷龶鹱龈麘齦龨龤齥齣鹯鹸鹷齽齺鹭

鹩鹦龨龤齬龷龶鹢鹡齏齌鹝鹜鼲鼵鹘鼠

\Drupal\Core\Form\FormInterface

齠麻鼵鹘齒鹎麑鼦鼮鹌鹻龈鹉黒鹈鹄鹝鹜鹂鼦鸿齹齸龈龨龤鹎鼛龙鸼龆鼔鸻鸸鸵鹜鸱鸯龷龶鼻龆鹝

鸫鹜鸧鸥鸻龙齏齌鼻龆龗鼮龷龶鸤鼝鼛龙鸣鸠龗鼮鸝鸜鹜鹂鼵鹘龘龷龶鸛鸚鸵鼧

鸥鸻鸵鹜鼶龷龶鹉齬龶鸗龷龶 single-step 齈鸏鸗龷龶 multi-step 龈龶鸗龷龶龩鸋龞齇龆龘鼒鸉龈麘龆龃齽齺龗鸅鸚黣黠鸫麑齹齸龘齽齺齈鹸鹷龈鸄鸏鸗龷龶鼛龙鸏鸅鸱鸯齽齺鸀龌鷿鷻齈鹸鹷黣黠鸫麑齹齸齈鼓鷷龈鸵鹜齠鹂龗鸗鼲龗鸗鷳鷯鷫鷩龈鷧鷤龘鷢麰龩鷞鷚龨龤鸤鸱鸯龘鸏鸅齽齺龈齵齲齮鼶龀齨齧齦鷘鷗鸿龷龶鼧

龶鸗龷龶 single-step 鷖龆鸝鷔鼠

鸥鸻鼱齏齌龗鼮龶鸗龷龶龈鷒鷑黄龓鷎齬鷍 yunke 鷉龈鷅鹱齏齌龗鼮龷龶鸛龈鷂鶾齬鼠

\yunke\src\Form\YunkeForm.php

鶴鶳齬鼠

<?php

/**
 * @file
 * 示例,建立一个表单
 */
namespace Drupal\yunke\Form;

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

class YunkeForm extends FormBase
{

    public function getFormId()
    {
        return 'yunke_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $form['phone_number'] = array(
            '#type' => 'tel',
            '#title' => $this->t('Your phone number'),
            );
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save'),
            '#button_type' => 'primary',
            );
        return $form;
    }

    public function validateForm(array & $form, FormStateInterface $form_state)
    {
        if (strlen($form_state->getValue('phone_number')) < 5) {
            $form_state->setErrorByName('phone_number', $this->t('The phone number is too short. Please enter a full phone number.@time',["@time"=>time()]));
        }
    }

    public function submitForm(array & $form, FormStateInterface $form_state)
    {
        drupal_set_message($this->t('Your phone number is @number', array('@number' => $form_state->
                getValue('phone_number'))));
    }

}

鷅鹱齏齌龗鼮鵞鵚麘龀龗鼮鵖鵓鵐龈鵖鵓鵐齒鵌鸯鹜鼲鵊鵇鼠

return  \Drupal::formBuilder()->getForm("\Drupal\yunke\Form\YunkeForm");

鵁鴽鵌鸯鹜鼲鵊鵇鼠

        $form_object=new \Drupal\yunke\Form\YunkeForm();
        $form_state=new \Drupal\Core\Form\FormState();
        return \Drupal::formBuilder()->buildForm($form_object, $form_state);

鴴鴳鵞鵚鴰鴯鷘鼮鵖鵓鵐龈鸸鸵鹜鴭鴬龷龶鹝龈鴪鹢龷龶鴦鸵鹜麑鴥鴢龘鵞鵚齏齌鹌鹻龈齥鼲鼠

yunke.routing.yml 齒鴞鴜龗鼮龷龶鴥龆鵞鵚鼠

yunke.form:
  path: '/yunke-form'
  defaults:
    _title: 'yunke form'
    _form: '\Drupal\yunke\Form\YunkeForm'
  requirements:
    _permission: 'access content'

鷅鹱鴰鴯鼠 http://www.yourdomain.com/yunke-form 鸸鸵鹜鹝龈鴗鴕齈鹜鹂鴰鴯鵖鵓鵐龘鹌鴓龩黣鴐鴎鴋龘

鸏鸗龷龶 multi-step 鷖龆鸝鷔鼠

齠鸏鸗龷龶齒龈鴈龗鸗鴅鼛龙龗鼮龷龶鸛龈鴃鸻鴁鹼鳽鼱鳹龗麋鼓鼒龈鴋鳷龈鷒鷑黄龓鷎齬鷍 yunke , 鸥鸻鳶齏齌龗鼮鳳鸛鹜齽鼙鴈鼮龷龶鸛龘鳱龆龏龌龈鷂鶾齥鼲鼠

\yunke\src\Form\Multistep\MultistepFormBase.php

鶴鶳齥鼲鼠

<?php

/**
 * @file
 * Contains \Drupal\yunke\Form\Multistep\MultistepFormBase.
 */

namespace Drupal\yunke\Form\Multistep;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManagerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

abstract class MultistepFormBase extends FormBase
{

    /**
     * @var \Drupal\user\PrivateTempStoreFactory
     */
    protected $tempStoreFactory;

    /**
     * @var \Drupal\Core\Session\SessionManagerInterface
     */
    private $sessionManager;

    /**
     * @var \Drupal\Core\Session\AccountInterface
     */
    private $currentUser;

    /**
     * @var \Drupal\user\PrivateTempStore
     */
    protected $store;

    /**
     * Constructs a \Drupal\yunke\Form\Multistep\MultistepFormBase.
     *
     * @param \Drupal\user\PrivateTempStoreFactory         $temp_store_factory
     * @param \Drupal\Core\Session\SessionManagerInterface $session_manager
     * @param \Drupal\Core\Session\AccountInterface        $current_user
     */
    public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user)
    {
        $this->tempStoreFactory = $temp_store_factory;
        $this->sessionManager = $session_manager;
        $this->currentUser = $current_user;

        $this->store = $this->tempStoreFactory->get('multistep_data');
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container)
    {
        return new static(
            $container->get('user.private_tempstore'),
            $container->get('session_manager'),
            $container->get('current_user')
        );
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        // Start a manual session for anonymous users.
        if ($this->currentUser->isAnonymous() && !isset($_SESSION['multistep_form_holds_session'])) {
            $_SESSION['multistep_form_holds_session'] = true;
            $this->sessionManager->start();
        }

        $form = array();
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type'        => 'submit',
            '#value'       => $this->t('Submit'),
            '#button_type' => 'primary',
            '#weight'      => 10,
        );

        return $form;
    }

    /**
     * Saves the data from the multistep form.
     */
    protected function saveData()
    {
        // Logic for saving data.
        //$this->deleteStore();
        drupal_set_message($this->t('The form has been saved.'));
    }

    /**
     * Helper method that removes all the keys from the store collection used for
     * the multistep form.
     */
    protected function deleteStore()
    {
        $keys = ['name', 'email', 'age', 'location'];
        foreach ($keys as $key) {
            $this->store->delete($key);
        }
    }
}

鷅鹱齏齌鳝龗鼮鸗鳜鼛龙龘龷龶鹢鹡龈鷂鶾齥鼲鼠

\yunke\src\Form\Multistep\MultistepOneForm.php

鶴鶳齥鼲鼠

<?php

/**
 * @file
 * Contains \Drupal\yunke\Form\Multistep\MultistepOneForm.
 */

namespace Drupal\yunke\Form\Multistep;

use Drupal\Core\Form\FormStateInterface;

class MultistepOneForm extends MultistepFormBase
{

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

    /**
     * {@inheritdoc}.
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {

        $form = parent::buildForm($form, $form_state);

        $form['name'] = array(
            '#type'          => 'textfield',
            '#title'         => $this->t('Your name'),
            '#default_value' => $this->store->get('name') ? $this->store->get('name') : '',
        );

        $form['email'] = array(
            '#type'          => 'email',
            '#title'         => $this->t('Your email address'),
            '#default_value' => $this->store->get('email') ? $this->store->get('email') : '',
        );

        $form['actions']['submit']['#value'] = $this->t('Next');

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $this->store->set('email', $form_state->getValue('email'));
        $this->store->set('name', $form_state->getValue('name'));
        $form_state->setRedirect('yunke.multistep_two');
    }

}

鳚齏齌鳝鳙鼮鸗鳜龘龷龶鹢鹡龈鷂鶾齥鼲鼠

\yunke\src\Form\Multistep\MultistepTwoForm.php

鶴鶳齥鼲鼠

<?php

/**
 * @file
 * Contains \Drupal\yunke\Form\Multistep\MultistepTwoForm.
 */

namespace Drupal\yunke\Form\Multistep;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

class MultistepTwoForm extends MultistepFormBase
{

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

    /**
     * {@inheritdoc}.
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {

        $form = parent::buildForm($form, $form_state);

        $form['age'] = array(
            '#type'          => 'textfield',
            '#title'         => $this->t('Your age'),
            '#default_value' => $this->store->get('age') ? $this->store->get('age') : '',
        );

        $form['location'] = array(
            '#type'          => 'textfield',
            '#title'         => $this->t('Your location'),
            '#default_value' => $this->store->get('location') ? $this->store->get('location') : '',
        );

        $form['actions']['previous'] = array(
            '#type'       => 'link',
            '#title'      => $this->t('Previous'),
            '#attributes' => array(
                'class' => array('button'),
            ),
            '#weight'     => 0,
            '#url'        => Url::fromRoute('yunke.multistep_one'),
        );

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $this->store->set('age', $form_state->getValue('age'));
        $this->store->set('location', $form_state->getValue('location'));

        // Save the data
        parent::saveData();
        $form_state->setRedirect('yunke.multistep_one');
    }
}

鳘鹝龈鸜齠鼛龙龆鴬龘龷龶鹢鹡鴅麑鹝龈鳚鼱齏齌鵞鵚龈齠 yunke.routing.yml 齒鴜麃鹜鼲鶴鶳鼠

yunke.multistep_one:
  path: '/yunke/multistep-one'
  defaults:
    _form: '\Drupal\yunke\Form\Multistep\MultistepOneForm'
    _title: 'First form'
  requirements:
    _permission: 'access content'
yunke.multistep_two:
  path: '/yunke/multistep-two'
  defaults:
    _form: '\Drupal\yunke\Form\Multistep\MultistepTwoForm'
    _title: 'Second form'
  requirements:
_permission: 'access content'

龗鳗鸸鳔龈龝鳑鷞鷚鷍 yunke 鷉黄龓龈鴰鴯鼠

http://www.yourdomain.com/yunke/multistep-one 鸸鸵鹜鹝

齨鼶鴭鴬龷龶鳎鸜鹝龈齨鸵鹜齽齺鹿鹾龈齠鹂龗鸗齈鼲龗鸗鷯鷫鷩黧黧

齵齲齮鸸鳊鴬鷘麕龈齬齨齧鸜龗鼮齦鷔龈齬鹱鳈龘龷龶 api 鳹鳇鳆龈鳂鼠齵齲齮鸫龆齦鷔鼱黥鲿鲼龈鲺鲸鲷鲶鲳鲯鹷鹱齬齨鳎鸜鼧

鷘龩 2017 鲣龘鸋鹱龗鲟齲齮龈鲜鲚鲗鳑鲣鲔鲐

本书共71小节:

评论 (写第一个评论)