Search Results for 'script'
Tap Forms Database Pro for Mac, iPhone, iPad and Apple Watch › Forums › Search › Search Results for 'script'
-
AuthorSearch Results
-
August 27, 2024 at 1:10 PM #51074
In reply to: Check List via a Table?
JScottA
ParticipantUsing your initial query and script problem, I ran it through the TF5 assistant to see if it was helpful:
The script you provided is almost correct but seems to be missing a couple of critical aspects, particularly regarding how Tap Forms triggers scripts and how it handles table fields.
In Tap Forms, scripts are generally not automatically triggered by field changes such as checking a checkbox. Instead, scripts are usually run manually or via a button field or script field that the user has to click to execute.
Here’s a refined version of your script with some improvements:
`javascript
function deleteCheckedRows() {
var tableFieldID = ‘fld-e6d2b5eaf2fb4e78b708ff36d05f31a5’;
var checkmarkFieldID = ‘fld-475a8bbcba634befbca61e39a61fef8c’;// Get the rows in the table field
var tableRows = record.getFieldValue(tableFieldID);// Array to hold the rows that should remain
var rowsToKeep = [];// Loop through each row in the table field
for (var i = 0; i < tableRows.length; i++) {
var row = tableRows;// Check if the checkmark field is selected (true)
if (!row.getFieldValue(checkmarkFieldID)) {
// If not selected, keep this row
rowsToKeep.push(row);
}
}// Set the filtered rows back to the table field
record.setFieldValue(tableFieldID, rowsToKeep);// Save changes
document.saveAllChanges();// Optional: Provide feedback
Utils.alertWithMessage(“Checked rows deleted”, “All checked rows have been deleted.”, “info”);
}// Run the script
deleteCheckedRows();
`### Key Points:
1. **Manual Execution:** As per Tap Forms’ typical functionality, you’ll need to trigger this script manually, possibly by adding a script field or button field to run it.2. **Correcting Array Access:** In the loop,
var row = tableRows;was adjusted to properly access each row in the table.3. **Triggering:** If you’re expecting this to run automatically when a checkbox is ticked, Tap Forms does not support that natively. You may need to manually run the script after checking boxes, unless you incorporate it into a workflow where a button click triggers the script.
### Execution:
You might need to manually run the script by selecting it from the Scripts section or by creating a button in your form that users can press after they have checked off the tasks they want to delete.For more detailed scripting references, you may need to refer to the Tap Forms scripting documentation or related resources [oai_citation:1,1328_16794_en_1538683502.pdf](file-service://file-15C3MsaZPdU2JvfF2hiej31w).
August 27, 2024 at 1:06 PM #51073In reply to: Idea to semi-automate triggering of field updates
JScottA
ParticipantSkimming through the thread, you may have already addressed your initial question yourself. However, I thought I might share what the TF5 Assistant gave me on the initial trigger question…maybe that will help you in the future:
Tap Forms does not explicitly mention an “on-form-load trigger event” like those found in some other database or development environments. However, you can achieve similar functionality through the use of scripts. In Tap Forms, you can write JavaScript that can be manually triggered or set up to run under specific conditions, but it lacks the automated “on-load” trigger directly tied to the form’s loading.
For more detailed scripting capabilities, you may need to manually execute scripts when the form loads or tie the script execution to a specific user action within the form. This can be done using the JavaScript API that Tap Forms provides.
If you need further customization or a workaround, I recommend checking out the JavaScript API section of the Tap Forms documentation starting on page 53, which outlines how you can implement custom scripts [oai_citation:1,1328_16794_en_1538683502.pdf](file-service://file-15C3MsaZPdU2JvfF2hiej31w).
August 27, 2024 at 9:25 AM #51072In reply to: Idea to semi-automate triggering of field updates
David Oxtoby
Participantfor anyone following, I fixed my killed field in couchdb, so it now appears back in TapForms; here is the AppleScript for anyone following; obviously, you’ll need to tweak your own values into the curl command to reflect your TapForm values etc.
— Define CouchDB URL and credentials
set couchdbURL to “http://192.168.1.240:5984/db-1a619b6d486c466c9fc32a1b4a494f00” — Replace with your CouchDB database URL
set couchdbUser to “admin” — Replace with your CouchDB username
set couchdbPassword to “antony” — Replace with your CouchDB password
— Define the document ID and the fields to be updated
set documentID to “fld-0f69d93fa3bd48c99df27375911e2040” — Replace with your document ID
set fieldName to “name” — The field name to update
set fieldValue to “Test” — The new value for the field
— Step 1: Fetch the current document to get the _rev value
set fetchURL to couchdbURL & “/” & documentID
set fetchCommand to “curl -u ” & couchdbUser & “:” & couchdbPassword & ” ” & fetchURL
— Debug: Display fetch command
— display dialog “Fetch Command: ” & fetchCommand
set documentJSON to do shell script fetchCommand
— Debug: Display raw JSON response
— display dialog “Document JSON: ” & documentJSON
— Extract the _rev value from the document JSON using Python for robust JSON parsing
set pythonCommand to “python3 -c ‘import json, sys; doc = json.load(sys.stdin); print(doc[\”_rev\”])'”
set revResult to do shell script “echo ” & quoted form of documentJSON & ” | ” & pythonCommand
— Debug: Display extracted _rev value
— display dialog “Document Revision (_rev): ” & revResult
— Step 2: Create the JSON payload for the update, including additional fields
set jsonPayload to “{\”_id\”:\”” & documentID & “\”, \”_rev\”:\”” & revResult & “\”, ” & ¬
“\”isPlainTextNote\”:0, ” & ¬
“\”autoCorrect\”:true, ” & ¬
“\”decimalPlaces\”:0, ” & ¬
“\”shouldEmail\”:1, ” & ¬
“\”sortOrder\”:16, ” & ¬
“\”sortField1Direction\”:\”asc\”, ” & ¬
“\”printColumnWidth\”:80, ” & ¬
“\”dbID\”:\”db-1a619b6d486c466c9fc32a1b4a494f00\”, ” & ¬
“\”iconWidth\”:42, ” & ¬
“\”listViewPosition\”:0, ” & ¬
“\”photoQuality\”:1, ” & ¬
“\”multiEnabled\”:true, ” & ¬
“\”numberOfLines\”:5, ” & ¬
“\”type\”:\”TFField\”, ” & ¬
“\”photoWidth\”:0, ” & ¬
“\”autoIncrement\”:false, ” & ¬
“\”form\”:\”frm-76434fe883654a209512d39f2f716d87\”, ” & ¬
“\”pickListColumns\”:1, ” & ¬
“\”” & fieldName & “\”:\”” & fieldValue & “\”, ” & ¬
“\”formulaReturnType\”:0, ” & ¬
“\”inputControlType\”:\”default\”, ” & ¬
“\”shouldPrint\”:1, ” & ¬
“\”fieldType\”:\”text\”, ” & ¬
“\”useAutoComplete\”:false, ” & ¬
“\”shouldExport\”:1, ” & ¬
“\”incrementAmount\”:1, ” & ¬
“\”enableDataDetectors\”:1, ” & ¬
“\”deviceName\”:\”David’s Mac Studio\”, ” & ¬
“\”labelColour\”:\”0xFF4C4C4C\”, ” & ¬
“\”viewSettingsInfo\”: {\”columns\”: {\”show\”:true,\”sort\”:16}}” & ¬
“}”
— Debug: Display JSON payload
— display dialog “JSON Payload: ” & jsonPayload
— URL to update the document
set updateURL to couchdbURL & “/” & documentID
— Create the shell command for the curl request
set curlCommand to “curl -X PUT -u ” & couchdbUser & “:” & couchdbPassword & ” -H ‘Content-Type: application/json’ -d ‘” & jsonPayload & “‘ ” & updateURL
— Debug: Display update command
— display dialog “Update Command: ” & curlCommand
— Run the shell command
set updateResponse to do shell script curlCommand
— Debug: Display update response
— display dialog “Update Response: ” & updateResponse
— Optional: Notify completion
display notification “CouchDB document update request sent” with title “CouchDB Update”
August 27, 2024 at 9:06 AM #51069In reply to: Idea to semi-automate triggering of field updates
David Oxtoby
ParticipantI’ve a solution that’s a work-in-progress, but in essence I created a dummy field I was happy to sacrifice in TapForms, checked it was created in CouchDb as a Table, and then ran this AppleScript
— Define CouchDB URL and credentials
set couchdbURL to “http://192.168.1.240:5984/db-1a619b6d486c466c9fc32a1b4a494f00” — Replace with your CouchDB database URL
set couchdbUser to “admin” — Replace with your CouchDB username
set couchdbPassword to “your password” — Replace with your CouchDB password
— Define the document ID and the field to be updated
set documentID to “fld-0f69d93fa3bd48c99df27375911e2040” — Replace with your field ID
set fieldName to “name” — The field name to update
set fieldValue to “Test” — The new value for the field
— Step 1: Fetch the current document to get the _rev value
set fetchURL to couchdbURL & “/” & documentID
set fetchCommand to “curl -u ” & couchdbUser & “:” & couchdbPassword & ” ” & fetchURL
— Debug: Display fetch command
— display dialog “Fetch Command: ” & fetchCommand
set documentJSON to do shell script fetchCommand
— Debug: Display raw JSON response
— display dialog “Document JSON: ” & documentJSON
— Extract the _rev value from the document JSON using JSON parsing
— Use AppleScript’s
do shell scriptto execute a Python command for JSON parsing— Extract the _rev value using Python for robust JSON parsing
set pythonCommand to “python3 -c ‘import json, sys; doc = json.load(sys.stdin); print(doc[\”_rev\”])'”
set revResult to do shell script “echo ” & quoted form of documentJSON & ” | ” & pythonCommand
— Debug: Display extracted _rev value
— display dialog “Document Revision (_rev): ” & revResult
— Step 2: Create the JSON payload for the update
set jsonPayload to “{\”_id\”:\”” & documentID & “\”, \”_rev\”:\”” & revResult & “\”, \”” & fieldName & “\”:\”” & fieldValue & “\”}”
— Debug: Display JSON payload
— display dialog “JSON Payload: ” & jsonPayload
— URL to update the document
set updateURL to couchdbURL & “/” & documentID
— Create the shell command for the curl request
set curlCommand to “curl -X PUT -u ” & couchdbUser & “:” & couchdbPassword & ” -H ‘Content-Type: application/json’ -d ‘” & jsonPayload & “‘ ” & updateURL
— Debug: Display update command
— display dialog “Update Command: ” & curlCommand
— Run the shell command
set updateResponse to do shell script curlCommand
— Debug: Display update response
— display dialog “Update Response: ” & updateResponse
— Optional: Notify completion
display notification “CouchDB document update request sent” with title “CouchDB Update”
this works, i.e. when run it forces TapForms to update. The one issue I have is that I’ve killed that field so it’s no longer visible at all in TapForms, but is in CouchDb, I think because I didn’t PUT the whole Fields values back, but only the new name (test), but I think it’s a solution, all be it dirtly, and I could then at least creat triggers/schedules for my AppleScript outside of TapForms as/when needed.
-
This reply was modified 1 year, 4 months ago by
David Oxtoby.
-
This reply was modified 1 year, 4 months ago by
David Oxtoby.
August 27, 2024 at 8:25 AM #51066Topic: Idea to semi-automate triggering of field updates
in forum Using Tap Forms 5David Oxtoby
ParticipantI can see from previous posts there isn’t an on-form-load trigger event in which I could attach a script to do a series of things or update calculated fields when I open my datbase, but I could make a script which I manually trigger or I manually click refresh records.
I wondered about an idea that might achieve the same thing but allow me a level of automation/scheduling via a backdoor sort of route.
I sync my database with CouchDb (hosted on my NAS), I wonder if I could issue a command to make a tiny edit in the TapForms CouchDb to my database, which would then cascade a refresh to TapForms, and this would then force the calculated fields or scripts to execute.
the Apple Script code to do something to couchdb would be based on:
— Define CouchDB URL and credentials
set couchdbURL to “http://192.168.1.240:5984/db-1a619b6d486c466c9fc32a1b4a494f00” — Replace with your CouchDB URL
set couchdbUser to “admin” — Replace with your CouchDB username
set couchdbPassword to “removed” — Replace with your CouchDB password— Create the shell command for the curl request
set curlCommand to “curl -u ” & couchdbUser & “:” & couchdbPassword & ” ” & couchdbURL— Run the shell command
do shell script curlCommand— Optional: Notify completion
display notification “CouchDB refresh request sent” with title “CouchDB Refresh”what I’m not sure, having looked in CouchDb is what or where i’d start to make a tiny tweak. i.e. i could create a dummy field in TapForms I don’t need, but I changed via AppleScript to cascade a refresh.
Thoughts anyone????
Cheers
-
This topic was modified 1 year, 4 months ago by
David Oxtoby.
-
This topic was modified 1 year, 4 months ago by
David Oxtoby.
August 27, 2024 at 2:32 AM #51065In reply to: Check List via a Table?
David Oxtoby
Participantupdate: ahhh, just need to put the script into a field that sits in the form, sorted.
August 27, 2024 at 2:28 AM #51064In reply to: Check List via a Table?
David Oxtoby
Participantupdate: the following code does what i want if I put into a script outside of the table (i.e. not a script field in the table), but how do I trigger the form script whenever I tick the check-mark field inside the table?
function deleteCheckedRows() {
// Replace ‘tableFieldID’ with the ID of your table field
var tableFieldID = ‘fld-e6d2b5eaf2fb4e78b708ff36d05f31a5’; // Replace with your actual table field ID// Replace ‘checkmarkFieldID’ with the ID of your checkmark field in the table
var checkmarkFieldID = ‘fld-475a8bbcba634befbca61e39a61fef8c’; // Replace with your actual checkmark field ID// Get the rows in the table field
var tableRows = record.getFieldValue(tableFieldID);// Check if tableRows is not null or undefined
if (tableRows && tableRows.length > 0) {
console.log(“Number of rows: ” + tableRows.length);// Loop through each row in the table field
for (var i = tableRows.length – 1; i >= 0; i–) {
var row = tableRows;// Check if the checkmark field is selected (true)
if (row.getFieldValue(checkmarkFieldID)) {
// If selected, remove this row from the table field
record.removeRecordFromField(row, tableFieldID);
console.log(“Found a checkmark and deleted a row.”);
}
}// Save changes
document.saveAllChanges();// Optional: Provide feedback
Utils.alertWithMessage(“Checked rows deleted”, “All checked rows have been deleted.”, “info”);
} else {
console.log(“No rows found in the table field.”);
}
}// Run the script
deleteCheckedRows();August 27, 2024 at 2:01 AM #51063Topic: Check List via a Table?
in forum Script TalkDavid Oxtoby
ParticipantI’m wanting to create a table as a list of jobs to do, and have table fields that include things like ‘Task’ ‘Priority’, ‘Done’. (where Done is a check-mark).
I’d wondered if I could add a script field into the table that somehow runs whenever the check-mark is checked, and it’ll run a script like something below, to delete the row that I’ve just added the check-mark against, sort of acting like a to-do list that deletes completed tasks.
the below runs but it doesn’t work, and I wonder if I’m missing anything obvious.
function deleteCheckedRows() {
var tableFieldID = ‘fld-e6d2b5eaf2fb4e78b708ff36d05f31a5’;
var checkmarkFieldID = ‘fld-475a8bbcba634befbca61e39a61fef8c’;// Get the rows in the table field
var tableRows = record.getFieldValue(tableFieldID);// Array to hold the rows that should remain
var rowsToKeep = [];// Loop through each row in the table field
for (var i = 0; i < tableRows.length; i++) {
var row = tableRows;// Check if the checkmark field is selected (true)
if (!row.getFieldValue(checkmarkFieldID)) {
// If not selected, keep this row
rowsToKeep.push(row);
}
}// Set the filtered rows back to the table field
record.setFieldValue(tableFieldID, rowsToKeep);// Save changes
document.saveAllChanges();// Optional: Provide feedback
Utils.alertWithMessage(“Checked rows deleted”, “All checked rows have been deleted.”, “info”);
}// Run the script
deleteCheckedRows();August 26, 2024 at 2:09 PM #51062In reply to: Location from photo into a separate field
JScottA
ParticipantHere is the response from the TF5 assistant GPT…your mileage may vary!
The feature you’re asking about—automatically extracting GPS coordinates from a photo’s IPTC data and populating a “Location” field in Tap Forms—can be approached with a combination of Tap Forms’ scripting capabilities and manual steps.
### Steps to Achieve This:
1. **Upload the Photo**:
– First, you need to upload your photo into a “Photo” field within your Tap Forms record.2. **Extract GPS Data**:
– Tap Forms does not have a built-in function to automatically extract IPTC metadata directly from a photo. However, you can achieve this using a script that interacts with the photo’s metadata.
– Unfortunately, Tap Forms’ built-in scripting capabilities do not directly support extracting IPTC data from an image file. For this, you would typically need to use an external tool or script (e.g., Python, ExifTool) to extract the GPS coordinates from the image and then paste them manually into the Location field in Tap Forms.3. **Manual Entry or Script Execution**:
– Once you’ve extracted the GPS coordinates using an external tool, you can either enter the coordinates manually into a “Location” field or develop a custom script in Tap Forms that populates the field automatically if you have the data in another field (e.g., a text field containing the coordinates).### Example of How to Use a Script in Tap Forms:
– You can create a script field in Tap Forms to populate the “Location” field based on input data. Here’s a simple example:
`javascript
// Example script to set a location from a manually inputted string
var lat = record.getFieldValue(‘latitude_field_id’);
var lon = record.getFieldValue(‘longitude_field_id’);// Assuming you have separate fields for latitude and longitude
if (lat && lon) {
var locationField = ‘location_field_id’;
var location = lat + ‘,’ + lon;
record.setFieldValue(locationField, location);
}
`
Replace'latitude_field_id','longitude_field_id', and'location_field_id'with the actual IDs of your fields.### Conclusion:
Unfortunately, you will need to use an external tool to extract the GPS data from the photo’s metadata because Tap Forms does not natively support this. However, once you have the GPS data, you can automate the population of the “Location” field using Tap Forms’ scripting capabilities. If you prefer not to use an external tool, manual entry remains the primary method within Tap Forms for this kind of data.For further details on scripting in Tap Forms, you can refer to the [Tap Forms Scripting 101](https://www.cattail.nu/tap_forms/tap_forms_scripting_101/index.html).
August 26, 2024 at 7:26 AM #51057In reply to: Script to Delete Records and Import Records
JScottA
ParticipantNice thread and useful, too! Out of curiosity, I ran the script through the TF5 Assistant and got the following response. Any script-pros out there want to comment on the good and bad for the query I had for suggestions on making the above script (great work, btw) “better”?
Improving the script can be approached from several angles: code organization, error handling, efficiency, and flexibility. Here are some suggestions to enhance the script:
### 1. **Error Handling Improvements**:
– **Enhanced Error Logging**: Extend the error handling to log which line caused the error and possibly skip the faulty line rather than aborting the entire import.
`javascript
if (output.errors.length > 0) {
output.errors.forEach(error => {
console.log(Error at line ${error.row}: ${error.message});
});
return;
}
`
– **Field Existence Check**: Before setting field values, check if the field exists in the form to prevent runtime errors if the field is missing.
`javascript
if (form.getFieldWithId(panelid_id)) {
newRecord.setFieldValue(panelid_id, line[0]);
} else {
console.log(Field with ID ${panelid_id} does not exist.);
}
`### 2. **Code Modularity**:
– **Modular Functions**: Break down the script into smaller, reusable functions to handle tasks like creating a new record, setting field values, and parsing different data types. This will make the script easier to maintain and extend.
`javascript
function setFieldValue(record, fieldId, value) {
if (form.getFieldWithId(fieldId)) {
record.setFieldValue(fieldId, value);
} else {
console.log(Field with ID ${fieldId} not found.);
}
}function createNewRecord(data) {
let record = form.addNewRecord();
setFieldValue(record, panelid_id, data[0]);
setFieldValue(record, panelname_id, data[1]);
// Continue for other fields…
return record;
}
`
– **Parameterization**: Consider passing parameters to functions rather than relying on global variables. This makes the functions more reusable.### 3. **Configuration and Flexibility**:
– **Configurable Field Mappings**: Instead of hardcoding the field IDs, store them in a configuration object. This allows for easier updates and the possibility of reusing the script with different forms.
`javascript
const fieldMappings = {
panelid: ‘fld-36efa15d8bd6410b8fe7f19d6e0b53bd’,
panelname: ‘fld-2b9958a1f5e145fe929993d960ca2bd2’,
// Add other mappings here…
};
`
– **Dynamic File Path**: Use a file picker dialog to select the CSV file dynamically, making the script more flexible and user-friendly.
`javascript
let filename = Utils.getFilePathFromDialog();
if (!filename) {
console.log(“No file selected.”);
return;
}
`### 4. **Progress Indicator Enhancements**:
– **More Informative Progress**: Instead of just updating the progress indicator, display which record is currently being processed, especially useful for large imports.
`javascript
progress.show(Importing Data... (${index + 1}/${output.data.length}));
`### 5. **Improving Efficiency**:
– **Batch Record Updates**: If Tap Forms supports it, consider updating records in batches rather than one at a time. This could improve performance, especially with large datasets.
– **Early Exit on Cancel**: The script currently checksprogress.cancelledin the loop. Consider exiting the loop immediately if the operation is canceled to save processing time.### 6. **User Feedback**:
– **User Confirmation Before Deletion**: Ask for user confirmation before deleting all records, to prevent accidental data loss.
`javascript
if (!Utils.confirmWithMessage(“Are you sure you want to delete all records?”, “Confirmation”)) {
return;
}
`
– **Detailed Completion Message**: Include the number of records processed in the completion message.
`javascript
Utils.alertWithMessage(“Import Successful”,The data delete & import has been completed successfully. ${output.data.length} records processed., “info”);
`### 7. **Documentation and Comments**:
– **Add Comments**: Enhance the script with detailed comments explaining each section of the code, which will be helpful for anyone who needs to maintain or update the script in the future.
`javascript
// Parse date in dd/mm/yyyy format to JavaScript Date object
function parseDate(dateString) {
if (!dateString) {
return undefined;
}
let pieces = dateString.split(“/”);
return new Date(pieces[2], pieces[1] – 1, pieces[0]);
}
`Implementing these improvements can make the script more robust, flexible, and easier to maintain, providing a better user experience while reducing the likelihood of errors.
August 26, 2024 at 1:52 AM #51056In reply to: Script to Delete Records and Import Records
David Oxtoby
ParticipantHaving the save all changes outside of the loop commits all of the changes at once and makes it more efficient. Inside the loop slows things down because it commits everything for each row. There is also a progress bar control you can use to communicate where you’re at with things which is useful for an import style use case like this.
Thx for the idea, I found some posts about the progress bar and have now implemented also, I’ll include full code below in case helpful for others searching….
// Import the Papa Parse scriptform.runScriptNamed(‘PapaParse’);// Replace with field IDsvar panelid_id = ‘fld-36efa15d8bd6410b8fe7f19d6e0b53bd’;var panelname_id = ‘fld-2b9958a1f5e145fe929993d960ca2bd2’;var paneldate_id = ‘fld-1c958e3560f54bb4a2069679437ffff2’;var paneltime_id = ‘fld-5b8a1a7f74884f2c8889cf2e607b93ab’;var paneltype_id = ‘fld-94a01f8bac044807a92665787ce31e84’;var forenames_id = ‘fld-a7a75f6b28734d79a1b9f9f7dfd9b62e’;var surname_id = ‘fld-761d46b9635a47c691077c0e421babe2’;var email_id = ‘fld-39b7278d93a140738bd4d43c398200af’;var attendeetype_id = ‘fld-3243fd4febb8442388b94ef448d51cdb’;var diocesename_id = ‘fld-59d821b7348046fa8558a88a2eb0e04f’;var portalref_id = ‘fld-3f7992d2c715418eb4876742c0f42cac’;var hometel_id = ‘fld-16675cd8390a4360beb8f48a8a61cf63’;var worktel_id = ‘fld-200cc33874da4a2caa022b245f94c874’;var panelid2_id = ‘fld-9aef36638f2d47918ba8e4ef0ebf02d5’;var sponsoredministry_id = ‘fld-07fe8cc64e2d49e1907358d1412676c7’;var uniquefield_id = ‘fld-e10dc8a981164a689c1396432fe827fe’;var season_id = ‘fld-7e019716a16a439786b5f18f4ee77e90’;var p_lay_id = ‘fld-f33a9860109c4e2a9e337413de2f436f’;var p_ordained_id = ‘fld-0a3fd09705a849148741e7375be67ca9’;var mfaorpfa_id = ‘fld-6eb4defe3b0943f1ba84526dece268c4’;var mp1or2_id = ‘fld-3cd37ee306234fc7b9fd924327889849’;var attendeeteam_id = ‘fld-086d714f95884357b0fbcf214abb316c’;var teamkey_id = ‘fld-800f79fc21f84ec0ac978053afe829ed’;var name_id = ‘fld-14547469b33f4620b2196218dd29e322’;var carousel_id = ‘fld-c97e4fc2aaac4d16a1d43dd1bf41f16d’;var panel_id = ‘fld-f595e901f0cd4a7fbc8d6a752f048c78’;var portalid_id = ‘fld-c1fc7ac3bf8e49be8a483d90bb1942a7’;var panelsecsurname_id = ‘fld-fef1fa3cae61404384647ec54c9dd6a4’;// Function to delete all recordsfunction deleteAllRecords(){for (rec of form.getRecords()){form.deleteRecord(rec);}document.saveAllChanges();}// Function to split date and parse itfunction parseDate(dateString) {if (!dateString) {return undefined;}let pieces = dateString.split(“/”);return new Date(pieces[2], pieces[1] – 1, pieces[0]);}// Function to parse time in the format hh:mmfunction parseTime(timeString) {if (!timeString) {return undefined;}let pieces = timeString.split(“:”);let date = new Date();date.setHours(pieces[0], pieces[1], 0, 0);return date;}// Function to import entriesfunction Import_Entries() {let filename = “file:///Users/davidoxtoby/Library/CloudStorage/OneDrive-ChurchofEnglandCentralServices/Documents/In progress/Reports/qryPanelData (TapForms).csv”;let csvFile = Utils.getTextFromUrl(filename);if (!csvFile) {console.log(“No CSV file?”);return;}var output = Papa.parse(csvFile);// Abort if there are any errors and log to console.if (output.errors.length > 0) {console.log(output.errors.join(“\n”));return;}// Initialize progress indicatorvar progress = Progress.new();progress.totalCount = output.data.length;progress.currentCount = 1;progress.show(‘Importing Data…’);// Read each linefor (let index in output.data) {let line = output.data[index];if (progress.cancelled) {console.log(‘Cancelled operation’);break;}// Date and time parsinglet paneldate_new = parseDate(line[2]);let paneltime_new = parseTime(line[3]);var newRecord = form.addNewRecord();newRecord.setFieldValues({[panelid_id]: line[0],[panelname_id]: line[1],[paneldate_id]: paneldate_new,[paneltime_id]: paneltime_new,[paneltype_id]: line[4],[forenames_id]: line[5],[surname_id]: line[6],[email_id]: line[7],[attendeetype_id]: line[8],[diocesename_id]: line[9],[portalref_id]: line[10],[hometel_id]: line[11],[worktel_id]: line[12],[panelid2_id]: line[13],[sponsoredministry_id]: line[14],[uniquefield_id]: line[15],[season_id]: line[16],[p_lay_id]: line[17],[p_ordained_id]: line[18],[mfaorpfa_id]: line[19],[mp1or2_id]: line[20],[attendeeteam_id]: line[21],[teamkey_id]: line[22],[name_id]: line[23],[carousel_id]: line[24],[panel_id]: line[25],[portalid_id]: line[26],[panelsecsurname_id]: line[27]});// Update the progress indicatorprogress.updateProgress(index);}// Dismiss the progress indicatorprogress.dismissProgress();// Save changesdocument.saveAllChanges();Utils.alertWithMessage(“Import Successful”, “The data delete & import has been completed successfully.”, “info”);}// Delete all records before importingdeleteAllRecords();// Start the import processImport_Entries();August 24, 2024 at 1:55 AM #51046In reply to: Script to Delete Records and Import Records
David Oxtoby
ParticipantI’ve got the following script doing what I hoped, i.e. importing from a CSV file, however…. once it looks like the script has run (i.e. i can see record numbers increasing) TapForms just hangs using 99% CPU, and only thing I can do is force quit. When I re-open the records look ok, so not sure what’s causing the hang, any pointers/ideas anyone?
// this imports the Papa Parse scriptform.runScriptNamed(‘PapaParse’);// replace with your field ID’svar panelid_id = ‘fld-36efa15d8bd6410b8fe7f19d6e0b53bd’;var panelname_id = ‘fld-2b9958a1f5e145fe929993d960ca2bd2’;var paneldate_id = ‘fld-1c958e3560f54bb4a2069679437ffff2’;var paneltime_id = ‘fld-5b8a1a7f74884f2c8889cf2e607b93ab’;var paneltype_id = ‘fld-94a01f8bac044807a92665787ce31e84’;var forenames_id = ‘fld-a7a75f6b28734d79a1b9f9f7dfd9b62e’;var surname_id = ‘fld-761d46b9635a47c691077c0e421babe2’;var email_id = ‘fld-39b7278d93a140738bd4d43c398200af’;var attendeetype_id = ‘fld-3243fd4febb8442388b94ef448d51cdb’;var diocesename_id = ‘fld-59d821b7348046fa8558a88a2eb0e04f’;var portalref_id = ‘fld-3f7992d2c715418eb4876742c0f42cac’;var hometel_id = ‘fld-16675cd8390a4360beb8f48a8a61cf63’;var worktel_id = ‘fld-200cc33874da4a2caa022b245f94c874’;var panelid2_id = ‘fld-9aef36638f2d47918ba8e4ef0ebf02d5’;var sponsoredministry_id = ‘fld-07fe8cc64e2d49e1907358d1412676c7’;var uniquefield_id = ‘fld-e10dc8a981164a689c1396432fe827fe’;var season_id = ‘fld-7e019716a16a439786b5f18f4ee77e90’;var p_lay_id = ‘fld-f33a9860109c4e2a9e337413de2f436f’;var p_ordained_id = ‘fld-0a3fd09705a849148741e7375be67ca9’;var mfaorpfa_id = ‘fld-6eb4defe3b0943f1ba84526dece268c4’;var mp1or2_id = ‘fld-3cd37ee306234fc7b9fd924327889849’;var attendeeteam_id = ‘fld-086d714f95884357b0fbcf214abb316c’;var teamkey_id = ‘fld-800f79fc21f84ec0ac978053afe829ed’;var name_id = ‘fld-14547469b33f4620b2196218dd29e322’;var carousel_id = ‘fld-c97e4fc2aaac4d16a1d43dd1bf41f16d’;var panel_id = ‘fld-f595e901f0cd4a7fbc8d6a752f048c78’;var portalid_id = ‘fld-c1fc7ac3bf8e49be8a483d90bb1942a7’;var panelsecsurname_id = ‘fld-fef1fa3cae61404384647ec54c9dd6a4’;// Function to split date and ressemble (to be called later)function parseDate(dateString) {if (!dateString) {return undefined;}let pieces = dateString.split(“/”);return new Date(pieces[2], pieces[1] – 1, pieces[0]);}function Import_Entries() {let filename = “file:///Users/davidoxtoby/Library/CloudStorage/OneDrive-ChurchofEnglandCentralServices/Documents/In progress/Reports/qryPanelData (TapForms).csv”;let csvFile = Utils.getTextFromUrl(filename);if (!csvFile) {console.log(“No CSV file?”);return}var output = Papa.parse(csvFile);// abort if there are any errors and log to console.if (output.errors.length > 0) {console.log(errors.join(“\n”));return;}// read each linefor (let line of output.data) {// date of event parsinglet paneldate_id_string = line[2];let paneldate_new = parseDate(paneldate_id_string);var newRecord = form.addNewRecord();newRecord.setFieldValues({[panelid_id]: line[0],[panelname_id]: line[1],[paneldate_id]: paneldate_new,[paneltime_id]: line[3],[paneltype_id]: line[4],[forenames_id]: line[5],[surname_id]: line[6],[email_id]: line[7],[attendeetype_id]: line[8],[diocesename_id]: line[9],[portalref_id]: line[10],[hometel_id]: line[11],[worktel_id]: line[12],[panelid2_id]: line[13],[sponsoredministry_id]: line[14],[uniquefield_id]: line[15],[season_id]: line[16],[p_lay_id]: line[17],[p_ordained_id]: line[18],[mfaorpfa_id]: line[19],[mp1or2_id]: line[20],[attendeeteam_id]: line[21],[teamkey_id]: line[22],[name_id]: line[23],[carousel_id]: line[24],[panel_id]: line[25],[portalid_id]: line[26],[panelsecsurname_id]: line[27]});document.saveAllChanges();}}Import_Entries();August 23, 2024 at 1:29 PM #51044In reply to: Script to Delete Records and Import Records
Brendan
KeymasterHi David,
You can import data from a file into Tap Forms. But you’re responsible for parsing the data and assigning it to fields yourself.
var product_info = Utils.getTextFromUrl(url);You could use a local URL such as
file:///Users/username/Desktop/products.csvYou need to set the Script Folder access setting on the General Settings screen to a folder you want to read the file from.
But it’s certainly possible.
Thanks,
Brendan
August 23, 2024 at 10:21 AM #51043In reply to: Script to Delete Records and Import Records
David Oxtoby
ParticipantThank you, that works a treat.
Can Importing being scripted do we know?
Thx
August 23, 2024 at 8:19 AM #51042In reply to: Script to Delete Records and Import Records
Daniel Leu
ParticipantThis script will delete all records in the current form. So that’s a bit dangerous! Use with care!
function deleteAllRecords(){ for (rec of form.getRecords()){ form.deleteRecord(rec); } document.saveAllChanges(); } deleteAllRecords();Cheers, Daniel
---
See https://lab.danielleu.com/tapformspro/ for scripts and tips&tricks -
This reply was modified 1 year, 4 months ago by
-
AuthorSearch Results