参考school_users_import
- 在表格开始处定义一个显示返回信息的区域
$form['mesg'] = array('#markup' => '<div id="replace_textfield_div"></div>');
- 给表格添加类
$form['#attributes'] = array('class' => array('block-progress'));
3.在CSS文件中添加样式,令进度条单独一行显示
.block-progress .ajax-progress {
display: block;
}
4.给submit按钮添加Ajax进度条设置
$form['add_batch'] = array(
'#type' => 'submit',
'#value' => '导入',
'#ajax' => array(
'progress' => array('type' => 'bar',
'url' => url('school-users/import-progress')),
// #ajax has two required keys: callback and wrapper.
// 'callback' is a function that will be called when this element changes.
'callback' => 'school_users_import_callback',
// 'wrapper' is the HTML id of the page element that will be replaced.
'wrapper' => 'replace_textfield_div',
// There are also several optional keys - see ajax_example_autocheckboxes
// below for details on 'method', 'effect' and 'speed' and
// ajax_example_dependent_dropdown for 'event'.
'event' => 'click',
),
'#attributes' => array('onclick' => '
jQuery("#replace_textfield_div").hide();return true;'),
);
5.更新进度
if ($rows % 10 === 0) {
$handle = fopen(temporary://school_users_import_progress', 'w');
fwrite($handle, $rows . '/' . $line_count);
fclose($handle);
}
6.添加ajax进度查询的回调函数
function school_users_import_progress() {
$handle = fopen('temporary://school_users_import_progress', 'r');
$line = fgets($handle, 1024);
$items = preg_split("#/#", $line);
$percentage = $items[0] * 100 / $items[1];
fclose($handle);
drupal_json_output(array('percentage' => (int)$percentage));
}
function school_users_import_callback() {
if (file_exists('temporary://school_users_import_progress')) {
unlink('temporary://school_users_import_progress');
}
return '<div id="replace_textfield_div" style="width:100%">
<div class="message"> </div>
</div>';
}
7. 为回调函数添加菜单入口
$items['mobil-import/progress'] = array(
'title' => '导入进度',
'page callback' => 'mobil_import_progress',
'access arguments' => array('mobil import'),
'type' => MENU_CALLBACK,
);
8. 如果想在完成后执行一些动作(如刷新页面),可以在callback函数中添加ajax command
$commands = array();
$commands[] = ajax_command_alert("Alert");
return array('#type' => 'ajax', '#commands' => $commands);
ajax command reference:
http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax_commands/7
怎样在ajax form完成以后执行JS代码:http://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7
一些内置的ajax命令:https://api.drupal.org/api/drupal/includes!ajax.inc/group/ajax_commands/7
如果进度条需要在几个按钮的下面显示,可以把按钮用<div class=”progress-button-group”></div>括起来。
评论