如何在drupal 8中创建文件下载链接

时间:2015-09-08 11:00:41

标签: drupal-8

我为mp3文件创建了一个自定义字段格式化程序,并添加了一个名为“提供下载链接”的设置表单字段,这是一个复选框。如果选中“提供下载链接”,我想提供文件下载链接。谁能告诉我如何在drupal 8中创建这个下载链接?我必须将动态下载链接传递给格式化程序模板文件(twig),以便用户可以通过单击链接下载mp3文件。

1 个答案:

答案 0 :(得分:1)

我假设你添加格式化的字段是一个允许上传文件的字段,例如mp3文件

Mp3Formatter.php假设这是格式化程序的类名。确保您的格式化程序类从FileFormatterBase扩展

    use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;

        // Get "Provide Download Link”  settings value.
        // Assuming the machine name you gave  to your setting is : download_link_setting.
        // Add the code below to your formatter class under the method body: viewElements
        // Get the referenced entities in this case files.

        $files = $this->getEntitiesToView($items);

        // initialise $url variable.

        $url = NULL;

        $download_link_setting = $this->getSetting(‘download_link_setting’);

        // Loop through the file entities.

        foreach ($files as $delta => $file) {

          // For each file add code below.
          // Check if the setting isn’t empty and then create the file url.

          if (!empty($download_link_setting)) {
            $mp3_uri = $file->getFileUri();
            $url = Url::fromUri(file_create_url($mp3_uri));
          }

          // Add the $url parameter to your render array e.g

          $elements[$delta] = [
            '#theme' => ‘mp3_formatter',
            '#item' => $item,
            '#url' => $url,
            '#filename' => $item->getFilename(),
          ];
        }

      return $elements;

在模块的.module文件中。

        // Register your theme under hook_theme.

        'mp3_formatter' => [
          'variables' => [
            'item' => NULL, 
            'url' => NULL, 
            'filename' => NULL,
          ],
        ],

在相应的TWIG模板中

        // Now add your download link into the twig element.
        // check if the url variable is set
        {% if url %}
          <a href="{{ url }}" download>{{ filename }}</a>
        {% else %}
          <p> {{ filename }} </p>
        {% endif %}