人天性是懒惰的,网站浏览者也是一样,很多时候,浏览者在输入单词时候,都希望能有自动提示功能,如果表单能自动完成,是能够提高不少的用户体验。Drupal 7能够很方便的创建自动完成的textfield,下面讲解如何做:
让我们想象一下,你正在构建一些表单,你想帮助用户自动完成。例如,这个可以是一个“城市”的输入文本框。你可以有类似下面的形式:
1' N: W. f/ ~' y' y 23 4* \% ]& u" ?4 a g 5 6 7 8 9 10 I: G+ y) x) G1 @& A' ] 11# m: }$ W3 Q) K" B' D; n 12+ a+ D( O7 ^1 U 13 | function module_name_form() {; l2 [3 N7 W! j% I; V; b $form = array(); $form['city'] = array( '#title' => t('City'), '#type' => 'textfield',. g! V) I$ i" g0 `& Z '#autocomplete_path' => 'example/autocomplete', //留意这行。下面将做讲解。 );0 [) c0 l# K2 ^; Z5 L8 V% g $form['submit'] = array( '#type' => 'submit',! U; _5 g7 N5 q7 c8 `' S '#value' => 'Save', ); y. U( b' y8 H9 U return $form;& `5 a: F# M5 ~ } |
上面代码,最关键的部分是:'#autocomplete_path' => 'example/autocomplete',它定义了一个回调到textfield,当用户在文本框输入一些文本,drupal 将会发送一个请求到example/autocomplete 路径,同时通过Json回调结果回来,而example/autocomplete我们是可以用hook_menu 菜单系统实现:
12- W. L, i4 _1 y: p 3& G# T7 d) `) i& F- P 4 5! q4 M! k4 f7 L4 ] l" v9 m- |) A 6 g4 w- \7 ^# v4 f. C, x 7* B' S( F0 {3 ^( j& J5 e, x4 [ 88 j( H! V8 Z' `- N1 F1 k# L | function module_name_menu() { $items['example/autocomplete'] = array( 'page callback' => '_module_name_autocomplete',//这个是函数 function _module_name_autocomplete($string),下面将讲述。* o; g: U! E9 `1 k( ~) n; R 'access arguments' => array('access example autocomplete'), 'type' => MENU_CALLBACK6 \# G2 C/ c0 ~$ [# {! q ); return $items; } |
最后一步是创建函数 _module_name_autocomplete:
1" Q" M* X8 Z% e% H1 B- S' q 2$ j) z3 Z4 a% p. l- ~8 g9 K0 Y 3 m J9 v6 Z9 L) A 45 6 ~4 u+ p. i, N9 z4 }$ v/ ~9 i% u 7 8 9 10 11 121 y/ ?2 p) o8 P/ n/ d4 C 13* o7 c8 s1 X) x- p- H% }1 I2 o$ m 14- |0 r0 T* \; V; O) i) S4 l% q 15 W4 a7 g. `& ^ 16% r" S* m4 `0 A1 I6 G* z/ v 17, A9 G/ x& z3 n2 f) f, R) l | function _module_name_autocomplete($string) { $matches = array(); // Some fantasy DB table which holds cities $query = db_select('cities', 'c'); // Select rows that match the string8 A3 I& M& p) l $return = $query ->fields('c', array('city')) ->condition('c.city', '%' . db_like($string) . '%', 'LIKE')8 S; q5 _* c& M0 ^ ->range(0, 10) ->execute(); ) p. f0 G7 C7 c$ s // add matches to $matches & W* @- ^# g1 j8 M. s& N; s- J foreach ($return as $row) {; H% }1 N* `9 D) w$ m" q e' e+ i $matches[$row->city] = check_plain($row->city); _2 M H. m3 Q3 [4 F } // return for JS drupal_json_output($matches); } |
这个函数我们通过db_select 读取数据库cities表的数据,从表数据中找到与用户输入相类似的条目。(如果不习惯db_select,也可以用回db_query,drupal 7同样支持)
如果你想要更多比较完整的例子,你可以去看看drupal 7的核心模块 taxonomy,里面有一个函数function taxonomy_autocomplete,大概在79行(‘modules/taxonomy/taxonomy.pages.inc’)。
猪跑啦网站的添加新问题页,http://www.drupalla.com/question/ask 是autocomplete,
还有也可以看看我的另外一个网站图标酷(http://www.openico.com),那个搜索表单,也是autocomplete的。
现在,我猜想你应该能完成一个autocomplete 了,赶紧试一下吧,实践最关键。
欢迎光临 国外设计欣赏网站 - DOOOOR.com (https://www.doooor.com/) | Powered by Discuz! X3.4 |