Help

Re: Code snipet for moving records within tables

998 0
cancel
Showing results for 
Search instead for 
Did you mean: 
snik
4 - Data Explorer
4 - Data Explorer

Hello! I'm trying to create a button in a table that when I press it, moves the whole record to another table within the same base and, AFTER THAT, deletes the record from the original base. I'm using an API Token. Also, both tables have exactly the same columns, in the same order.

However, I'm stuck with how to retrieve the record ID of the row where the button pressed is.

Could someone help out with the script? This is what I have so far:

 

// Airtable's API token and base information
const API_TOKEN = 'aaaaaaaaaaaaaaaaaaaaaaaa';
const BASE_ID = 'appaaaaaaaaaaaaaaa';
const SOURCE_TABLE_NAME = 'Table1';
const DESTINATION_TABLE_NAME = 'Table2';

// Get the current record ID using input.recordAsync
input.recordAsync('Select a record to move and delete').then((record) => {
  const recordId = record.id;
  moveAndDeleteRecord(recordId);
});

// Function to move and delete a record
async function moveAndDeleteRecord(recordId) {
  try {
    // Step 1: Get the record data
    const getRecordResponse = await fetch(`https://api.airtable.com/v0/${BASE_ID}/${SOURCE_TABLE_NAME}/${recordId}`, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${API_TOKEN}`,
      },
    });

    const recordData = await getRecordResponse.json();

    // Step 2: Create a new record in the destination table
    await fetch(`https://api.airtable.com/v0/${BASE_ID}/${DESTINATION_TABLE_NAME}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${API_TOKEN}`,
      },
      body: JSON.stringify({ fields: recordData.fields }),
    });

    // Step 3: Delete the record from the source table
    await fetch(`https://api.airtable.com/v0/${BASE_ID}/${SOURCE_TABLE_NAME}/${recordId}`, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${API_TOKEN}`,
      },
    });

    console.log('Record moved and deleted successfully');
  } catch (error) {
    console.error('Error moving and deleting record:', error);
  }

 

 

 

 

4 Replies 4
Andy_Lin1
9 - Sun
9 - Sun

If you're running the script via a button/extension, the functions available to you are a bit different:

 

const sourceTable = base.getTable('Table1');
const destinationTable = base.getTable('Table2');
const fields = sourceTable.fields.map(field => field.name);

input.recordAsync('Select a record to move and delete', sourceTable).then((record) => {
  moveAndDeleteRecord(record);
}); // need to specify record source, e.g. table or view

async function moveAndDeleteRecord(record) {
  try {
    let newRecord = {};
    fields.forEach(field => {
      newRecord[field] = record.getCellValue(field);
    });

    await destinationTable.createRecordAsync(newRecord);
    await sourceTable.deleteRecordAsync(record.id);
    console.log('Record moved and deleted successfully');
  } catch (error) {
    console.error('Error moving and deleting record:', error);
  }
}

 

Note: I haven't tested this and I'm less caffeinated than usual.

EDIT: Forgot to mention that when run via a button, the input.recordAsync prompt is skipped and the record the button belongs to is automatically used.
EDIT: Knew I made a mistake in the code.

Thank you very much! I didn't realize I should be using a different approach. I understand what you are doing with the code, but I can't seem to make it work on my baseI'm still learning how to use JavaScript.... 😞

JavaScriptAnd I don't know what may be wrong. Sorry, but I'm still learning how to use JavaScript.

Ah, I'm afraid I'm not much help then – all of my JS knowledge is from StackOverflow! 

For troubleshooting, the Scripting Extension/Block provides a console on the side to help with troubleshooting. The API/function behaviours are consistent between the extension and button (the button references a script, after all), so if you have it solved in the extension, it should work when run via a button. (Automations are another thing, but @kuovonne has written a guide about it, though I can't find a post where she linked to it  at the moment.)

My Kuovonne's Guide to Scripting in Airtable has a some info. My Kuovonne's Guide to Airtable is useful for non-scripting concepts. Both are published in my Coda profile.

Where did you get the code in your original post? This script looks like it has a weird mix of code for the Web API and code for scripting. If it was generated by AI, this article has my thoughts about Airtable scripts generated by AI.

Your use case (moving a data from one table to another table) on a button press should be easy for someone experienced with Airtable scripting, but would have a high learning curve for someone new to Airtable scripting and new to JavaScript.