Drupal7 managed_file表单

时间:2013-10-04 14:21:38

标签: forms drupal-7

我在Drupal自定义模块中有这个managed_file表单,用户可以上传图像并将其保存在sites / default / files下。

     $form['Background_image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image'),
    '#progress_message' => t('Please wait...'),
     '#progress_indicator' => 'bar',
    '#description' => t('Click "Browse..." to select an image to upload.'),
    '#required' => TRUE,
     ///'#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
    '#upload_location' => 'public://backgroundimage/'
    '#default_value' => $this->options['Background image'],
    );

如何添加函数来获取上传的文件? 我尝试了这个,但它没有用。

    $image = file_load($form_state['values']['Background_image']);

1 个答案:

答案 0 :(得分:3)

您应该能够只创建表单元素,然后使用$form_state['values']数组来获取fid。像这样:

function my_module_form() {
  $form = array();
  $form['background_image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image'),
    '#progress_message' => t('Please wait...'),
    '#progress_indicator' => 'bar',
    '#description' => t('Click "Browse..." to select an image to upload.'),
    '#required' => TRUE,
    '#upload_location' => 'public://backgroundimage/',
    '#default_value' => $this->options['background image'] //fid
   );
   return $form;
}

function my_module_form_submit($form, &$form_state) {
  $file = file_load($form_state['values']['background_image']);
  $file->status = FILE_STATUS_PERMANENT;
  file_usage_add($file, 'module_name', 'entity_name', $entity_id);
  file_save($file);
}

我刚刚写了那个,所以我确定有语法错误:)但这就是主意。如果您没有从$form_state['values']['background_image']获取文件ID,我会尝试在您的提交处理程序中删除并转储$form_state['values']的内容:

function my_module_form_submit($form, &$form_state) {
  die(var_dump($form_state['values']['background_image']));
}

这应该告诉你一些关于从你的表单中返回的事情。