drupal8 表单_了解Drupal中的表单

本文深入探讨了Drupal8中表单的创建与处理方法,包括使用drupal_get_form函数生成表单,创建基本表单,验证及提交表单数据,以及使用字段集组织表单元素。文章还介绍了Drupal表单API的便利性和灵活性,使得表单的管理和维护更加容易。
摘要由CSDN通过智能技术生成

drupal8 表单

Web applications today are being used in all kinds of industries. They need to take in and process a lot of user data. The capturing of the data happens through HTML forms which let you create different types of input fields like textboxes, radio buttons etc. using HTML tags. These forms get difficult to maintain or update if they are written directly in the HTML code. Drupal provides a very good way of defining forms directly in your PHP code, while the form generation is done by Drupal itself. This makes it easy for you to create and maintain forms. In this article we are going to see how we can create forms in Drupal. The final code can be cloned from Github.

当今的Web应用程序正在各种行业中使用。 他们需要接收和处理大量用户数据。 数据捕获是通过HTML表单进行的,HTML表单使您可以使用HTML标签创建不同类型的输入字段,例如文本框,单选按钮等。 如果这些表单直接用HTML代码编写,则很难维护或更新。 Drupal提供了一种非常好的直接在PHP代码中定义表单的方法,而表单生成是由Drupal本身完成的。 这使您轻松创建和维护表单。 在本文中,我们将了解如何在Drupal中创建表单。 最终代码可以从Github克隆。

drupal_get_form函数– Drupal中的表单生成 (The drupal_get_form function – Form generation in Drupal)

The whole magic of form creation in Drupal is performed by the function drupal_get_form. This function returns a renderable form array to the Drupal system. It takes an argument as the form_id: a unique identifier to identify the form, and if a function with the same name exits then that function is called to build it. You can read more about drupal_get_form at the link https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_get_form/7

Drupal中表单创建的全部魔力是由drupal_get_form函数drupal_get_form 。 此函数将可渲染的表单数组返回给Drupal系统。 它使用一个参数作为form_id:一个用于标识表单的唯一标识符,并且如果退出具有相同名称的函数,则将调用该函数来构建它。 您可以在链接https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_get_form/7上阅读有关drupal_get_form更多信息。

在Drupal中创建基本表单 (Creating a basic form in Drupal)

Let’s start by creating a small module which will create a menu callback and then on that menu callback create a form using the drupal_get_form function. To create a module add a folder to your Drupal installation sites\all\modules\drupalform and add two files to it: drupalform.info and drupalform.module with the following code:

让我们从创建一个小模块开始,该模块将创建菜单回调,然后在该菜单回调上使用drupal_get_form函数创建一个表单。 要创建模块,请在您的Drupal安装sites\all\modules\drupalform添加一个文件夹, sites\all\modules\drupalform其中添加两个文件: drupalform.infodrupalform.module ,其代码如下:

drupalform.info (drupalform.info)
name = drupalform
description = This module creates a form using Drupal.
core = 7.x
drupalform.module (drupalform.module)
<?php
/**
 * @file
 * This is the main module file.
 */

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

  if ($path == 'admin/help#rupalform') {
    $output = '<h3>' . t('About') . '</h3>';
    $output .= '<p>' . t('The drupalform module shows how to create forms using Drupal.') . '</p>';
    return $output;
  }
}

With the above code you should be able to see your module in the available module list and should be able to enable it as shown below. If these steps seem mysterious or complicated, please see my last tutorial for a good Drupal Module introduction.

使用上面的代码,您应该能够在可用模块列表中看到您的模块,并且应该能够如下所示启用它。 如果这些步骤看起来很神秘或很复杂,请参阅我的上一教程,以获得有关Drupal Module的良好介绍

alt

Once we have done this we will add a menu callback using hook_menu and create a form on the page. The code for that is as follows

完成此操作后,我们将使用hook_menu添加菜单回调并在页面上创建一个表单。 的代码如下

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

  return $items;
}

function drupalform_form1() {
    $form = array();


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

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

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

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

      return $form;
}

In the above code in the implementation of hook_menu we create a menu item whose page_callback is drupal_get_form and the argument to that is the form_id "drupalform_form1". The function drupalform_form1 returns the form array which we want to create.

在上述执行hook_menu代码中,我们创建一个菜单项,其page_callbackdrupal_get_form ,其参数为form_id “ drupalform_form1”。 函数drupalform_form1返回我们要创建的表单数组。

In the function drupalform_form1 we create three text fields: name, last_name, email, and one select box for the country. In the select box we specify the options of the country with an array. We have also added a Submit button, so the user can actually submit the form. Now you should be able to go to your menu url: <your drupal base url>/drupalform/form1 and see the form as follows

在函数drupalform_form1我们创建三个文本字段:name,last_name,email和一个国家/地区的选择框。 在选择框中,我们使用数组指定国家/地区的选项。 我们还添加了一个“提交”按钮,因此用户可以实际提交表单。 现在您应该可以转到菜单URL: <your drupal base url>/drupalform/form1并看到如下所示的表单

alt

验证Drupal表单 (Validating a Drupal form)

Drupal uses naming conventions heavily to identify which functions to call on which events. The complete Drupal hook system is based on naming conventions. Similarly, the function called to validate your form data has to follow the naming convention <form_id>_validate and it will be passed the form_state as a variable.

Drupal大量使用命名约定来标识在哪些事件上调用哪些函数。 完整的Drupal挂钩系统基于命名约定。 同样,用来验证表单数据的函数必须遵循命名约定<form_id>_validate ,它将作为变量传递给form_state

Hence, for our form the function name will be:drupalform_form1_validate($form, $form_state).

因此,对于我们的表单,函数名称将为: drupalform_form1_validate($form, $form_state)

The values which the user has entered will be present in an array $form_state['values'] with the same id as you specified in the form. So if we have to do the validations for our form the function will be:

用户输入的值将出现在数组$form_state['values'] ,该ID与您在表单中指定的ID相同。 因此,如果我们必须对表单进行验证,则该函数将为:

function drupalform_form1_validate($form, $form_state) {

  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');
  else if(filter_var($form_state['values']['email'], FILTER_VALIDATE_EMAIL) == false)
    form_set_error('email','Email is not valid');
}

In the above function we check if the name and last_name are not empty and that the email is valid. If that is not the case we set a form error using the Drupal function form_set_error. This will display the error to the user and the form will not be submitted.

在上面的函数中,我们检查名称和last_name是否不为空以及电子邮件是否有效。 如果不是这种情况,我们使用Drupal函数form_set_error设置表单错误。 这将向用户显示错误,并且不会提交表单。

If you submit the form by entering an empty name you should see the following error on the screen:

如果您通过输入一个空名称提交表单,您应该在屏幕上看到以下错误:

alt

提交Drupal表单 (Submitting a Drupal form)

Similar to the validation function the submit function is also called based on the naming convention and the function name should be <form_id>_submit. Again, the variable $form_state will be passed to it. Our submit function will thus be defined as:

与验证功能类似,还基于命名约定调用<form_id>_submit函数,并且函数名称应为<form_id>_submit 。 同样,变量$form_state将传递给它。 因此,我们的Submit函数将定义为:

function drupalform_form1_submit($form, $form_state) {
   //Depending on the type of form you can add the logic
   //to store the details of the form 
   //by adding it in a Drupal table.
   //or sending a mail to the admin
   //Storing in a file
   //or pass it to some other service
   drupal_set_message("Form has been submitted");
}

Now if we pass all the valid fields you will get the following message on screen.

现在,如果我们通过所有有效字段,您将在屏幕上看到以下消息。

alt

在Drupal表单中使用字段集来分隔元素。 (Using Field sets in Drupal Forms to separate elements.)

Sometimes when the form is bigger and has many fields you might want to break it into small sections so that the form seems more logical to the user. To do this you can create fieldsets in Drupal to create groups of fields.

有时,当表单较大且具有许多字段时,您可能希望将其分成小部分,以使表单对用户而言看起来更合乎逻辑。 为此,您可以在Drupal中创建字段集以创建字段组。

To create a fieldset called basicdetails to hold the fields we defined above we will have to update the drupalform_form1 as follows

要创建一个称为basicdetails的字段basicdetails来保存我们上面定义的字段,我们将必须更新drupalform_form1 ,如下所示

function drupalform_form1() {
    $form = array();


     $form['basicdetails']=array(
        '#type'=>'fieldset',
        '#title'=>t('Enter your Basic details below'),
        '#description'=>t('These are all madatory')
      );

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

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


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

      return $form;
}

This will create a separate fieldset as shown below

这将创建一个单独的字段集,如下所示

alt

可在Drupal表单中使用的不同表单元素 (The different form elements that can be used in Drupal forms)

Drupal provides a great number of different types of fields which we can use in our forms. I will update our form to use some of these by creating two more field sets for address details and additional details. The updated code is below:

Drupal提供了许多不同类型的字段,我们可以在表单中使用它们。 我将通过为地址详细信息和其他详细信息创建另外两个字段集来更新我们的表单以使用其中的一些表单。 更新后的代码如下:

function drupalform_form1() {
    $form = array();


     $form['basicdetails']=array(
        '#type'=>'fieldset',
        '#title'=>t('Enter your Basic details below'),
        '#description'=>t('These are all madatory')
      );

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

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

  $form['addressdetails']=array(
        '#type'=>'fieldset',
        '#title'=>t('Enter your Address details below'),
        '#description'=>t('These are all madatory')
      );

        $form['addressdetails']['country']=array(
            '#type'=>'select',
            '#title'=>t('Select your country'),
            '#options'=>array('USA','UK','France','Japan')
          );
        $form['addressdetails']['city']=array(
            '#type'=>'textfield',
            '#title'=>t('Enter your city'),
            '#description'=>t('Your city name goes here')
          );
        $form['addressdetails']['localaddress']=array(
            '#type'=>'textarea',
            '#title'=>t('Enter address'),
            '#description'=>t('Your Address name goes here')
          );

     $form['additionaldetails']=array(
        '#type'=>'fieldset',
        '#title'=>t('Enter your other details below'),
        '#description'=>t('These are all optional')
      );

        $form['additionaldetails']['gender']=array(
            '#type'=>'radios',
            '#title'=>t('Gender'),
            '#options'=>array('Male','Female')
          );

        $form['additionaldetails']['suscribtion']=array(
            '#type'=>'checkboxes',
            '#title'=>t('I want to subscribe for'),
            '#options'=>array('Email newsletter','Offer vouchers')
          );

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

        $form['#attributes']['enctype'] = 'multipart/form-data';

         $form['additionaldetails']['picture']=array(
            '#type'=>'file',
            '#title'=>t('Upload your picture'),
          );



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

      return $form;
}

This is what the new fieldsets look like:

这是新的字段集的样子:

alt

结论 (Conclusion)

Drupal helps you create and process forms right inside your module. The APIs Drupal offers make it very simple to make an addition or modification of your form as the forms are arrays and even the validation and submission happens in a different function. This modular approach keeps the form code in your module clean and easy to maintain. You also do not need to bother with the HTML details of the form if you use the Drupal form API – all the HTML is auto-generated. Have fun creating your next form in your Drupal module!

Drupal帮助您直接在模块内部创建和处理表单。 Drupal提供的API使表单的添加或修改变得非常简单,因为表单是数组,甚至验证和提交都在不同的函数中进行。 这种模块化方法可以使模块中的表单代码保持整洁并易于维护。 如果您使用Drupal表单API,您也无需理会表单HTML详细信息-所有HTML都是自动生成的。 玩得开心在您的Drupal模块中创建您的下一个表单!

If you'd like us to cover a more specific use case or go into more details, or just have feedback, let us know in the comments below!

如果您希望我们涵盖更具体的用例或进入更多详细信息,或者只是想反馈,请在下面的评论中告诉我们!

翻译自: https://www.sitepoint.com/understanding-forms-drupal/

drupal8 表单

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值