如何在 drupal8 中设置 'managed_file' 类型的默认值

How to set default value for 'managed_file' type in drupal8

在 drupal 8 中,我创建了一个自定义表单来上传 .xlsx 文件。上传.xlsx文件时文件保存成功,但下次访问页面时忘记了文件名。所以我想为元素显示一个默认值。这些是我的代码,但没有效果。请指教,谢谢

$form['test_file'] = [
  '#type' => 'managed_file',
  '#title' => $this->t('Test File'),
  '#upload_location' => 'private://',
  '#upload_validators' => [
    'file_validate_extensions' => ['xls xlsx'],
  ],
  '#description' => $this->t('Please upload test data excel file.'),
  '#default_value' => $config->get('test_file'),
];

$element[#value][fids]是managed_file字段处理过程中使用的条件。 (参见 core/module/file/src/Element/ManagedFile.php ) 试试这个:

$fid = $config->get('test_file'); // the fid of the file you want to show in the field
$form['test_file'] = [
  '#type' => 'managed_file',
  '#title' => $this->t('Test File'),
  '#upload_location' => 'private://',
  '#upload_validators' => [
    'file_validate_extensions' => ['xls xlsx'],
  ],
  '#description' => $this->t('Please upload test data excel file.'),
  '#default_value' => null, // don't need
];
// A condition for your test_file variable
if($fid != NULL){
  $form['test_file']['#value']['fids'] = array($fid);
}