标签:
Drupal中创建自定义表单,用来上传文件,对上传文件做一些操作。以下是放在Module中的代码:
一、菜单建立表单路径
/** Implementation of hook_menu(). */ function moduleName_menu () { $items = array(); $items[‘admin/import‘] = array( ‘title‘ => ‘title‘, ‘page callback‘ => ‘drupal_get_form‘, ‘page arguments‘ => array(‘importform‘), ‘access callback‘ => TRUE, ‘type‘ => MENU_LOCAL_TASK, ‘context‘ => MENU_CONTEXT_INLINE, // 只在菜单里显示 ); return $items; }
二、生成表单
function importform($form, &$form_state) { $form = array(); $form[‘file‘] = array( ‘#type‘ => ‘file‘, ‘#title‘ => ‘题库模板文件‘, ‘#description‘ => "请上传题目录入文件, 允许的文件格式为: xlsx", ); $form[‘submit‘] = array( ‘#type‘ => ‘submit‘, ‘#value‘ => ‘导入‘, ); return $form; }
三、验证表单
function importform_validate($form, &$form_state) { $file = file_save_upload(‘file‘, array( ‘file_validate_extensions‘ => array(‘xlsx‘), )); if ($file) { if ($file = file_move($file, ‘public://‘)) { $form_state[‘values‘][‘file‘] = $file; } else { form_set_error(‘file‘, t(‘文件上传失败!‘)); } } else { form_set_error(‘file‘, t(‘没有文件被上传!‘)); } }
四、上传表单
function importform_submit($form, &$form_state) { $file=$form_state[‘values‘][‘file‘]; unset($form_state[‘values‘][‘file‘]); $file->status = FILE_STATUS_PERMANENT; file_save($file); //这边可以做一些逻辑事情 drupal_set_message(t(‘@filename 该文件已上传成功!‘, array(‘@filename‘ => $file->filename))); }
标签:
原文地址:http://www.cnblogs.com/RockyZhang/p/5513611.html