2
我已經爲mp3文件創建了一個自定義字段格式化程序,並添加了一個名爲「Provide Download Link」的設置表單字段,該字段是一個複選框。如果選中「提供下載鏈接」,我想提供文件下載鏈接。任何人都可以告訴我如何在drupal 8中創建這個下載鏈接?我必須通過動態下載鏈接到格式化程序模板文件(小枝),以便用戶可以通過單擊鏈接下載mp3文件。如何在drupal中創建文件下載鏈接8
我已經爲mp3文件創建了一個自定義字段格式化程序,並添加了一個名爲「Provide Download Link」的設置表單字段,該字段是一個複選框。如果選中「提供下載鏈接」,我想提供文件下載鏈接。任何人都可以告訴我如何在drupal 8中創建這個下載鏈接?我必須通過動態下載鏈接到格式化程序模板文件(小枝),以便用戶可以通過單擊鏈接下載mp3文件。如何在drupal中創建文件下載鏈接8
我假設你要添加的格式化的字段是允許文件e.g 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 %}