Search Results for 'form.getRecords'
Tap Forms Database Pro for Mac, iPhone, iPad and Apple Watch › Forums › Search › Search Results for 'form.getRecords'
-
AuthorSearch Results
-
October 14, 2025 at 12:57 PM #53071
In reply to: How do I make a Check Mark Script Reset
David White
ParticipantOh… so close. I made the change: myForm.getRecords()… to: myForm.fetchRecords().
It stopped the Error Message, and when i clicked on the script it even unchecked one of my two check boxes. It unchecked: Day 2. But not: Day 1.
I will copy and paste here my script. Hope it helps make sense of it. In the script… First Field ID is Day 1. Second Field ID is Day 2. ( Only Day 2 checkbox resets ). My script below.
function uncheckRecords() {
// get the ID of the form you want to get the records from
var myForm = document.getFormNamed(‘Reset Check’);// get the ID of the checkbox field
var checkMarkField = ‘fld-f9318c6c66944131b69e29e75ab996db’;
var checkMarkField = ‘fld-3adc2a737f9f468b8bb6be8327c9139d’;// get the records from that form
var records = myForm.fetchRecords();// iterate through all records and set the charkMarkField to unchecked
for (var index = 0, count = records.length; index < count; index++){
// pull single record from array:
var theRecord = records[index];
// change field value for that record
theRecord.setFieldValue(checkMarkField, 0, false);
document.saveAllChanges();
}}
uncheckRecords();
-
This reply was modified 1 week, 5 days ago by
David White.
October 13, 2025 at 9:57 AM #53069In reply to: How do I make a Check Mark Script Reset
David White
ParticipantHello Shane and Brendan.
First I want to thank you both for your help.
I got scared I was going to mess up my CWL WARs Form … so I made a practice form that does kinda the same thing.
My practice Form is called: Reset Check. And I made only two checkboxes name: Day 1 and Day 2.
I put your Script in and where it says:
Var myForm = document.getFormNamed( ‘Reset Check’);As you can see I put: Reset Check.
I put in the IDs For: Day 1 and Day 2.
Everything seems to work … except I get this message that pops up:
ERROR
TypeError: myForm.getRecords is not a function. ( In ‘myForm.getRecords(); ‘myForm.getRecords’ is undefined), line:(null)I have no idea what that means. I was hoping it would work. I don’t know what to do to fix that.
Hoping you might have a trick up your sleeve that can make this script work.
Note: As I mentioned in the beginning… I only use IOS iPhone and iPad. I don’t have a Max Lap Top. Hoping it doesn’t matter. I am using Tap Forms Pro app i purchased. Thats why i chose this Forum. If i’m not suppose to be here… let me know. I will post my questions where i’m told to go.
Thanks.
God Bless.October 11, 2025 at 1:15 PM #53065In reply to: How do I make a Check Mark Script Reset
Shane
ParticipantThat’s a difficult thing to easily explain in layperson’s terms because it requires explaining a programming language. I”m new to scripting in TapForms, but have some experience with Javascript via web programming.
You need to create a script field which gets run when the form is viewed (I believe). In the script, it would have to do the following:
function uncheckRecords() { // get the ID of the form you want to get the records from var myForm = document.getFormNamed('CWL WARS'); // get the ID of the checkbox field var checkMarkField = 'fld-11d1cd0f0dc64bc389c3298076f0b9c8'; // get the records from that form var records = myForm.getRecords(); // iterate through all records and set the charkMarkField to unchecked for (var index = 0, count = records.length; index < count; index++){ // pull single record from array: var theRecord = records[index]; // change field value for that record theRecord.setFieldValue(checkMarkField, 0, false); document.saveAllChanges(); } } uncheckRecords();So this is how I see the code going in theory, but I haven’t tested it. I’m assuming that a check mark field would result in 0 (unchecked) and 1 (checked) just like a form would in Javascript but haven’t verified it in Tapforms. There are some other changes I’d make to this code to make it more efficient (such as an if then conditional to only change the records that are already checked) but for simplicity purposes I kept it this way.
Good luck.
April 8, 2025 at 11:24 AM #51810In reply to: Max of field (per Month, which is selected))
Daniel Leu
ParticipantThat’s an interesting project….
Following function should return the next track number you’re looking for. To keep the function generic, it returns an integer. You need to set the ids of the three different fields (date_id, track_number_id and track_id_id).
function getNextTrackNumber(){ const date_id = 'fld-xxx'; const track_number_id = 'fld-xxx'; const track_id_id = 'fld-xxx'; // get date and month from current record const date = new Date(record.getFieldValue(date_id)); const month = date.getMonth()+1; const year = date.getFullYear(); // filter records to match year/month of current record let recs = form.getRecords(); let trackNumbers = [0]; // initialize array recs.forEach((el) => { const thisDate = new Date(el.getFieldValue(date_id)); const thisMonth = thisDate.getMonth()+1; const thisYear = thisDate.getFullYear(); if (month == thisMonth && year == thisYear){ let trackNumber = parseInt(el.getFieldValue(track_number_id)); if (!isNaN(trackNumber)) trackNumbers.push(trackNumber); } }) console.log(JSON.stringify(trackNumbers, "",4)) // get max value const maxTrackNumber = Math.max(...trackNumbers); const nextTrackNumber = maxTrackNumber + 1; console.log("nextTrackNumber: " + nextTrackNumber); return nextTrackNumber; }Attached is my test form. It contains two scripts, one to set the track number field and the other for the track id field.
The track number is automatically set to “01” when no entry is available, otherwise to the next value. You can overwrite this. The track id is set based on the date and the track number. Whenever you update one or the other, it’s updated as well.
Happy biking and tracking :-)
Attachments:
You must be logged in to view attached files.Cheers, Daniel
---
See https://lab.danielleu.com/tapformspro/ for scripts and tips&tricksFebruary 21, 2025 at 10:00 AM #51653In reply to: calendar feature
JScottA
ParticipantUsing the custom GPT, Tap Forms 5 Assistant (unofficial), I got the following. Maybe it can assist you:
Response to Tech Support Post
1. Automating “Add to Calendar” for New Entries
Currently, Tap Forms requires users to manually press the “Add to Calendar” button for each entry in a date field. There is no built-in setting to automate this process for new records.
However, automation might be possible using scripting. Tap Forms supports JavaScript for automating tasks, and it may be possible to write a script that triggers the “Add to Calendar” function whenever a new record is created. You can refer to Tap Forms Scripting 101 for guidance on scripting in Tap Forms.
To apply this automation to existing records, a script could loop through all records and execute the “Add to Calendar” function in bulk.
2. Toolbar Calendar Icon Not Jumping to Current Month
From the Tap Forms manual (Section 7.3, Calendar View, p. 47-48), the calendar view allows navigation between months, but clicking on the calendar icon in the toolbar does not automatically jump to the month displayed in list mode. You must manually navigate the calendar using the arrows at the top.
3. Calendar Not Jumping to Selected Record in Sidebar
In the Calendar View, selecting a record from the list in the sidebar does not cause the main calendar view to jump to the corresponding month of that record. This behavior is currently by design.
A potential workaround could be:
• Clicking on a specific date within the calendar to filter records displayed.
• Using a Saved Search to focus on specific date ranges.Summary & Suggested Fixes
• Automate “Add to Calendar”: Use JavaScript scripting.
• Toolbar Calendar Icon Behavior: No automatic jump to the current month.
• Calendar Sidebar Selection: Selecting a record in the sidebar doesn’t change the calendar view.Would you like help drafting a script to automate adding records to your Apple Calendar?
and…
Here’s a Tap Forms JavaScript script that will automatically add records to your Apple Calendar when a new record is created. This script iterates through all records in a form and adds any missing entries to the Apple Calendar.
Steps to Use the Script:
1. Open Tap Forms.
2. Navigate to the Form where you want to automate the “Add to Calendar” function.
3. Open the Scripts Editor.
4. Create a new Script Field and paste the script below.
5. Run the script manually or set it up to execute automatically when new records are added.Tap Forms Script to Add Entries to Apple Calendar
// Tap Forms script to automatically add all records with a date field to Apple Calendar
function addToCalendar() { var form = document.getForm(); // Get the current form var records = form.getRecords(); // Get all records var dateField = form.getFieldNamed("Your Date Field Name"); // Change to match your Date field name var titleField = form.getFieldNamed("Event Title"); // Change to match your title field var calendarScriptField = form.getFieldNamed("Added to Calendar"); // Optional: Track if event was added if (!dateField || !titleField) { alert("Please check that you have a valid Date and Title field."); return; } for (var i = 0; i < records.length; i++) { var record = records; var eventDate = record.getFieldValue(dateField); var eventTitle = record.getFieldValue(titleField); var addedToCalendar = record.getFieldValue(calendarScriptField); // Check if already added if (eventDate && eventTitle && !addedToCalendar) { var script =tell application “Calendar”
set newEvent to make new event at end of calendar “Your Calendar Name”
set start date of newEvent to date “${eventDate}”
set summary of newEvent to “${eventTitle}”
end tell
`;// Execute AppleScript to add event to Calendar
var result = Utilities.executeAppleScript(script);if (calendarScriptField) {
record.setFieldValue(calendarScriptField, “Added”);
}console.log(“Added to Calendar:”, eventTitle, “on”, eventDate);
}
}
}// Run the function
addToCalendar();`
How It Works
• This script retrieves all records in a form.
• It checks for a date field and an event title field.
• If a record hasn’t already been added to the Apple Calendar, it:
• Runs an AppleScript command to create an event in Apple Calendar.
• Marks the record as “Added” (if you have a field for tracking).Setup Instructions
1. Replace “Your Date Field Name” with the actual Date field name in your form.
2. Replace “Event Title” with the name of your event Title field.
3. Replace “Your Calendar Name” with the actual name of your calendar in Apple Calendar.
4. Optional: Create a new Text field named “Added to Calendar” in your form to track which records have already been added.Execution & Automation
• Run this script manually to add existing records.
• If you want it to auto-run when a record is created, use a Trigger Script Field with Tap Forms.Would you like assistance setting up an automatic trigger for new records? 🚀
If you want further assistance, you can use the assistant or wait for the Safe of TF to give you to canonical response.
December 23, 2024 at 6:29 PM #51407In reply to: Previous Record Script
Daniel Leu
ParticipantHi Glen,
Set the return type of your Today & Previous script to
number! Astext, it concatenates the fields instead of adding them.Here’s the yesterday’s hours script:
function yesterdays_hours() { var records = form.getRecords(); var currentRecordIndex = records.indexOf(record); if (currentRecordIndex > 0) { var previousRecord = records[currentRecordIndex-1]; } else { return 0; } var today_hours_id = 'fld-7ecb8ad8fe3a4b6db80ea939a60accb2'; var yesterday = previousRecord.getFieldValue(today_hours_id); console.log("Yesterday: " + yesterday) return yesterday; } yesterdays_hours();Cheers, Daniel
---
See https://lab.danielleu.com/tapformspro/ for scripts and tips&tricksNovember 17, 2024 at 1:34 AM #51310In reply to: Group summaries
Daniel Leu
ParticipantThe Javascript API doesn’t provide a way to work on groups. The script posted by JScott shows results on all records. This could be enhanced if you can define how the records are grouped.
Another option would be to work on the current saved search. This would mean that you create a saved search for each group. Then you could replace
var records = form.getRecords();withvar records = search.getRecords();to get the results on the currently selected saved search.Oh, ignore the
alert(output)command in the script since this is not supported. You could useUtils.alertWithMessage(), but that’s not designed to display multi-line results. The console is your friend.Cheers, Daniel
---
See https://lab.danielleu.com/tapformspro/ for scripts and tips&tricksNovember 16, 2024 at 9:13 PM #51309In reply to: Group summaries
JScottA
ParticipantGlen, I have not tested the answer below, but I hope it helps you. It is from the unofficial custom GPT, Tap Forms 5 Assistant. I suggest you work on a copy of your database when testing this. Good luck!
To calculate and display the number of unique values for each field (e.g., “Class,” “Order,” “Family,” etc.) in your Tap Forms database, you have two options: either use the app’s built-in features for a manual method or run a script.
Option 1: Manual Method Using Export and External Analysis
1.Export the Data:
•Use Tap Forms’ export functionality to export your data as a CSV file. Instructions for exporting are on page 126 of the Tap Forms manual .
2.Analyze in Excel/Spreadsheet:
•Open the CSV in Excel or another spreadsheet tool.
•Use the “Remove Duplicates” feature for each column to count unique entries.
Option 2: JavaScript Script in Tap Forms
If you’d prefer an automated method, you can use Tap Forms’ scripting functionality (JavaScript API) to calculate the unique values for each field. Here’s a sample script you can use:
Sample Script
// This script calculates unique values for specified fields in the current form.
function uniqueValueCounts() {
var form = document.getFormNamed(‘Museum needs’); // Replace with your form’s name
var fields = [‘Class’, ‘Order’, ‘Family’, ‘Genus’, ‘Sp’]; // Replace with your field names
var result = “”;
fields.forEach(function(fieldName) {
var field = form.getFieldNamed(fieldName);
var records = form.getRecords();
var uniqueValues = {};
records.forEach(function(record) {
var value = record.getFieldValue(field);
if (value) uniqueValues[value] = true;
});
result += fieldName + “: ” + Object.keys(uniqueValues).length + ” unique values\n”;
});
return result;
}
var output = uniqueValueCounts();
console.log(output);
alert(output); // Displays the result in an alert box
How to Use the Script
1.Go to the Scripts section in Tap Forms and create a new script.
2.Copy and paste the above JavaScript code.
3.Modify the form and field names to match your data.
4.Run the script.
The output will display the unique value counts for each field in an alert box and in the console.
For additional details on scripting in Tap Forms, refer to the Tap Forms Scripting 101 Guide.
If you need further guidance or customization of the script, feel free to ask!
October 29, 2024 at 11:18 AM #51241In reply to: Prompter not pausing execution
Daniel Leu
ParticipantI don’t have the API, so I can’t verify, but otherwise, this seems to work.
The changes: I wrapped your main code in a function:
async function main(){....}and in there, I check if the id exists, if not I use thePrompterto get it.var apiKey = 'xxxxxxx';//var title_id = 'fld-a211cf1facf34470b4723b2b77e3f159';var genre_id = 'fld-f2fe50de9ca44bc6bee8887a6a1d1083';var IMDBrating_id = 'fld-e8c5f6890dce415396e3c5d6aa84a446';var runtime_id = 'fld-a917ded5c581468795cfcce40cb9f43b';var imdbid_id = 'fld-2b3bfd5a43ae46c1a3f059dbda9a3dd4';var year_id = 'fld-7f1cf965a9e04e7dae76e1f380f43367';var imdbsummary_id = 'fld-08a25e880aca4f7f89cf4cc268c55013';var poster_id = 'fld-688c78c4bd5148f0877e9a3f99799d5d';var graphic_id = 'fld-9e2d22d7b5d141678e741f41b2205fb5';var imdb_url_id = 'fld-2253e940bec14e7ca246db78109db488';var last_imdb_check_id = 'fld-d9b429bd674c4b5e8235844abaed9ba3';var checkdate = new Date();var imdb_url = ("https://www.imdb.com/title/" + record.getFieldValue(imdbid_id) + "/");// var imdb;var prompterVar;function textPrompter(title, text="") {return new Promise(function(resolve, reject) {let prompter = Prompter.new();prompter.cancelButtonTitle = 'Cancel';prompter.continueButtonTitle = 'Continue';prompter.addParameter(text,'prompterVar').show(title, ((status) => {if (status == false || prompterVar == undefined) {reject('Cancel');} else {resolve(prompterVar);}}));});}// Note: the following parameters are valid .addParameter(label, field_name, control type, values_list, default_value)function fetchMovieFromURL(){var movieID = imdbid_id;// var movieID = record.getFieldValue(imdbid_id);var fetchURL = 'https://www.omdbapi.com/?i=' + movieID + '&apikey=' + apiKey + '&r=json&plot=full';console.log('Requesting: ' + fetchURL);var movie_info = Utils.getJsonFromUrl(fetchURL);return movie_info;}async function main(){var movieID = record.getFieldValue(imdbid_id);if (!movieID) {try {await textPrompter("Enter the IMDB ID");console.log(prompterVar + " entered");const id = prompterVar;console.log("ID: " + id);record.setFieldValue(imdbid_id, id);form.saveAllChanges();// movieID = newID;// console.log(movieID);imdb_url = ("https://www.imdb.com/title/" + id + "/");} catch (errorText) {// user clicked 'No'console.log('Cancel button clicked');return "aborted by user";}}// var idValue = record.getFieldValue(imdbid_id);var results = fetchMovieFromURL();// if (results.totalItems) {// var movie_data = results[0];var movie_genre = (results["Genre"]);var movie_runtime = (results["Runtime"]);var movie_summary = (results["Plot"]);var movie_poster = (results["Poster"]);var movie_year = (results["Year"]);//var movie_title = (results["Title"]);var movie_IMDBrating = (results["imdbRating"]);var movie_stars = (results["Actors"]);var movie_writers = (results["Writer"]);var movie_director = (results["Director"]);record.setFieldValues({[genre_id]: movie_genre,[runtime_id]: movie_runtime,[imdbsummary_id]: movie_summary,[imdb_url_id]: imdb_url,[poster_id]: movie_poster,[year_id]: movie_year,[IMDBrating_id]: movie_IMDBrating,// [imdbid_id]: imdb,[last_imdb_check_id]: checkdate}, false);var poster = record.getFieldValue(graphic_id);if (poster <= "") {record.addPhotoFromUrlToField(movie_poster, graphic_id);}form.saveAllChanges;// Now process actor and director recordsvar actors_form = document.getFormNamed("Actors");var actor_records = document.getFormNamed("Actors").getRecords();var actor_name_id = 'fld-9e6772cd3ce64be1b0ba9f4bcaaeddd6';var actors_link_id = 'fld-dda27dcbe76447978890b3ad6be470d2';var actor_found = "N";// var writer_found = "N";let stars = movie_stars.split(', ');//loop to parse json results:for (let star of stars) {// console.log("**star** " + star);var candidateRecord = star;actor_found = "N";//now check if in actor form already, add if notfor (var index = 0, count = actor_records.length; index < count; index++) {var actor_name = actor_records[index].getFieldValue(actor_name_id);// console.log("actor_name " + actor_name);var actor_record_id = actor_records[index].getId(actor_name_id);var candidateField = actors_form.getRecordWithId(actor_record_id);// var currentRecord = movie_form.getRecords();if (actor_name == candidateRecord) { //ie, actor is already in actors form// console.log(actor_name === candidateRecord); // true or falseactor_found = "Y";console.log("Actor found - " + actor_name);// console.log("candidate_found should be Y " + candidate_found);// console.log("Yep - bye");// console.log("Existing actor found - adding to link table... "+ actor_name);// record.addRecordToField(candidateField, actors_link_id);// console.log("checking " + star + " in link table");// break;} else {actor_found = "N";} //if actor name} //for var index loopif (actor_found == "N") {console.log("New actor found - adding to main record... " + candidateRecord);var newRecord = actors_form.addNewRecord();newRecord.setFieldValue(actor_name_id, candidateRecord);// console.log("New actor found - adding to link table... " + candidateRecord);// record.addRecordToField(newRecord, actors_link_id);// form.saveAllChanges();} //if candidate foundconsole.log("Saving...");form.saveAllChanges();console.log("Existing actor found - updating link table... " + candidateRecord);record.addRecordToField(candidateField, actors_link_id);} //for let star of stars loopdocument.saveAllChanges();//....directorsvar directors_form = document.getFormNamed("Directors");var director_records = document.getFormNamed("Directors").getRecords();var director_name_id = 'fld-2132ad9eddc4412aaeed59e366946a3b';var directors_link_id = 'fld-e5ea9fce00e84ecd9d342f13840a10b4';var director_found = "N";let directors = movie_director.split(', ');//loop to parse json results:for (let director of directors) {var directorRecord = director;director_found = "N";for (var index = 0, count = director_records.length; index < count; index++) {var director_name = director_records[index].getFieldValue(director_name_id);var director_record_id = director_records[index].getId(director_name_id);var directorField = directors_form.getRecordWithId(director_record_id);if (director_name == directorRecord) { //ie, director is already in directors formdirector_found = "Y";console.log("Director found - " + director_name);// console.log("candidate_found should be Y " + candidate_found);// console.log("Yep - bye");// console.log("Existing director found - adding to link table... "+ director_name);// record.addRecordToField(directorField, directors_link_id);// console.log("checking " + star + " in link table");// break;} else {director_found = "N";} //if actor name} //for var index loopif (director_found == "N") {console.log("New director found - adding to main record... " + directorRecord);var newRecord = directors_form.addNewRecord();newRecord.setFieldValue(director_name_id, directorRecord);// console.log("New director found - adding to link table... " + directorRecord);// record.addRecordToField(newRecord, directors_link_id);// form.saveAllChanges();} //if director foundconsole.log("Saving...");form.saveAllChanges();console.log("Existing director found - adding to link table... " + directorRecord);record.addRecordToField(directorField, directors_link_id);} //for let star of stars loopdocument.saveAllChanges();}main();-
This reply was modified 12 months ago by
Daniel Leu.
-
This reply was modified 12 months ago by
Daniel Leu.
Cheers, Daniel
---
See https://lab.danielleu.com/tapformspro/ for scripts and tips&tricksOctober 28, 2024 at 7:17 AM #51232In reply to: Add up or down?
JScottA
ParticipantDoes this help you? I’ve not tested it but maybe it will spur your creativity for a real solution:
To achieve the desired effect of consistently placing duplicated records immediately after the original in Tap Forms, a JavaScript-based scripted function could provide a workaround. Here’s a general approach, leveraging the Tap Forms API capabilities found in the documentation:
1.Retrieve the Current Record’s Position: Identify the position of the original record within the sorted list.
2.Duplicate the Record: Use the record.duplicate() function to create a copy of the current record .
3.Insert at Correct Position: Based on the original record’s position in the form’s sorted list, reposition the duplicate if needed. This could be done by iterating over records to ensure the duplicate’s position is adjusted relative to the original.
Here’s a basic script outline:
// Retrieve the current record
var records = form.getRecords();
var currentRecord = form.getSelectedRecord(); // assuming this is the record to duplicate
var index = records.indexOf(currentRecord);
// Duplicate the record
var duplicatedRecord = currentRecord.duplicate();
// Reposition the record if needed by sorting again or programmatically moving
// Example: You might delete and re-add in sorted order if Tap Forms sorting is strict
form.saveAllChanges();
This script, while a creative workaround, may have limitations if Tap Forms enforces strict sorting on save, potentially reordering records automatically. Testing would determine if the manual duplication places the record in the intended position consistently.
October 10, 2024 at 9:09 AM #51198In reply to: How to add Text to multiple records?
Daniel Leu
ParticipantDo you have some type of criteria to select these records? Can you create a saved search for them? Or is it for all records?
Do add them to the list, I think the only way is using a script. Here’s an example of what I’m using:
var prompterVar;
function callbackSetTag() {const name_id = 'fld-xxx';const tags_id = 'fld-xxx';// get records from a saved searchlet recs = form.getSearchNamed('Selected').getRecords();// // use all records// let myRecords = form.getRecords();console.log('Found ' + recs.length + ' records');for (rec of recs){console.log("Processing " + rec.getFieldValue(name_id))var tags = new Array();// load initial valuesvar tag = rec.getFieldValue(tags_id);// create an array of tagsif (tag) {tags = tag.split(",");}// add new tagif (prompterVar){tags.push(prompterVar);}// save new tagsrec.setFieldValue(tags_id, tags.toString());console.log("Setting tags: " + tags.toString());}document.saveAllChanges();};function setTag(){let prompter = Prompter.new();prompter.addParameter('Tag', 'prompterVar', 'text').show('Add Tag to current record', callbackSetTag);}setTag();You will need to update the name_id and tag_id constants. name_id is used in the console log to provide some infos on which record the routine is running. tag_id is the field where you collect your tags. In your case, that would be the Mailings field.Next, you have to decide if this works on a saved search or on all records. My saved search is called Selected. Either you update this, or comment this line and uncomment the next block to perform the tagging on all fields.When you run the script, you get a prompter where you enter the new tag. Note, the tag may not contain commas!Hoffentlich hilft das. Viel Spass und Erfolg!Cheers, Daniel
---
See https://lab.danielleu.com/tapformspro/ for scripts and tips&tricksAugust 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 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&tricksApril 8, 2024 at 7:33 AM #50676Fernando DS
ParticipantHello everyone, I have an amount search script in the table field of all records. But it works for me with some quantities and not with others. And I don’t understand why.
This is the script:// Definiciones de IDs de campos dentro de la tabla
var pagos_cobros_tabla_id = ‘fld-a878bb1af5534101bcfab905279b1180’; // ID del campo Pagos/Cobros dentro de la tabla
var movs_banco_tabla_id = ‘fld-57a5fdcd593e46b298948845321d78ac’; // ID del campo Mvtos. Banco dentro de la tabla
var fecha_id = ‘fld-547c13e982e84d0793b0aba6c220cf76’; // ID del campo de fecha dentro de la tabla
var nombre_id = ‘fld-baf116cd116e4cde9b65e79014a49f28’; // ID del campo de nombre dentro de la tabla
var tabla_id = ‘fld-d8a58dbf35914f3c858c6dfb880c1c48’;
var nota_id = ‘fld-7918261f865b489a8f7672cf733712a9’;
var listado_de_script_id = ‘fld-555622f4bf0344f9b9e92af0806210fc’;
// Reemplazar ‘XXXXXX’ con el ID del campo “Listado de script”// Define el importe a buscar
var buscarImporte = “19.99”; // Ajusta este valor según el importe que desees buscarconsole.log(“”);
console.log(“*************************************”);
console.log(“Importe buscado: ” + buscarImporte);
console.log(“*************************************”);
console.log(“”);// Inicializar el contenido del campo “Listado de script”
var output = “”;// Función para parsear el importe independientemente del formato
function parseImporte(importeStr) {
if (typeof importeStr === ‘string’) {
return parseFloat(importeStr.replace(/[^\d.-]/g, ”)) || 0; // Devolver 0 si el valor no se puede convertir a número
} else {
return parseFloat(importeStr) || 0; // Devolver 0 si el valor no se puede convertir a número
}
}buscarImporte = parseImporte(buscarImporte);
var records = form.getRecords();
for (var i = 0; i < records.length; i++) {
var record = records;
var registrosTabla = record.getFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’) || []; // Reemplaza ‘tabla_id’ con el ID del campo de la tabla
var nombre = record.getFieldValue(‘fld-baf116cd116e4cde9b65e79014a49f28’); // Obtener el nombre fuera del bucle de la tabla// Array para almacenar los movimientos correspondientes a cada nombre
var movimientosNombre = [];for (var j = 0; j < registrosTabla.length; j++) {
var registroTabla = registrosTabla[j];
var pagosCobros = parseImporte(registroTabla.getFieldValue(pagos_cobros_tabla_id));
var movsBanco = parseImporte(registroTabla.getFieldValue(movs_banco_tabla_id));
var fechaRaw = new Date(registroTabla.getFieldValue(fecha_id));
var fecha =${('0' + fechaRaw.getDate()).slice(-2)}/${('0' + (fechaRaw.getMonth() + 1)).slice(-2)}/${fechaRaw.getFullYear().toString().substr(-2)};
var nota = registroTabla.getFieldValue(nota_id);// Comparar el valor absoluto de los importes
if (Math.abs(pagosCobros) === Math.abs(buscarImporte) || Math.abs(movsBanco) === Math.abs(buscarImporte)) {
movimientosNombre.push({ fecha: fecha, movsBanco: movsBanco, pagosCobros: pagosCobros, nota: nota });
}
}// Mostrar el nombre y luego los movimientos correspondientes
if (movimientosNombre.length > 0) {
output += “\n” + nombre + “\n\n”;
console.log(“” + nombre);
console.log(“”);
for (var k = 0; k < movimientosNombre.length; k++) {
var movimiento = movimientosNombre[k];
output +=${movimiento.fecha}: ${movimiento.movsBanco} | ${movimiento.pagosCobros}\n\n${movimiento.nota}\n;
console.log(${movimiento.fecha}: ${movimiento.movsBanco} | ${movimiento.pagosCobros});
console.log(“” + movimiento.nota);
console.log(“”);
}
}
}// Actualizar el campo “Listado de script” del primer registro con el texto generado
record.setFieldValue(listado_de_script_id, output);// Guardar los cambios en los registros
form.saveAllChanges();Any help will be welcome.
March 11, 2024 at 11:07 AM #50623In reply to: Previous record skip
Glen Forister
ParticipantI can’t figure out how to fix the code so the first actual record after the “Begin Year Mark” record adds the $100 to $0 of the initialization record for the year.Thanks…Date Org $ Total$01/01/24 Begin. 0 0 Begin Year mark01/01/24. KVMR 100 003/12/24 test 20 2003/27/24. test.2. 50 7004/17/24. test.3. 55 125Can’t remember how to display the code correctly – searched for it – Put that hint somewhere? “!”???!function Year_to_date() {var date_id = ‘fld-e2d20da877cb4a6c8fd72153b86f1ab1’;var donation_id = ‘fld-05c429d6a4484061b554aa584a45f8fc’;var total_id = ‘fld-7c6b9bb288ab47e0b295af6eacc9cd26’;var records = form.getRecords(); // calls function getRecords()var currentRecordIndex = records.indexOf(record);if (currentRecordIndex > 0) {var previousRecord = records[currentRecordIndex-1];} else {return 0;}// Is this the beginning of the year?var date = record.getFieldValue(date_id);if (date.getMonth() == 0 && date.getDate() == 1){return 0;}var today = record.getFieldValue(donation_id);var previous_total = previousRecord.getFieldValue(total_id);var total = today + previous_total;console.log(“Today: ” + today)console.log(“Previous: ” + previous_total)console.log(“Total: ” + total)return total;}Year_to_date();! -
This reply was modified 1 week, 5 days ago by
-
AuthorSearch Results