简体   繁体   English

Drupal 8 Webform 为上传的文件名添加前缀

[英]Drupal 8 Webform add prefix to uploaded file names

I have a webform with a file upload field.我有一个带有文件上传字段的网络表单。 I need do one of two things.我需要做两件事之一。 Either upload files into a subfolder inside the private area, OR, add a prefix to the filename that the user is uploading.将文件上传到私有区域内的子文件夹中,或者为用户正在上传的文件名添加前缀。 The user can upload several files.用户可以上传多个文件。 The webform editor allows you to 'Rename' the file and use tokens for this, but I don't see any way of preserving the original file name.网络表单编辑器允许您“重命名”文件并为此使用令牌,但我看不到任何保留原始文件名的方法。 I can hack getFileDestinationUri() in WebformManagedFileBase.php to do what I want, but obviously I would rather not do that.我可以破解 WebformManagedFileBase.php 中的 getFileDestinationUri() 来做我想做的事,但显然我不想那样做。 Am I missing something?我错过了什么吗?

It turns out that you can use the drupal form alter hook to alter the destination.事实证明,您可以使用 drupal 形式更改挂钩来更改目的地。 I had thought of this but felt if was unlikely to work.我曾想过这一点,但觉得不太可能奏效。 It does.确实如此。

Below is MY code solution: (I may be missing container types)以下是我的代码解决方案:(我可能缺少容器类型)

function _mymodule_fix_elements(&$elements) {
  foreach ($elements as $key => &$element) {
    if (strpos($key, '#') !== 0) {
      if (is_array($element)) {
        if (isset($element['#type'])) {
          if (($element['#type'] == 'fieldset') ||
              ($element['#type'] == 'webform_flexbox') ||
              ($element['#type'] == 'container')) {
            _mymodule_fix_elements($element);
          } else if ($element['#type'] == 'managed_file') {
            $pattern = $element['#upload_location'];
            if (strpos($pattern, 'private:') === 0) {
              $element['#upload_location'] = $pattern . '/' . $key;
            }
          }
        }
      }
    }
  }
}

function mymodule_form_alter(&$form, &$form_state, $id) {
  if (strpos($id, 'webform_') === 0) {
    _mymodule_fix_elements($form['elements']);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM