谁能建议如何最好地设置一个临时变量与范围之间的钩子使用?
我有一个自定义模块,用于检查和警告是否尝试上传的文件与系统上的现有文件匹配。
我使用hook_form_alter来识别特定的上传表单,并使用hook_file_validate来检查文件是否以前上传过。
我的问题是这两个钩子没有共享一个共同的参数——我需要将信息从hook_form_alter传递回hook_validate。
我希望函数共享的信息是一个简单的布尔值,应该在文件上传完成/驳回后立即销毁,因此使用variable_set将其持久化到数据库是多余的。我不认为session或者cookie方法是最好的。
更新:
全局方法:
function duplicate_uploads_warning_init(){
$GLOBALS['processed'] = 'testing';
}
function duplicate_uploads_warning_file_validate($file){
drupal_set_message("PROCESSED[file-validate]: {$GLOBALS['processed']}", 'warning');
}
function duplicate_uploads_warning_form_alter(&$form, &$form_state, $form_id){
if( $form_id == 'file_entity_add_upload' ){
drupal_set_message("PROCESSED[form-alter]: {$GLOBALS['processed']}", 'error');
$GLOBALS['processed'] = 'tested';
$form['#validate'][] = 'duplication_validate';
}
}
上面的代码在init钩子中设置GLOBALS[processed],并且该值会立即在hook_form_alter中确认。
然而,尝试将值重新分配给测试的失败。重新分配的值是我希望在hook_file_validate中看到的,但我仍然得到测试的初始值。
Hook_form_alter验证方法:
我尝试添加一个自定义验证函数,但图像的上传仍然发生在我打算停止它的地方。我的代码如下:
function duplication_validate($form, &$form_state) {
$data = duplicates($form_state['complete form']['upload']['#file']->filename);
if( sizeof($data) > 0 ){
form_set_error('test', 'testing validation');
return false;
}
}
我可以确认我的$data变量有内容并且sizeof测试返回大于0
使用variable_set将其持久化到数据库是多余的
我不同意它们是过度的(你可以很容易地删除变量),正如@2pha提到的,不建议使用全局变量。我认为你可以使用variable_set($name, $value)
, variable_get($name)
和variable_del($name)
而不用担心,除非你需要超级优化你的网站数据库查询。如果真的不想使用variable_*函数,那么cache_set()和cache_get()可能会起作用,因为你可以给它一个临时状态。
编辑,变量方法:
function duplicate_uploads_warning_init(){
$account = 'Drupal::currentUser();
variable_set($account->id() . '_processed', 'testing');
}
function duplicate_uploads_warning_file_validate($file){
$account = 'Drupal::currentUser();
$processed_var = variable_get($account->id() . '_processed');
drupal_set_message("PROCESSED[file-validate]: {$processed_var}", 'warning');
}
function duplicate_uploads_warning_form_alter(&$form, &$form_state, $form_id){
if( $form_id == 'file_entity_add_upload' ){
$account = 'Drupal::currentUser();
$processed_var = variable_get($account->id() . '_processed');
drupal_set_message("PROCESSED[form-alter]: {$processed_var}", 'error');
variable_set($account->id() . '_processed', 'tested');
$form['#validate'][] = 'duplication_validate';
}
}
…,在success或#submit回调函数中运行variable_del($account->id() . '_processed')
删除变量
可能$GLOBALS['processed']
与static
关键字初始化在别处....?