Drupal Form API

本文深入解析Drupal中表单生成引擎如何通过调用element_info()函数收集表单元素信息,进而实现自定义元素类型,如仅接受数值输入的文本框。接着,解释了表单验证、提交功能的配置方式,以及如何利用hook_form_alter()钩子让模块个性化定制表单。文章以数组形式详细展示了如何声明表单元素,包括它们的层次结构和属性,并提供了构建文本字段示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Now, form generation engine collects the information about formelements bycalling element_info() function.This in turn callshook_element(), which might beimplemented by other modules. We can use this hook to create ourown specialized element types, eg textbox which only takes numericinput.

Now engine know the definition of all element type, so it next itwill look for form validation function. The form validationfunction to use can be specified in any of theforms #validate,orformID_validate() or #base_validate()#base isthe value that you specify with the form array.

Engine will look for submit function to which the form will besubmitted. They can be specified asvalue #submit for key,orformID_submit() functionor #base_submit() function.Once it gets the submit function for the form itcalls hook_form_alter() togive any module which wants to change the form. Basically it’s ourtime to modify someone else’s form to add or remove the inputfields and/or descriptions.

Form elements are now declared in array fashion, with thehierarchical structure of the form elements themselves as arrayelements (which can be nested), and each form elementsproperties/attributes listed as array elements in key/valuepairs--the key being the name of the property/attribute, and thevalue being the value of the property/attribute. For example,here's how to go about constructing a textfield formelement:

drupal_get_form doesthe following:

 

  • Starts the entire form-building process by gettingthe $form fromthe builder function
  • Translates the $form['name'] itemsinto actual form elements
  • Performs any validation and "clean-up" that needs to be done, andcalls custom validation functions if declared
  • Submits the form if a submit function is declared, and the form hasbeen submitted
  • Calls any custom theming functions that have been declared
  • Returns an HTML string which contains the actual form.
The preferred method of submitting forms with the API is throughthe use of a form submit function. This has the same namingconvention and arguments as the validation function,except _submit isappended instead. Any forms which are submitted from a buttonof type=> 'submit' willbe passed to their corresponding submit function if it isavailable. This method is more secure thangrabbing $_POST['edit'] andusing a switch statement.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值