我为 mp3 文件创建了一个自定义字段格式化程序,并添加了一个名为“提供下载链接”的设置表单字段,这是一个复选框。如果选中“提供下载链接”,我想提供文件下载链接。谁能告诉我如何在 drupal 8 中创建这个下载链接?我必须将动态下载链接传递给格式化程序模板文件(twig),以便用户可以通过单击链接下载 mp3 文件。
问问题
7476 次
1 回答
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 %}
于 2015-09-10T13:08:20.263 回答