Skip to main content

Hey Airtable Community.


I need help with automating the repetitive task of manually changing the name of a file after it’s been uploaded into my base. As of right now, we have a user filling out a form, and after it’s submitted, I want that to trigger the name changing. I have a field that is automatically created with a formula based on information captured in the form that I want the name changed too.


I’ve been looking at using the Airtable automation feature, but after trying a bunch of things, I can’t get it to work (perhaps I’m just too new at this) I also feel like maybe using a script might be the answer, but I don’t know how to do that, and if that’s the path to get this to work, I’ll need your help too 🙂 . Ultimately, I’m not sure and was hoping you (the community) might know.


Thanks in advance everyone!

@greenant Thanks a Million

And thanks Heavens for rollback 😎


Found the solution... For those who are interested, check my video above to see the fields and the base structure to understand...


The inputs used from input.config() were:
recordID
newName

 

The rest is not necessary. There are some comments that explain the code, use google translator from Portuguese PT-BR to your language.

 

// Setup
let config = input.config()
let table = base.getTable("Lista mestra")

// Define a variável newName e atribui a ela o valor Nome ajustado
let newName = config.newName
console.log(config.newName)

// Cria o vetor para armazenar as infos do registro submetido
const record = await table.selectRecordAsync(config.recordID)
console.log(record)

// @ts-ignore > Ignora o erro devido a possibilidade do registro ser nulo, pois as condições gatilho da automação garantem que não será.
// Armazena as informações do(s) anexos no vetor attachmentField
let attachmentField = record.getCellValue("Documento")

// Cria um novo vetor vazio que receberá o(s) documento(s) renomeados para sobrescrever os existentes com nome original
let newAttachment =t]

// Vai executar o for para a quantidade de anexos que houver dentro do vetor attachmentField
for (let attachmentNumber, attachment] of attachmentField.entries()){
console.log(attachmentNumber,attachment,)

// Quebra a string do nome original do anexo em um vetor onde a extensão está separada em um endereço desse vetor
let findExtension = attachment.filename.match(/\.\w+$/) || /""]
let extension = findExtensionf0]
console.log(extension)

// Se o número de anexos é maior que 1, então ele renomeará os anexos e acrescentará um incrementador sequencial ao final
let fileSpecifcName = attachmentNumber>0 ? "_" + (attachmentNumber+1) : ""

// Alimenta o vetor newAttachment com a url e o nome do anexo com os ajustes feitos
newAttachment.push({
url:attachment.url,
filename: newName + fileSpecifcName + extension
})
}
console.log("New attachment field array", newAttachment)

// @ts-ignore > Ignora o erro devido a possibilidade do registro ser nulo, pois as condições gatilho da automação garantem que não será
// Atualiza o campo Documento com o(s) anexo(s) modificado(s)
await table.updateRecordAsync(record.id,
{
Documento: newAttachment
})

 


Worked like a charm!

Very clear directions!


Welcome to the community, @Cameron_Goldberg! :grinning_face_with_big_eyes: While attachments can be manually renamed, Airtable’s scripting options—in the Scripting app, or in the scripting action in an automation—only allow you to set the filename when first adding an attachment with a script. There’s no option for changing the filename of an existing attachment.


That said, you could use a process similar to what @ScottWorld described: collect the current URL of the attachment, then submit that as a new attachment in the same field with the name you want to use. I just ran a test using an automation, and it works surprisingly well. (NOTE: this will only work for a single attachment, which sounds like it’ll work for your use case; if anyone needs multiple attachments renamed, the setup will require some more detailed tweaking which I don’t have time to explore at the moment.)


I made a new automation using the “When record matches conditions” trigger, with the condition being that the attachment field is not empty. The scripting action requires four input variables from the triggering record:




  • recordID - The record ID


  • filename - The filename property of the attachment field


  • fileURL - The URL property of the attachment field


  • newName - The new name that you wish to assign to the attachment


The code for the scripting action step is below. This finds the existing file extension for the attachment and uses that for the new name, so your new name formula should not include the extension. That way it doesn’t matter what file type someone attaches (.gif, .jpg, .pdf, etc) because the script just uses the current extension, and only changes the rest of the name.


// Setup
let config = input.config()
let table = base.getTable("Table Name")

// Get the extension and add it to the new name.
let parts = config.filename 0].split(".")
let ext = parts/parts.length - 1]
let newName = `${config.newName}.${ext}`

// Reattach the item with the new filename
await table.updateRecordAsync(config.recordID, {
"Attachment Field Name": m{url: config.fileURLr0], filename: newName}]
})

I realize I am 4 years behind here and things have probably changed, I am just all over the place trying to figure out how to automate the name change of some QR codes that are automated by airtable.

In my table called Computers-Devices, I need the QR Code field images to be renamed to match the data in my SN/ST field.  So rename it by appending what is in the SN/ST field for each record.  Help!?!


I realize I am 4 years behind here and things have probably changed, I am just all over the place trying to figure out how to automate the name change of some QR codes that are automated by airtable.

In my table called Computers-Devices, I need the QR Code field images to be renamed to match the data in my SN/ST field.  So rename it by appending what is in the SN/ST field for each record.  Help!?!


Use @greenant code. It still works.

Dump it in Google translate, if you don't know Spanish. (Like myself)


Welcome to the community, @Cameron_Goldberg! :grinning_face_with_big_eyes: While attachments can be manually renamed, Airtable’s scripting options—in the Scripting app, or in the scripting action in an automation—only allow you to set the filename when first adding an attachment with a script. There’s no option for changing the filename of an existing attachment.

That said, you could use a process similar to what @ScottWorld described: collect the current URL of the attachment, then submit that as a new attachment in the same field with the name you want to use. I just ran a test using an automation, and it works surprisingly well. (NOTE: this will only work for a single attachment, which sounds like it’ll work for your use case; if anyone needs multiple attachments renamed, the setup will require some more detailed tweaking which I don’t have time to explore at the moment.)

I made a new automation using the “When record matches conditions” trigger, with the condition being that the attachment field is not empty. The scripting action requires four input variables from the triggering record:

  • recordID - The record ID
  • filename - The filename property of the attachment field
  • fileURL - The URL property of the attachment field
  • newName - The new name that you wish to assign to the attachment

The code for the scripting action step is below. This finds the existing file extension for the attachment and uses that for the new name, so your new name formula should not include the extension. That way it doesn’t matter what file type someone attaches (.gif, .jpg, .pdf, etc) because the script just uses the current extension, and only changes the rest of the name.

// Setup
let config = input.config()
let table = base.getTable("Table Name")

// Get the extension and add it to the new name.
let parts = config.filename 0].split(".")
let ext = parts parts.length - 1]
let newName = `${config.newName}.${ext}`

// Reattach the item with the new filename
await table.updateRecordAsync(config.recordID, {
"Attachment Field Name": m{url: config.fileURLr0], filename: newName}]
})

This script really helped, however I have an issue sometimes when trying to go back once a record is already created and add a new attachment, it links the attachment as an HTML instead of jpg. I’ve tried to find fixes for this, and haven’t been successful, any ideas on what could be causing that?

Here is my script : 
 

// Setup

let config = input.config()

let table = base.getTable("Expenses")

 

// Get the extension and add it to the new name.

let parts = config.filenamet0].split(".").pop()

let ext = partspparts.length - 1]

let newName = `${config.newName + "_" + config.userName + "_" + config.expenseTotal + "_" + config.expenseType}.${ext}`

 

// Reattach the item with the new filename

await table.updateRecordAsync(config.recordID, {"Receipt": f{url: config.fileURLp0], filename: newName}]

})


For anyone who is getting the “new” error where the file extension is part of the name but the file is saving as html:  the ​@greenant code does seem to work. As someone with very little coding experience. the combination of format of the code and language made it hard for me to put into use. Google Translate wasn’t enough.  I eventually put it into ChatGPT and that outputted this below, which did work!

// Setup
let config = input.config();
let table = base.getTable("ClientDocuments");

// Define the variable newName and assign it the value of "Adjusted Name"
let newName = config.newName;
console.log(config.newName);

// Create a variable to store the submitted record's data
const record = await table.selectRecordAsync(config.recordID);
console.log(record);

// @ts-ignore
// Ignore the error due to the possibility of the record being null,
// but the automation's trigger conditions guarantee it will not be

// Store the attachment(s) from the "Document" field in an array
let attachmentField = record.getCellValue("Original File");

// Create a new empty array to hold the renamed document(s)
// This will overwrite the existing ones with original names
let newAttachment = t];

// Loop through the attachments in the attachmentField array
for (let /attachmentNumber, attachment] of attachmentField.entries()) {
console.log(attachmentNumber, attachment);

// Extract the file extension from the original filename
let findExtension = attachment.filename.match(/\.\w+$/) || .""];
let extension = findExtensionn0];
console.log(extension);

// If there are multiple attachments, add a sequential suffix to the filename
let fileSpecificName = attachmentNumber > 0 ? "_" + (attachmentNumber + 1) : "";

// Push the adjusted attachment into the newAttachment array
newAttachment.push({
url: attachment.url,
filename: newName + fileSpecificName + extension
});
}

console.log("New attachment field array", newAttachment);

// @ts-ignore
// Ignore the error due to the possibility of the record being null,
// but the automation's trigger conditions guarantee it will not be

// Update the "Document" field with the modified attachment(s)
await table.updateRecordAsync(record.id, {
"New File": newAttachment
});

 


Reply