drupal8 表单_在Drupal中构建类似于多页向导的表单

drupal8 表单

Drupal gives you the APIs to build forms by merely specifying the details of the form. It will create the underlying HTML on its own provided you just specify the fields you want in it. We discussed the details of building a form in Drupal in a previous article.

Drupal仅通过指定表单的详细信息即可为您提供构建表单的API。 只要您在其中指定所需的字段,它将自行创建基础HTML。 在上一篇文章中,我们讨论了在Drupal中构建表单的细节。

Usally, we would just need a simple form with a few fields, but there may be cases where there might be too many fields on a single page and the form might look confusing and tedious to fill out. This might not make the best UI for your site and it would be good to break your form into logical sections so that it is easier for the user to fill in the information. One way to break the form into different logical blocks is using the field set, but this usually only works if you have a low number of sections. The other way to organize your form is to make it into a wizard or a multi-page form where the user fills the details on one page and then moves ahead to the next page. In this article we will take a look at how to create a multi-page form in Drupal.

通常,我们只需要一个带有几个字段的简单表单,但是在某些情况下,单个页面上可能有太多字段,并且填写该表单可能会造成混乱和繁琐。 这可能不是您网站的最佳UI,最好将表单分成逻辑部分,以便用户更轻松地填写信息。 将字段分为不同的逻辑块的一种方法是使用字段集,但这通常仅在部分数量较少的情况下有效。 组织表单的另一种方法是将其设置为向导或多页表单,其中用户在一页上填写详细信息,然后前进到下一页。 在本文中,我们将研究如何在Drupal中创建多页表单。

创建多页表单模块 (Creating the multipage form module)

The first thing we will have to do is create a module in Drupal. To do this, create a folder sites\all\modules\multipageform in your Drupal installation and add the following files to it

我们要做的第一件事是在Drupal中创建一个模块。 为此,请在Drupal安装中创建一个sites\all\modules\multipageform文件夹,并将以下文件添加到其中

multipageform.info

multipageform.info

name = multipageform
description = This module creates a multipage form form using Drupal.
core = 7.x

multipageform.module

multipageform.module

<?php
/**
 * @file
 * This is the main module file.
 */

 /**
 * Implements hook_help().
 */
function multipageform_help($path, $arg) {

  if ($path == 'admin/help#multipageform') {
    $output = '<h3>' . t('About') . '</h3>';
    $output .= '<p>' . t('The multipageform module shows how to create a multiple page form using Drupal.') . '</p>';
    return $output;
  }
}

Once you have done this you should be able to see the new module in the module list.You can now enable the module.

完成此操作后,您应该能够在模块列表中看到新模块。您现在可以启用该模块。

alt

定义表单中的页数和表单内容。 (Defining the number of pages in the form and the form contents.)

Once we have our module ready, let’s start defining the Multipage form. To do that, the first thing we will do is create a menu item which will display our form. We will have to add the hook menu in our module as follows

准备好模块后,让我们开始定义“多页”表单。 为此,我们要做的第一件事是创建一个菜单项,该菜单项将显示我们的表单。 我们将必须在模块中添加挂钩菜单,如下所示

/**
* Implementation of hook_menu().
*/
function multipageform_menu() {
  $items['multipageform/form1'] = array(
        'type' => MENU_CALLBACK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('multipageform_form1'));

  return $items;
}

In the above code we have created a menu item at multipageform/form1 and the page callback is the drupal_get_form function with the argument being our multipageform_form1 function which will return the form for Drupal to render it.

在上面的代码,我们在创建一个菜单项multipageform/form1和页面回调是drupal_get_form的说法是,我们的函数multipageform_form1函数将返回的形式为Drupal来呈现它。

Now we will define the function multipageform_form1 as follows

现在,我们将如下定义函数multipageform_form1

function multipageform_form1($form, &$form_state) {


    if(isset($form_state['values'])) {
        $currstep = $form_state['step'] + 1;
    }else {
        $currstep = 0;
    }
    $form_state['step'] = $currstep;
    $allsteps = getForm();
    $currform =  $allsteps[$currstep];

    return $currform;
}

function getForm() {

    $form = array();
    $step1 = array();
    $step1['name']=array(
        '#type'=>'textfield',
        '#title'=>t('Enter your name'),
        '#description'=>t('Your first name goes here')
      );
    $step1['last_name']=array(
        '#type'=>'textfield',
        '#title'=>t('Enter your Last name'),
        '#description'=>t('Your Last name goes here')
      );


    $step1['submit']=array(
        '#type'=>'submit',
        '#value'=>t('Next')
      );

    $form[] = $step1;

    $step2['email']=array(
        '#type'=>'textfield',
        '#title'=>t('Enter your email'),
        '#description'=>t('Your email goes here')
      );

    $step2['country']=array(
        '#type'=>'select',
        '#title'=>t('Select your country'),
        '#options'=>array('USA','UK','France','Japan')
      );


    $step2['submit']=array(
        '#type'=>'submit',
        '#value'=>t('Next')
      );

    $form[] = $step2;

    $step3['birthdate']=array(
            '#type'=>'date',
            '#title'=>t('Birthdate'),
          );

    $step3['submit']=array(
        '#type'=>'submit',
        '#value'=>t('Submit')
      );

    $form[] = $step3;

    return $form;
}

In this function the variable $form_state will contain the state of our multipage form. In the state we will store the current step or page we are on, and also the values which have been entered by the user in the previous steps.

在此函数中,变量$form_state将包含多页表单的状态。 在状态下,我们将存储当前所在的步骤或页面,以及用户在先前步骤中输入的值。

The first thing to determine in this function is to know if the user has started a new form or if we need to be on some other step/page of the form. To do this, we will maintain the step we are on in the $form_state[‘step’] variable. If that variable is not set, then we are on step zero. Otherwise, we increment the step by one. Then we store the current step in $form_state for future use.

在此功能中确定的第一件事是要知道用户是否已经启动了新表单,或者我们是否需要进入表单的其他步骤/页面。 为此,我们将在$form_state['step']变量中保留我们要执行的步骤。 如果未设置该变量,那么我们将进入步骤零。 否则,我们将步长增加一。 然后,我们将当前步骤存储在$form_state以备将来使用。

Next we’ll get a form for the current step. To do this we have to define the form elements for all the steps in a form array. This is done in the function getForm. In getForm the first step has the name and last name as two form elements; step two has the email and country and step three has a birthday. Here you can easily add or remove elements or even steps according to the form you are trying to build. If you go to the url <your drupal url>/?q=multipageform/form1 you will see the form as below

接下来,我们将获得当前步骤的表格。 为此,我们必须为表单数组中的所有步骤定义表单元素。 这是在功能getForm完成的。 在getForm ,第一步将名称和姓氏作为两个表单元素。 第二步有电子邮件和国家,第三步有生日。 在这里,您可以根据要构建的表单轻松地添加或删除元素,甚至步骤。 如果您转到url <your drupal url>/?q=multipageform/form1您将看到以下表单

alt

存储表单的状态。 (Storing the state of the form.)

Now we will need to store the state of the form at each stage so that when all the steps are finished, we can store the values in a file or database.

现在,我们将需要在每个阶段存储表单的状态,以便在完成所有步骤后,可以将值存储在文件或数据库中。

To do that we have to define the function multipageform_form1_submit as follows

为此,我们必须定义函数multipageform_form1_submit ,如下所示

function multipageform_form1_submit($form, &$form_state) {

    $form_state['storedvalues'][$form_state['step']] = $form_state['values'];
    if($form_state['step'] + 1 != getNumberOfSteps()) {
        $form_state['rebuild'] = TRUE;
    }else {

        //Reached end of multipage form

    }

}

function getNumberOfSteps() {
    return count(getForm());
}

In the above code the function getNumberOfSteps returns the number of steps in the form based on the array of the steps which we have defined. Then in the function multipageform_form1_submit we get the values submitted by the user for the current step in $form_state['values'];. We store this value for further use in form_state against the current step in the statement

在上面的代码中,函数getNumberOfSteps基于我们定义的步骤数组以表格形式返回步骤数。 然后,在函数multipageform_form1_submit我们可以在$form_state['values'];获取用户为当前步骤提交$form_state['values']; 。 我们将该值存储在form_state中,以供语句中当前步骤使用

$form_state['storedvalues'][$form_state['step']] = $form_state['values'];

Then we check if this step is the last step. If it is not the last step, we set $form_state['rebuild']=TRUE so that the form is rebuilt and our function multipageform_form1 will generate the form with the next step.

然后,我们检查此步骤是否为最后一步。 如果不是最后一步,则设置$form_state['rebuild']=TRUE以便重建表单,并且我们的函数multipageform_form1将在下一步生成表单。

Now if you go to the form URL, enter some values and click next you should move to step two and three as seen below

现在,如果您转到表单URL,请输入一些值,然后单击下一步,您将移至第二步和第三步,如下所示

alt


alt

多页表单验证 (Multi-page form validation)

We might want to validate the data at each step based on the data we are collecting in the form and on some rules we have. To do that we have to write a function multipageform_form1_validate as follows

我们可能希望根据表单中收集的数据以及我们拥有的某些规则在每个步骤中验证数据。 为此,我们必须编写一个multipageform_form1_validate函数,如下所示

function multipageform_form1_validate($form, $form_state) {

    switch ($form_state['step']) {
        case '0':
            if(empty($form_state['values']['name']))
             form_set_error('name','Name cannot be empty');
          else if(empty($form_state['values']['last_name']))
             form_set_error('last_name','Last name cannot be empty');
            break;

        case '1':
            if(filter_var($form_state['values']['email'], FILTER_VALIDATE_EMAIL) == false)
                 form_set_error('email','Email is not valid');
            break;

        default:
            break;
    }

}

In the above function the first thing we have to determine is which step we’re on. We do that using $form_state['step'] in which we are storing the current step of the form.

在上面的函数中,我们首先要确定的是我们要走哪一步。 我们使用$form_state['step']进行此操作,在其中存储表单的当前步骤。

Then in the switch block we add cases of all the steps we want some validation in. In the above code we have done validations for step 0 and step 1. In step 0 we check if the name and last name are not empty and in step 1 we check if the email is valid. In case we find an error, we set the error using the Drupal function form_set_error which will not move the form to the next step and will show an error to the user:

然后在switch块中添加要进行验证的所有步骤的用例。在上面的代码中,我们对步骤0和步骤1进行了验证。在步骤0中,我们检查名称和姓氏是否不为空,并在步骤3中进行检查。 1我们检查电子邮件是否有效。 如果发现错误,则使用Drupal函数form_set_error设置错误,该函数不会将表单移至下一步,并向用户显示错误:

alt

多页表单提交 (Multi-page form submission)

Once all the steps are complete you will want to extract all the values and then maybe store it in a file or in the database. To do that you will have to modify the multipageform_form1_submit function as below

完成所有步骤后,您将需要提取所有值,然后将其存储在文件或数据库中。 为此,您将必须修改multipageform_form1_submit函数,如下所示

function multipageform_form1_submit($form, &$form_state) {

    $form_state['storedvalues'][$form_state['step']] = $form_state['values'];
    if($form_state['step'] + 1 != getNumberOfSteps()) {
        $form_state['rebuild'] = TRUE;
    }else {

        $finalformvalues=array();
        $currStep = 0;
        foreach (getForm() as $step) {
            foreach ($step as $key => $value) {
                if(strcmp($key,"submit") != 0) {
                    $finalformvalues[$key] = $form_state['storedvalues'][$currStep][$key];
                }
            }
            $currStep++;
        }
        //Store the values from $finalformvalues in database or file etc

    }

}

In the above function, once we detect that we have submitted the last step of the form, we get all the form element keys for all steps and then get the values which the user entered which we had stored in $form_state['storedvalues'] before putting them into the array $finalformvalues. Finally $finalformvalues will contain all the values for all form elements for all steps. This can then be further processed and stored.

在上面的函数中,一旦我们检测到提交了表单的最后一步,就获得了所有步骤的所有表单元素键,然后获得了用户输入的,我们存储在$form_state['storedvalues']在将它们放入数组$finalformvalues 。 最后, $finalformvalues将包含所有步骤的所有表单元素的所有值。 然后可以对其进行进一步处理和存储。

结论 (Conclusion)

Drupal’s Form API lets you create forms without worrying about how to render the HTML for it. Also, we can use the approach shown above to build longer forms which can be broken down into steps so that they are easier and more logical for users to process. Drupal helps us easily carry forward the state in various steps of the form and also provide hooks to validate the values and notify the user in case there are any problems. This all can be done with ease with the functionality that Drupal provides. Have fun creating your next multi-page form in Drupal!

Drupal的Form API使您无需担心如何呈现HTML即可创建表单。 同样,我们可以使用上面显示的方法来构建更长的表格,将其分解为多个步骤,以便用户更轻松,更合理地进行处理。 Drupal帮助我们轻松地在表单的各个步骤中继承状态,并提供钩子来验证值并在出现任何问题时通知用户。 借助Drupal提供的功能,可以轻松完成所有这些工作。 玩得开心在Drupal中创建您的下一个多页表单!

翻译自: https://www.sitepoint.com/building-multi-page-wizard-like-form-drupal/

drupal8 表单

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值