How to shorten attachment links to something more readable
Attachment links
Without this code, when attachment file names display in tables they can be super long and distort the readability of the field and the table as a whole. Relabeling gives the column a consistent width. This code could be further updated to specify a certain view for your specific use case.
There are two ways to label attachment files:
Option A : Default Name
Option B: Field File Name (Table views only)
Option A: Default Name
Modifies all attachments that are a File field asset with a default attachment name using HTML
The JS
We create a handler that renders on any application view and sets the attachment link text.
Adjust text to the preferred nomenclature if other than Attachment (i.e. "File")
"Attachment"
You may use:
Attachment
View
File
Option B: Field File Name (Table views only)
Modifies one of the attachment field File types HTML to another field instead. This will only work for connected file fields connected to a parent table view.
Examples:
Work Orders table view connected to multiple attachments
The JS
We create a function that renders on any application view and sets the attachment link text in the table view using HTML. We add also add the field to the table as well to leverage the text used in that same table and use the span id attribute to tie it to the file field.
/********************************************************/
/** Relabel Attachment Links in Tables to Name Field **/
/********************************************************/
// replace attachment file name with name field. hide_name to hide nameField from table
function replaceAttachmentFilenameWithNameField(fileFieldId, nameFieldId, hide_name = true) {
// find each attachment cell
$("td." + fileFieldId).each(function() {
// find each attachment link within the cell
$(this).find("span").children("span").each(function() {
let attachmentType = "View";
let fileRecordId = $(this).context.id;
// if neighboring field exists on same table, retrieve the corresponding type
$(this).closest("tr").children("td." + nameFieldId)
.find("span")
.children("span")
.each(function() {
let nameRecordId = $(this).context.id;
if (fileRecordId == nameRecordId) {
attachmentType = $(this).text();
}
});
// update link contents
$(this).find("a").html(attachmentType);
});
});
// hides the name field ID based on third parameter. Default true.
if (hide_name){
$("td." + nameFieldId).hide();
$("th." + nameFieldId).hide();
}
}
$(document).on("knack-view-render.any", function (event, view, data) {
$("a.kn-view-asset").html("View");
replaceAttachmentFilenameWithNameField("field_XXX", "field_YYY");
});