Custom JS examples

Home Forums Modern DFFS Custom JS examples

Viewing 16 reply threads
  • Author
    Posts
    • #36150
      Alexander Bautz
      Keymaster

        To use all these examples you must have v1.0.12.0 or later


        Updated February 04, 2024: Added dffs_vLookup_callback example

        Updated September 07, 2023: Updated dffs_showModal code example and added dffs_hideModal


        Please note that you can do most of this with rules. Using Custom JS is an option for advanced users.

        Do something before the item is saved

        You can use a function like this to run your own custom code before save. The function must return true to allow save, or false to stop the save. If you use this function it will run before the rules triggering on “Before save of the form” and “After save of the form”. If your function returns false the rules described will not run.

        function dffs_PreSaveAction(exit, autosave) {
          if (exit) { // Code only runs when you use SaveAndExit (new in v1.0.46.0)
            // This example will prevent save if the title field value is not "test"
            if (getFieldValue("Title") !== "test") {
              alert("Nope, you cannot save!");
              return false;
            }
            // Allow save
            return true;
          } else {
            if (autosave) {
              console.log("AutSaving");
            } else {
              console.log("QuickSaving");
            }
          }
        }

        Save the item from Custom JS

        Call this function from Custom JS to save the form:

        dffs_triggerSave(true); // Save and exit
        dffs_triggerSave(false); // Quick save

        Do something after the item is saved

        You can use a function like this to run your own custom code after the item is saved

        function dffs_PostSaveAction() {
          // Do something after the item is saved - for example redirect to another page
          // You can read values from the current item using getFieldValue("Name_of_field")
          location.href = "https://contoso.com/SavedMsg";
        }
        

        Do something if the item is cancelled / closed

        You can use a function like this to run your own custom code if a form is opened and then cancelled out of without saving.

        function dffs_PostCancelAction() {
          // Do something if the item is cancelled - for example redirect to another page
          location.href = "https://contoso.com/CancelMsg";
        }
        

        Do something if the item is deleted

        You can use a function like this to run your own custom code after an item is deleted (from within a form, not from the list view menu).

        function dffs_PostDeleteAction() {
          // Do something if the item is deleted - for example redirect to another page
          location.href = "https://contoso.com/DeletedMsg";
        }
        

        Show a modal dialog

        To show a modal dialog with a custom message you can use this code. Please note that this will be a non-blocking dialog so it will not prevent other code from running when the dialog is shown (like the default browser “alert” function does).

        var modalId = dffs_showModal({
        "title": "A message to you",
        "body": "Add your message body here. You can use plain text or HTML",
        "isBlocking": true,
        "showClose": true,
        "showFooter": true,
        "closeCallbackFn": () => {
        // Add your custom code that runs when the dialog has been dismissed
        alert("Closed");
        },
        "cancelBtnLabel": "Cancel button",
        "cancelBtnFn": () => {
        // Add your custom code to run when clicking the cancel button
        },
        "okBtnLabel": "OK Button",
        "okBtnFn": () => {
        // Add your custom code to run when clicking the OK button
        }
        });
        

        If you don’t include the “cancelBtnFn”, the Cancel button is not shown. The OK button will always show (unless you set “showFooter”: false) and will by default close the dialog.

        New in v1.0.32.0 is that the dffs_showModal returns the ID of the modal – which can be used to programatically close the modal like this:

        dffs_hideModal(modalId);

        Trigger custom code when a field is changed

        Use a function like this to run custom code when a field is changed.

        function dffs_fieldChanged(fin, new_value, previous_value) {
          console.log("The field " + fin + " was changed from");
          console.log(previous_value);
          console.log("to");
          console.log(new_value);
        }
        

        Toggle readonly on a field

        Toggling readonly can be easily done in rules, but if you want to do it using custom js you can do it like this:

        // Set as readonly
        dffs_doReadonly(["Status", "Title", "AssignedTo"]);
        // Undo readonly
        dffs_undoReadonly(["Status", "Title", "AssignedTo"]);
        

        Toggle the visiblity on individual options in a choice field

        The code example was changed because of a change in v1.0.46.0

        dffs_choice_option_hidden = {"DropdownChoice_31838417512562245": { "Enter Choice #1": true, "Enter Choice #3": true }};
        

        The id (DropdownChoice_31838417512562245) for your field can be found in the field property panel. Add the label of the options you want to hide and set the value to true. Reversing the action and make them visible again by setting the value as false. You only have to address the options you want to hide or show.

        Detect change in a field

        Use this in for example dffs_PreSaveAction to detect change in the title field:

        if(dffs_beforeProperties["Title"] !== getFieldValue("Title")){
            alert("Title has changed!");
          }
        

        Add a callback when a vLookup has loaded

        You can use this method to run your own custom code when a vLookup has loaded. You can find the id of the vLooup in the vLookup configurator.

        function dffs_vLookup_callback(id, items){
          if(id === "vLookup_7943515991751215"){
            console.log(id, items);
          }
        }
        

        Flag, clear or check mandatory fields from Custom JS

        These functions requires v1.0.65.0 or above.

        // Flag fields as required
        dffs_flagMandatory(["Field_1", "Field_2"]);
        // Clear the required flag from fields
        dffs_clearMandatory(["Field_1", "Field_2"]);
        // Check if all mandatory fields have been filled in.
        let allFieldsFilledIn = dffs_checkMandatory(false); // Shows required fields banner to alert the user of any enpty required fields
        let allFieldsFilledIn = dffs_checkMandatory(true); // Do not show any message to the user
        

        Please note that flagging a field that is not in the form has no effect.

        Post any question below.

        Best regards,
        Alexander

      • #36169
        SteveE
        Participant

          Hi Alexander,

          I’m just getting to play around with this and I think you might have missed some of your instructions. You mention setting something as read only but then your code is for hiding a choice.

          Anyway, I’m trying the hide option and I can’t get it to work. I wrapped it in a ready function that I know works. I tried adding # to the beginning of the field reference also.

          Here’s what I’m using:
          jQuery(document).ready(function($) {
          dffs_choice_option_hidden[“8506407795472748_DropdownField”] = {“Enter Choice #3”: true };
          });

          I’m on version 0.9.0.14. Thanks.

          • #36173
            Alexander Bautz
            Keymaster

              Sorry about that – the example has been updated to add the readonly example.

              Not sure why your options are not hiding – can you add some screenshots (or email it to me)?

              Alexander

          • #36587
            Joe Penland
            Participant

              Hi Alexander,

              Can you provide an example of triggering a rule in Custom JS? I am struggling to figure out how to do that with Modern DFFS, and I may be missing it, but can’t seem to find an example (for Modern DFFS) by searching the forum.

              Thank you for your help.

            • #36588
              Alexander Bautz
              Keymaster

                This is currently not possible. What are you trying to accomplish?

                Alexander

                • #36589
                  Joe Penland
                  Participant

                    Oh, I assumed it was possible because in the rule it shows:

                    RuleID (for use in Custom JS)

                    I am trying to show or hide an element based on the value in a field. For some reason the rule does not apply when the form loads–just when the field is manually updated afterwards. We do have it set to trigger on “Form load and change of conditions for triggering this rule,” but it seems to only trigger on the change of conditions part. Our condition is just if a particular field is “Yes” and the “If yes” part uses the “Show elements” action while the “If no” part uses the “Hide elements” action. It works if the field is manually updated, but it doesn’t seem to run the rule when the form opens.

                    My thought was to run the rule on a button click that is part of the form navigation anyway. I will see if I can come up with another way to make sure the rule applies like I want it to.

                    If I do resort to an action in the button click, is there a built-in action to hide an element from Custom JS?

                  • #36590
                    Alexander Bautz
                    Keymaster

                      I see, the id can only be used to check the status of a rule in your custom js – like this:

                      if(dffs_ruleState['030030010565992526']){
                          // The rule is true - do something
                      }
                      

                      Are you sure you have checked correct option under “Trigger this rule on”?

                      If you have, please give me some details on the field type and any other things I need to replicate the issue.

                      Alexander

                  • #36591
                    Joe Penland
                    Participant

                      It is just a normal choice field with “No” and “Yes” options. There may be more to this on our side. I am picking up where another user created the beginning of the form. I will do some more research into this and report back whether or not there is something that requires your assistance. Thanks for your willingness to help.

                      • #36653
                        Joe Penland
                        Participant

                          It turns out the issue was a rule/form configuration mismatch. The rule which was supposed to trigger on form load included hiding many fields, but the fields had been deleted from the form itself where the rule was being applied. This did not trigger any errors, and I never could get any output in the console even with debugging on, which seems strange still. However, I was able to rebuild the form and only hide fields which were actually present. With this configuration, the rule triggers and outputs to the console as expected.

                          So my conclusion is, it seems if the rule which triggers on form load is referencing fields that do not actually exist in the form (even though they exist in the list), the rule may break or otherwise not run–even though the trigger conditions are met (but I never got any error messages to prove this theory).

                        • #36654
                          Alexander Bautz
                          Keymaster

                            Sorry, but I’m not able to recreate this issue. If you are able to give me a step-by-step guide to recreate it I’ll do my best to fix it though.

                            In my testing I found another bug where if you deleted a field used in a show/hide action in a rule, selecting the rules tab in the configuration would crash the configurator – I’ll get this one fixed in the next release.

                            Alexander

                          • #36655
                            Joe Penland
                            Participant

                              There must have been something unusual going on, but I don’t know what. I tried reproducing it, but I couldn’t do it with a simple clean list. Not sure exactly what was happening, but I did get it resolved by overwriting the form with an export from a mirror list. Sorry about the false alarm and inability to reproduce the issue! Thanks for your help.

                          • #36659
                            Alexander Bautz
                            Keymaster

                              No problem – I’m glad you got it resolved.

                              Alexander

                            • #37055
                              Wendi Watson
                              Participant

                                Hi Alexander,

                                Would you be able to tell me how I make an HTML header section collapsible and expandable? Also is there a way to pop up a preview of email before it is sent in a window?

                              • #37057
                                Alexander Bautz
                                Keymaster

                                  Hi,
                                  You can use this example to create a collapsible HTML section: https://www.w3schools.com/howto/howto_js_collapsible.asp

                                  The email preview is a good idea – I’ll add it to the wish list for a future version.
                                  Alexander

                                • #37238
                                  Jonathan Stamper
                                  Participant

                                    Is the PostSaveAction available in the classic version of DFFS? If so, could I use email templates to send out emails instead of using workflows?

                                  • #37244
                                    Alexander Bautz
                                    Keymaster

                                      Sorry, but there are no PostSaveAction in the classic DFFS.

                                      Alexander

                                    • #37943
                                      Travis Goodman
                                      Participant

                                        Alexander, is there a reference sheet that has all the possible dffs functions that can be leveraged?

                                        • #37947
                                          Alexander Bautz
                                          Keymaster

                                            The functions listed at the top of the page is about it. Is there anything specific you are looking for?

                                            Please note that to interact with other SharePoint list you can use any JavaScript code that uses the REST API.

                                            Alexander

                                          • #37971
                                            Travis Goodman
                                            Participant

                                              yeah like for example, right now I have a vlookup table that’s bringing in a few calculated columns that output numbers. Even though I have the column in the list set to 2 decimal places, the vlookup table is loading them with like 10 decimal places. I don’t see a clear way on how to custom format those, so I’m just going to do it the old fashioned way with jQuery.

                                              That’s not my best example though, it’d be more like understanding what functions are available inside what in classic would be called spjs.utility. Additionally, customjs dffs specific actions like setFieldValue, getFieldValue, etc. which I know exist, but I’m wondering what else exists that I’m not currently aware of without digging into the code itself and looking.

                                              That kind of stuff, because for me rules are great, but I end up doing a ton of advanced stuff within customjs and I find myself often just writing things in jQuery when you probably have a shortcut script that already handles it already that I could leverage.

                                              I’m trying to think of something even more specific… ok so referring to a few of my notes here, it looks like I’ve written down some things missing from Modern DFFS that I’m accustomed to in Classic DFFS. Triggering a specific rule from within a customjs function appears to not be part of Modern DFFS yet. I don’t see it in the user manual, but correct me if I’m wrong.

                                            • #37972
                                              Travis Goodman
                                              Participant

                                                I did find the field customizer inside vlookup settings just now, but it wasn’t mentioned in user manual. Does modern vLookup have separate documentation like classic vlookup does? the documentation on classic vlookup is really robust, and has helped me a lot! That actually gives me clarity on how to describe what I’m looking for. So in the classic vlookup documentation you have a section about events for event triggering and also a section on accessing the vlookup data object, it’s that kind of advanced stuff I’m looking for to see what I can do within customjs to fully leverage dffs beyond the rules GUI. And I don’t want to focus just on vlookup, that’s just an example. It would help me tremendously if I knew what all built in functions exist that I can leverage in customjs.

                                            • #37974
                                              Alexander Bautz
                                              Keymaster

                                                Hi,
                                                I’m not able to recreate the problem where a vLookup table number field shows the “raw” data with 10 digits. Can you send me some screenshots of your config?

                                                Regarding documentation for vLookup:
                                                No, there is no separate documentation. The user manual shows some examples for vLookup – like how to get the list of items when the vLookup table has loaded. I’ll try to find time to update the documentation in the user manual with more information.

                                                Regarding available functions you can use in Custom JS:
                                                There are less built in functions you can access in the Modern DFFS version compared with the Classic DFFS version. This is because it is built as an SPFx solution using React, and the source files are not exposed in the global window-namespace.

                                                The functions that are available are listed in this forum thread (linked from the user manual Custom JS section): https://spjsblog.com/forums/topic/custom-js-examples/

                                                In addition you can – as you mention – use any custom code you write yourself interacting with other SharePoint lists using the REST API.

                                                Regarding triggering rules from custom js:
                                                The latest version (v1.0.65.0) added a new trigger in the rules section where you can create a rule that can be triggered from Custom JS. Please note that you cannot trigger any rules, but only the ones configured with this trigger.

                                                Alexander

                                              • #38106
                                                Wayne Thompson
                                                Participant

                                                  Hi Alexander! 🙂

                                                  How about a handy Custom JS example to rename the “Save and exit” button?

                                                  I was so spoiled with all of the Classic DFFS Built-in Function References.

                                                  Thanks again,
                                                  Wayne

                                                • #38109
                                                  Alexander Bautz
                                                  Keymaster

                                                    I’ll look into it and see if I can let you override all strings. I’ll try to get a new version out later this week.

                                                    Alexander

                                                  • #38133
                                                    Wayne Thompson
                                                    Participant

                                                      Hi everyone! 🙂

                                                      Seeking volunteers and examples of any custom code for the following scenario:

                                                      Wish to hide field elements in a Display Form in bulk if their value is blank.

                                                      Could accomplish this one field at a time with multiple rules but that is inefficient.

                                                      Thanks,
                                                      Wayne

                                                      • #38138
                                                        Alexander Bautz
                                                        Keymaster

                                                          Hi,
                                                          You can do this by creating a rule that triggers on “Form is loaded” and in the “if yes” select the “Call a function”. Add the name of the function like this:

                                                          hideEmptyFields
                                                          

                                                          Now add this to your Custom JS and change the “arr” to include the FieldInternalName of the fields you want to check for empty.

                                                          function hideEmptyFields() {
                                                            var arr = ["Field1", "Field2", "Field3", "Field4"];
                                                            arr.forEach(fin => {
                                                              if (String(getFieldValue(fin)) === "") {
                                                                document.querySelectorAll("div[data-fin='" + fin + "']").forEach(row => {
                                                                  row.style.display = "none";
                                                                });
                                                              }
                                                            });
                                                          }
                                                          

                                                          Alexander

                                                          • This reply was modified 1 month, 1 week ago by Alexander Bautz. Reason: Fixed wrong trigger name
                                                        • #38140
                                                          Wayne Thompson
                                                          Participant

                                                            Perfect and precise! 🙂

                                                            Thanks so much,
                                                            Wayne

                                                        • #38279
                                                          Wayne Thompson
                                                          Participant

                                                            Hi everyone! 🙂

                                                            Seeking volunteers and examples of any custom code for the following scenario:

                                                            Wish to force attachments shown in the Display Form when selected/clicked to have the option to Download in addition to open.

                                                            Thanks,
                                                            Wayne

                                                          • #38286
                                                            Alexander Bautz
                                                            Keymaster

                                                              I have noted it and will see if I can add support for that in a future release (most likely as an option that you can set on the attachment field if you want to allow downloading files).

                                                              Alexander

                                                          Viewing 16 reply threads
                                                          • You must be logged in to reply to this topic.