I have created a custom field formatter for mp3 files and added a settings form field named "Provide Download Link" which is a checkbox. I want to provide a file download link if the "Provide Download Link" is checked. Can anyone please tell me how can I create this download link in drupal 8? I have to pass the dynamic download link to the formatter template file(twig) so that user can download the mp3 file by clicking the link.
3
votes
1 Answers
1
votes
I am assuming the field you are adding the formatter is a field that allows uploading of files e.g mp3 files
Mp3Formatter.php assuming that’s the formatter’s class name. Make sure your formatter class extends from 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;
In the .module file of your module.
// Register your theme under hook_theme.
'mp3_formatter' => [
'variables' => [
'item' => NULL,
'url' => NULL,
'filename' => NULL,
],
],
In the corresponding TWIG template
// 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 %}