dashan 提交于
论坛:
Drupal Commerce 提供的是一个文本框,这可以在数量字段的字段显示设置中设置。 如安装 Commerce Kickstart Product UI 模块,可提供类似淘宝的 Spinner 微调选择框,实际上使用 jQuery.spinner 插件。
但如果安装 commerce_stock 实现库存管理,或者再来个限购字段,那么 Spinner 有时也不够友好,用户可以选择超过库存或限购的数量。
如果使用 select 下拉框来动态构建选项,则可以比较好的处理库存和限购,但库存量比较大时,我们不便全部列出,只列出 1-10 的选项,这样处理应该可以满足大多数顾客的需求了,如果购买超过 10 件,则可能需要多次添加到购物车。 那我们怎么来修改这个字段呢? 其实,商品页的添加到购物车这些选项,是在一个以 commerce_cart_add_to_cart_form 为基础的表单中,根据Drupal 的原则,任何表单都是可能通过 hook_form_alter来修改表单的元素,但我使用了针对特定表单的 hook,这样可以提高网站的性能,下面是实现代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
//将数量文本框出修改为下拉框 function commerce_custom_form_commerce_cart_add_to_cart_form_alter(& $form , & $form_state , $form_id ) { $product = commerce_product_load( $form [ 'product_id' ][ '#value' ]); //查库存数量 $stock_count = 0; if (! empty ( $product ->commerce_stock) && $product ->commerce_stock[LANGUAGE_NONE][0][ 'value' ]>0) { $stock_count = intval ( $product ->commerce_stock[LANGUAGE_NONE][0][ 'value' ]); } //查限购数量 $limit_max = 0; if (! empty ( $product ->commerce_product_limit_max) && $product ->commerce_product_limit_max[LANGUAGE_NONE][0][ 'value' ]>0) { $limit_max = $product ->commerce_product_limit_max[LANGUAGE_NONE][0][ 'value' ]; } if ( $stock_count == 0) { $limit = 0; } elseif ( $limit_max < $stock_count && $limit_max > 0) { $limit = $limit_max ; } elseif ( $limit_max >= $stock_count && $stock_count > 0) { $limit = $stock_count ; } else { if ( $stock_count > 10) { $limit = 10; //超过10件的,只显示 10 个 } else { $limit = $stock_count ; } } $i = ( $limit == 0) ? 0:1; while ( $i <= $limit ) { $values [] = $i ; $i ++; } $options = array_combine ( $values , $values ); //dpm($product,'$product'); $form [ 'quantity' ][ '#type' ] = 'select' ; $form [ 'quantity' ][ '#options' ] = $options ; unset( $form [ 'quantity' ][ '#size' ]); //select类型没有此选项 }
|
- 登录以发表评论