Tap Forms app icon half
Tap Forms Forum text image
Blue gradient background

Exchange tips and ideas with the Tap Forms community

Search Results for 'script'

Viewing 15 results - 2,356 through 2,370 (of 2,985 total)
  • Author
    Search Results
  • #37058
    Sam Moffatt
    Participant

    The built in calculation field has a DAYS function that will give you the number of days between two dates and put it in the field.

    The field ID detection code I think is triggered by getFieldValue('fld-etc') and using the var date_id syntax is tripping it up. It’s a little bit magical, I made my piece with it once I figured it out.

    In the script editor when I run the code (though changing the field ID), I also get an error reporting TypeError: bought.getTime is not a function. (In 'bought.getTime()', 'bought.getTime' is undefined), column:46, line:4. Take out the getTime()

    You don’t need the document.saveAllChanges() in this context, however in your example what you’re missing is a return days; at the end. Something like this I think would work better for you:

    function calcdays() {
        var today = new Date();
        var bought = record.getFieldValue('fld-018ce5f02f7a4655be3e8f4377592f8b');
        var days = today - bought;
        var days = days / (1000*3600*24);
        return days;
    }
    calcdays();
    

    Here’s what that script looks like:

    And in the default layout it looks like this:

    That said once that script runs once, unless the “bought” field changes or your refresh the record then the script field value won’t change. There isn’t a way to automatically recalculate the value. This makes sense because Tap Forms is generating the value and saving it so that it doesn’t have to recalculate it every time. I suspect it also helps the search system by not having to regenerate the value when you search or sort too.

    Another thread on age calculations is here: https://www.tapforms.com/forums/topic/age-calculations/

    Attachments:
    You must be logged in to view attached files.
    #37057
    Marcus
    Participant

    By using an additional number field that works:

    function calcdays() {
    var today = new Date();
    var date_id = 'fld-db4e94e8bb1a46e7b886afba72a6f2df';
    var bought = record.getFieldValue(date_id);
    var days=today.getTime() - bought.getTime();
    var days=days / (1000*3600*24);
    var res = record.setFieldValue('fld-1737a7de921041b3a2d6d90340537480',days);
    document.saveAllChanges();
    }
    calcdays();

    But is the right way to use a script field ?
    The general question I have:
    Is such a script field able to have a output (value) directly ?

    #37055
    Sam Moffatt
    Participant

    I believe script fields are only executed when a referenced field is changed. Because the default snippet doesn’t reference any fields, by default it doesn’t execute. Perhaps it could be considered a bug it doesn’t run on a new record creation, calculation fields run after creation.

    What you could do is get the value of every field in the form, then a change will trigger the script every time those fields change. Alternatively you can manually refresh the record after creation and it’ll force the execution of every script and calculation field. The manual refresh is done by clicking the “Recalculate formulas” button at the bottom of your record, by selected “Record” > “Refresh Selected Record” when the record is selected in the layout or you can refresh your entire form by clicking “Refresh record list” under the list view area.

    When running in the script editor, not everything is persisted. If you’re working with just a single record you’ll need to manually refresh it per the above but if you want the new script field code to apply to all of your existing records you should tick “Update records when saving” next to “Done”/”Save” buttons at the bottom right of the script editor.

    I’ve not found this too problematic in practice, generally you’re picking up field values to work with and when those are populated the script should execute. What is your use case for running a script at form creation?

    #37052
    Marcus
    Participant

    Hi Script Guys,

    It’s more or less not a scripting question but how to use it in TapForms.

    I do have a form with a script field, the script behind, just as simple example:

    function Script() {
    var hello_world = "Hello World"; 
    return hello_world;
    }
    
    Script();

    I assumed TapForms will set this field value to “Hello World” when a recordset is added or changed ?
    But it’s empty, independant of which type of value (text, number, …)
    The console log shows the value, but the field stays empty.

    I additional added document.saveAllChanges; without any change.

    Or is such a script field to be used only to set another field value by using recordset.setFieldValue(ID,value) ?

    #37039
    Sam Moffatt
    Participant

    A long time ago, I created one checkbox to mark a particular state transition. A while later I ended up realising I need another checkbox because I messed up the first one and it could be ambiguous. So I decided to create a sort of flip flop where if you check one check box, it unchecks the other one.

    To solve this I created a new script field that watched the two fields and then used itself to store the historic state of these fields as a serialised JSON value. When it runs, it checks the values and then sees if the field changing is different to what it’s seen previously. It then decides if it wants to toggle the checkbox and returns a JSON string with the current field states to be stored for next time.

    To work this uses the Logger module and it also includes a reference to the Form Logger that I used to find the field ID of the script fields. The script is listed below:

    // Import the logger and output the header.
    document.getFormNamed('Script Manager').runScriptNamed('Logger');
    logger.consoleHeader('Checkbox Flip Flop', 'Shipments');
    
    // Get the current values of the check boxes.
    var confirmed = record.getFieldValue('fld-2adb9ba8cdd048bbbb614d46b415ada5');
    var unverified = record.getFieldValue('fld-abdb319b7db74fc39812a94778c433cc');
    
    // Get the current value for this script field.
    var oldState = record.getFieldValue('fld-2cd0296ea0884c8cba3640d8e33f010b');
    
    // Create a copy of the new state for later.
    var newState = {'confirmed': confirmed, 'unverified': unverified};
    
    // This logs all of the script fields in the form using the form logger.
    document.getFormNamed('Script Manager').runScriptNamed('Form Logger');
    formLogger.dump({'type': ['script']});
    
    // For debugging, log the various states.
    logger.logMessage(<code>Current State: ${oldState}</code>);
    logger.logMessage('New State: ' + JSON.stringify(newState)); 
    
    // If we have an old state, we parse it out (otherwise it'd be null).
    if (oldState)
    {
    	oldState = JSON.parse(oldState);
    }
    else
    {
    	oldState = { 'unverified': false, 'confirmed': false };
    }
    
    // If the old state was unverified and not confirmed and this is confirmed...
    if (oldState['unverified'] && !oldState['confirmed'] && confirmed)
    {
    	// Update the unverified field to not be set.
    	logger.logMessage('Unsetting unverified flag since confirmed flag toggled');
    	record.setFieldValue('fld-abdb319b7db74fc39812a94778c433cc', false, false);
    }
    
    // If the old state was confirmed and not verified and this is now unverified...
    if (oldState['confirmed'] && !oldState['unverified'] && unverified)
    {
    	// Update the confirmed field to not be set.
    	logger.logMessage('Unsetting confirmed flag since verified flag toggled');
    	record.setFieldValue('fld-2adb9ba8cdd048bbbb614d46b415ada5', false, false);
    }
    
    // Save the changes to the database.
    document.saveAllChanges();
    
    // Turn the newState into a JSON string.
    var result = JSON.stringify(newState);
    logger.consoleFooter('Checkbox Flip Flop', 'Shipments');
    
    // Return the JSON string for the next execution run.
    result;
    

    There’s one issue with this in that the UI doesn’t seem to update properly when the checkbox state is changed. At some point I’ll turn it into a combobox and fix my fields but until then, I have some automation to keep my state consistent.

    #37038
    Sam Moffatt
    Participant

    I had a need to get the script field ID which isn’t readily available in the Script Editor and decided to do a quick form script so that I could pick it up later. If you’ve used my ‘Script Manager’ form convention, then just create a new form script in it called ‘Form Logger’.

    You can call it without arguments to get all fields dumped, here’s some sample calling code:

    document.getFormNamed('Script Manager').runScriptNamed('Form Logger');
    formLogger.dump()

    If you want to filter by type, you can specify the field type:

    document.getFormNamed('Script Manager').runScriptNamed('Form Logger');
    formLogger.dump({'type': ['script', 'text']});

    And this is it’s output in the console:

    Form Logger: Shipments
    Type Filter: ["script","text"]
    Layout: default
    fld-c487390743c947969cbe661cff596855: text	Tracking Number
    fld-0950c430cb0c41f79c51d43a544b366b: text	Carrier
    fld-7a29242731d9451092c92d8586dbc94a: script	Tracking Details
    fld-dddcdc15e1c44aa4a99bba6314dc7a07: script	Tracking URL Autocomplete
    fld-9bee4fd0919e4b439e7bed8d5a6c1053: script	Tracking Number Reformat
    fld-2cd0296ea0884c8cba3640d8e33f010b: script	Checkbox Flip Flop
    fld-a9a09a61a9e949199e92d47c02fd364c: text	Shipment Order ID
    fld-f7aba3b5ddd6430cb8e9a211e0086c84: script	Date Propagation
    fld-45c8f29ec3214fc5aacbba73e2de3142: script	Order ID FK

    *Note:* This won’t look as formatted in the console because it uses a proportional font.

    Here’s the full script, it’s pretty simple:

    // ========== Form Logger Start ========== //
    // NAME: Form Logger
    // VERSION: 1.0.1
    // CHANGELOG:
    //   1.0.1: Added support for custom form name and fix for "getId" rename.
    
    /**
     * Method to dump out the field ID's, type and names with the ability to filter by type.
     */
    if (formLogger == undefined)
    
    var formLogger = (function() {
    
    	return {
    	
    		dump: function({type = [], layout = 'default', formName = ''} = {})
    		{
    			let targetForm = form;
    			if (formName)
    			{
    				targetForm = document.getFormNamed(formName);
    			}
    
    			console.log('Form Logger: ' + targetForm.name);
    			console.log('Type Filter: ' + JSON.stringify(type));
    			console.log('Layout: ' + layout);
    	 		var fields = targetForm.getFields();
    
    			for (field in fields)
    			{
    				if (type.length == 0 || type.includes(fields[field].fieldType)) 
    				{
    					console.log(fields[field].getId() + ": " + fields[field].fieldType + "\t" + fields[field].name);
    				}
    			}
    		
    		}
    	}
    })();
    // ========== Form Logger End ========== //
    

    As you might gather, I want to have a layout additional filter but haven’t gotten there yet. Maybe in a later version.

    #36948
    Brendan
    Keymaster

    form.selectRecord() just selects the record. It doesn’t specifically do it for the Default Layout. It displays whatever the last layout that was selected. Tap Forms stores that information in a preferences file (DocumentProperties.plist) within the .tapforms document so it knows what layout to display the next time you view a form’s records.

    It definitely sounds interesting and useful to add some more UI automation features to the scripting engine.

    #36941
    Daniel Leu
    Participant

    Hi Brendan,

    I work on a CRM system using Tapfroms where I would like to guide the user (eg, me:) along the way. I used custom layouts to add a new client, quotations, orders, and sales. Each has its own form and custom layout.

    On the client form, I would like to have buttons for ‘quotation’, ‘order’, ‘invoice’. etc. Clicking a button would trigger a script that creates a new record in the respective form. Next I would like to display directly the custom layout to enter the needed information, eg, form.showLayoutNamed(‘my fancy quotation layout’);.

    I haven’t seen anything in the documentation supporting this. Is this something that could be added? This would make it much easier to implement flow-like applications and guide the user along.

    Thanks,
    Daniel

    Cheers, Daniel

    ---
    See https://lab.danielleu.com/tapformspro/ for scripts and tips&tricks

    #36929

    In reply to: Auto backup iOS

    Doug
    Participant

    Thanks for your answers.
    iCloud for the device and for Tap Forms works but you cant restore from previous version with these solutions.
    In fact, you can with device iCloud backup, but it’s totally incontrollable as we dont know exactly the date, and there is only 1-2 restore point.
    T think of a create a iOS reminder but i dont know how to do that with the script function.
    Thank you.

    #36916

    In reply to: Auto backup iOS

    Brendan
    Keymaster

    I haven’t written any scripting code to allow you to write a script that lets you automate a backup on iOS. On macOS quitting the app can trigger an automatic backup, but not on the iOS version. You have to tap the + button on the Backup & Restore screen periodically to create a backup file manually.

    #36913
    Rocky Machado
    Participant

    Thanks Sam / Brendan – I created a script and brought the date(s) to the parent form. I can now search using the General Search.

    thanks,
    rocky

    #36911

    Topic: Auto backup iOS

    in forum Script Talk
    Doug
    Participant

    Hi, is there a way to create a backup automatically, for example when leave app, or sometime when working on the bdd?
    Only on iOS please, a script can handle the job to click on the + on the Backup & Restore window ?!
    Thank you for yours ideas!

    #36910
    Sam Moffatt
    Participant

    Starting with modelling the data is probably the first problem and then move on from there. Like any database, you’re only going to get so far before you need to teach it some of your custom logic and processes.

    That said I write a lot of scripting for Tap Forms to help automate a lot of data entry and speed up common tasks. Scripting added a massive power boost for Tap Forms capability wise to enable all sorts of interesting functionality.

    #36909
    Sam Moffatt
    Participant

    The script I posted for combining multiple values from a child form should also work for tables. I use this to make parent fields searchable by values in their child fields.

    #36906
    Brendan
    Keymaster

    Hi Rocky,

    That’s right. Date fields can’t be searched via the general search. You need a Saved Search for that. However, Date fields within a Table field can’t be searched at all. I only index the text and numeric data types within a Table field. You could do it by adding a Script field to your parent form which extracts out the date values from your Table field into a single Script field in the parent form. That way when you do a general search you’ll be searching the parent form, not the Table field’s records directly.

    Thanks,

    Brendan

Viewing 15 results - 2,356 through 2,370 (of 2,985 total)