Drupal:需要文件上传吗? [英] Drupal: File upload required?
本文介绍了Drupal:需要文件上传吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于某种原因,当我尝试要求上传文件时,表单中断。这是它的代码:
For some reason, my form breaks when I try to make a file upload required. Here is the code for it:
$form_id = "upload_form";
$form[$form_id] = array (
'#type' => 'fieldset',
'#description' => t('This is a utility to import nodes from a Comma Separated Value file. To begin, pick a node type, and upload a CSV.'),
);
$form[$form_id]['type'] = array(
'#title' => t('Enter node type'),
'#type' => 'textfield',
// '#autocomplete_path' => '', TODO: autocomplete for node types
'#required' => TRUE,
'#description' => t('This node type should already exist. If it doesn\'t, create it first.'),
);
$form[$form_id]['upload'] = array(
'#type' => 'file',
'#title' => t('Upload CSV file'),
// '#size' => 40,
'#description' => t('This will not work for a non-CSV file.'),
// '#required' => TRUE, TODO: breaks it. why?
);
$form[$form_id]['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
$form['#attributes'] = array('enctype' => 'multipart/form-data');
在Drupal支持上网站,有人说不可能要求上传文件。
On a Drupal support site, someone says that it's impossible to make file uploads required. Is this true?
推荐答案
这是我使文件字段为必填项的解决方法:
This is my workaround to make file field required:
<?
// A piece of form that defines the file field
$form['attachment'] = array(
'#type' => 'file',
'#title' => t('Title'),
//'#required' => TRUE, // check this manually
);
// Form validation hook
function yourformname_validate($form, &$form_state) {
// Validate file
$validators = array(
'file_validate_extensions' => array('doc txt pdf'), // does not work for user 1
'file_validate_size' => array(1000000, 0),
);
$file = file_save_upload('attachment', $validators, file_directory_path());
if ($file) {
$form_state['values']['attachment'] = $file; // drupal file object
}
else{
form_set_error('attachment', "File is required");
}
}
?>
这篇关于Drupal:需要文件上传吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文