Skip to main content
Hasan KOYUNCU
Inspiring
February 24, 2025
Question

Help Needed: Acrobat Folder Level Scripting Error

  • February 24, 2025
  • 2 replies
  • 1510 views

The laborious task of scripting multiple fields within an Acrobat form presents a formidable challenge. Driven by this very difficulty, I endeavored to craft a Folder Level script, a mechanism to imbue numerous fields with specialized code within their Properties tabs. Alas, my creation falters.

Consider, if you will, a scenario. From the dialog box's dropdown, I select the "Day" field, its true nature revealed in the sequence "Day1" through "Day31." Within this same dialog, I specify "1" as the Start Number and "31" as the End Number, thus defining the scope of my intended action. Furthermore, I choose "Format" from the Target Action menu. Finally, in the designated area for JavaScript Code, I input the specific script intended for the Format property of these selected fields. The culmination of these actions, however, yields not the desired result, but rather a disheartening error, etched in the console log.

I find myself in a state of hopeful anticipation, awaiting your invaluable assistance in resolving this perplexing matter.

App Alert:
Please select a Field Prefix.

Console Log:

Before execDialog
Dialog initialized
Commit function called
After execDialog, result: ok, dialog.results: {}

Complete Script Code:

// FormScriptUtility.js - Folder Level Script for Acrobat

app.addToolButton({
    cName: "FormScriptUtility",
    cLabel: "Populate Properties",
    cTooltext: "Set custom scripts for multiple form fields",
    cEnable: "event.rc = (app.doc != null);",
    cExec: "launchFormScriptUtility();",
    nPos: -1
});

function launchFormScriptUtility() {
    var allFields = [];
    for (var i = 0; i < this.numFields; i++) {
        allFields.push(this.getNthFieldName(i));
    }
    var prefixMap = {};
    allFields.forEach(function(field) {
        var match = field.match(/^([A-Za-z]+\.?)(\d+)$/); // Nokta için \.?
        if (match) {
            var prefix = match[1]; // "ProjectCode." gibi
            prefixMap[prefix] = true;
        }
    });
    var formPrefixes = Object.keys(prefixMap);

    var dialog = {
        results: {}, // Dialog sonuçlarını saklamak için

        initialize: function(dialog) {
            console.println("Dialog initialized");
            var fieldItems = {};
            fieldItems[""] = ""; // Boş seçenek
            formPrefixes.forEach(function(prefix) {
                fieldItems[prefix] = prefix; // Metni doğrudan kullan
            });

            var actionItems = {
                "": "",
                "Validate": "Validate",
                "Calculate": "Calculate",
                "Keystroke": "Keystroke",
                "Format": "Format",
                "Mouse Up": "Mouse Up",
                "Mouse Down": "Mouse Down",
                "Focus": "Focus",
                "Blur": "Blur"
            };

            dialog.load({
                "fpre": fieldItems,
                "snum": "",
                "enum": "",
                "actn": actionItems,
                "scpt": ""
            });
        },
        commit: function(dialog) {
            console.println("Commit function called");
            var results = dialog.store();
            console.println("Store results: " + JSON.stringify(results));

            // Field prefix
            this.results.fieldPrefix = results["fpre"] || "";

            // Sayılar
            this.results.startNum = parseInt(results["snum"], 10) || 0;
            this.results.endNum = parseInt(results["enum"], 10) || 0;

            // Action
            this.results.action = results["actn"] || "";

            // Script
            this.results.script = results["scpt"] || "";

            console.println("dialog.results updated: " + JSON.stringify(this.results));
        },
        description: {
            name: "Set Form Scripts",
            elements: [{
                type: "view",
                width: 450,
                height: 450,
                elements: [{
                    type: "static_text",
                    name: "Step 1: Select Field Prefix from Form Fields",
                    width: 400,
                    height: 20,
                    alignment: "align_center"
                }, {
                    type: "popup",
                    item_id: "fpre",
                    width: 200,
                    height: 20
                }, {
                    type: "view",
                    align_children: "align_row",
                    elements: [{
                        type: "static_text",
                        name: "Start Number:",
                        width: 100,
                        height: 20
                    }, {
                        type: "edit_text",
                        item_id: "snum",
                        width: 50,
                        height: 20,
                        char_width: 4
                    }, {
                        type: "static_text",
                        name: "End Number:",
                        width: 100,
                        height: 20
                    }, {
                        type: "edit_text",
                        item_id: "enum",
                        width: 50,
                        height: 20,
                        char_width: 4
                    }]
                }, {
                    type: "static_text",
                    name: "Step 2: Select Target Action:",
                    width: 400,
                    height: 20,
                    alignment: "align_center"
                }, {
                    type: "popup",
                    item_id: "actn",
                    width: 200,
                    height: 20
                }, {
                    type: "static_text",
                    name: "Step 3: Enter JavaScript Code",
                    width: 400,
                    height: 20,
                    alignment: "align_center"
                }, {
                    type: "edit_text",
                    item_id: "scpt",
                    width: 400,
                    height: 200,
                    multiline: true
                }, {
                    type: "cluster",
                    alignment: "align_right",
                    elements: [{
                        type: "ok_cancel",
                        ok_name: "OK",
                        cancel_name: "Cancel"
                    }]
                }]
            }]
        }
    };

    console.println("Before execDialog");
    var result = app.execDialog(dialog);
    console.println("After execDialog, result: " + result + ", dialog.results: " + JSON.stringify(dialog.results));

    if (result === "ok") {
        processDialogResults(dialog.results);
    } else {
        console.println("Dialog cancelled");
    }
}

function processDialogResults(results) {
    if (!results || typeof results !== "object") {
        app.alert("Error: No valid results from dialog.");
        return;
    }

    var fieldPrefix = results.fieldPrefix ? results.fieldPrefix.trim() : "";
    var fieldPrefixes = fieldPrefix ? [fieldPrefix] : [];
    var startNum = results.startNum || 0;
    var endNum = results.endNum || 0;
    var action = results.action ? results.action.trim() : "";
    var script = results.script || "";

    var validActions = ["Validate", "Calculate", "Keystroke", "Format", "Mouse Up", "Mouse Down", "Focus", "Blur"];
    var errorMessages = [];

    if (!fieldPrefix) {
        app.alert("Please select a Field Prefix.");
        return;
    }
    if (isNaN(startNum) || startNum < 1) {
        app.alert("Start Number must be a valid positive number.");
        return;
    }
    if (isNaN(endNum) || endNum < startNum) {
        app.alert("End Number must be a valid number greater than or equal to Start Number.");
        return;
    }
    if (!action || !validActions.includes(action)) {
        app.alert("Please select a valid Target Action: " + validActions.join(", "));
        return;
    }
    if (!script) {
        app.alert("JavaScript Code cannot be empty.");
        return;
    }

    var totalSuccessCount = 0;

    fieldPrefixes.forEach(function(prefix) {
        for (var i = startNum; i <= endNum; i++) {
            var fieldName = prefix + i; // "ProjectCode." + "1" -> "ProjectCode.1"
            var field = this.getField(fieldName);
            
            if (field) {
                try {
                    field.setAction(action, script);
                    totalSuccessCount++;
                } catch (e) {
                    errorMessages.push("Error setting script for " + fieldName + ": " + e);
                }
            } else {
                errorMessages.push("Field not found: " + fieldName);
            }
        }
    }, this);

    if (errorMessages.length) {
        app.alert("Some fields could not be updated:\n" + errorMessages.join("\n"));
    } else {
        app.alert("Scripts successfully applied to " + totalSuccessCount + " fields for prefix: " + fieldPrefix);
    }
}


 

2 replies

Bernd Alheit
Community Expert
Community Expert
February 24, 2025

What error do you get?

Hasan KOYUNCU
Inspiring
February 24, 2025

Pop-Up Message:

"Please select a Field Prefix."

Console Error Log:

Before execDialog
Dialog initialized
Commit function called
After execDialog, result: ok, dialog.results: {}

PDF Automation Station
Community Expert
Community Expert
February 24, 2025

Please provide an example of what you are entering into the item id "scpt" dialog field.

Hasan KOYUNCU
Inspiring
February 24, 2025

I extend my sincere gratitude for your prompt response to my query.

Consider, if you will, a Time Sheet, a document where each day of the month is meticulously recorded. Thirty-one fields, christened "Day1" through "Day31," stand ready to receive their due entries. I have devised a command, a concise yet potent invocation, "checkHolidays();," which, residing within a Document Level script, can be swiftly applied to these fields, nestled within a chosen tab of their Properties. A mere matter of seconds, and the task is accomplished. While this particular command is brief, the "sct" field can accommodate scripts of greater length and complexity.

To illustrate further, the manual entry of field names and their corresponding Property tabs yields flawless execution. However, my ambition extends beyond this manual approach. I yearn to automate the process, to create a script that intelligently discerns field names, presenting them in a user-friendly, selectable dropdown list. This list should not merely display the numerical identifiers that distinguish the fields (e.g., "1" from "Day1"), but rather the common prefix (e.g., "Day"). Furthermore, fields containing a period (e.g., "ProjectCode.1") should retain the prefix up to and including the period (e.g., "ProjectCode."). The numerical portion of the field name, however, will be entered manually into "Start Number" and "End Number" fields. Similarly, all functional tabs within the Properties should be available in a dropdown list for the "Target Action."

The script that performs admirably when field names and Target Action are entered manually is attached for your perusal.

// FormScriptUtility.js - Folder Level Script for Acrobat

app.addToolButton({
    cName: "FormScriptUtility",
    cLabel: "Set Form Scripts",
    cTooltext: "Set custom scripts for multiple form fields",
    cEnable: "event.rc = (app.doc != null);",
    cExec: "launchFormScriptUtility();",
    nPos: -1
});

function launchFormScriptUtility() {
    var dialog = {
        initialize: function(dialog) {
            dialog.load({
                "fpre": "",
                "snum": "",
                "enum": "",
                "actn": "",
                "scpt": ""
            });
        },
        commit: function(dialog) {
            var results = dialog.store();
            this.fieldPrefix = results["fpre"] || "";
            this.startNum = parseInt(results["snum"] || "0", 10);
            this.endNum = parseInt(results["enum"] || "0", 10);
            this.action = results["actn"] || "";
            this.script = results["scpt"] || "";
        },
        description: {
            name: "Set Form Scripts",
            elements: [
                {
                    type: "view",
                    width: 450,
                    height: 450,
                    elements: [
                        {
                            type: "static_text",
                            name: "Step 1: Enter Field Prefix and Range (e.g., Day, ProjectCode, OverTime; separate multiples with commas)",
                            width: 400,
                            height: 20,
                            alignment: "align_center"
                        },
                        {
                            type: "edit_text",
                            item_id: "fpre",
                            name: "Field Prefix:",
                            width: 200,
                            height: 20
                        },
                        {
                            type: "view",
                            align_children: "align_row",
                            elements: [
                                {
                                    type: "static_text",
                                    name: "Start Number:",
                                    width: 100,
                                    height: 20
                                },
                                {
                                    type: "edit_text",
                                    item_id: "snum",
                                    width: 50,
                                    height: 20,
                                    char_width: 4
                                },
                                {
                                    type: "static_text",
                                    name: "End Number:",
                                    width: 100,
                                    height: 20
                                },
                                {
                                    type: "edit_text",
                                    item_id: "enum",
                                    width: 50,
                                    height: 20,
                                    char_width: 4
                                }
                            ]
                        },
                        {
                            type: "static_text",
                            name: "Step 2: Enter Target Action (e.g., Validate, Calculate):",
                            width: 400,
                            height: 20,
                            alignment: "align_center"
                        },
                        {
                            type: "edit_text",
                            item_id: "actn",
                            width: 200,
                            height: 20
                        },
                        {
                            type: "static_text",
                            name: "Step 3: Enter JavaScript Code",
                            width: 400,
                            height: 20,
                            alignment: "align_center"
                        },
                        {
                            type: "edit_text",
                            item_id: "scpt",
                            width: 400,
                            height: 200,
                            multiline: true
                        },
                        {
                            type: "cluster",
                            alignment: "align_right",
                            elements: [
                                {
                                    type: "ok_cancel",
                                    ok_name: "OK",
                                    cancel_name: "Cancel"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    };

    if (app.execDialog(dialog) === "ok") {
        var fieldPrefix = dialog.fieldPrefix || "";
        var fieldPrefixes = fieldPrefix.split(",").map(function(p) { return p.trim(); }).filter(function(p) { return p; });
        var startNum = dialog.startNum;
        var endNum = dialog.endNum;
        var action = dialog.action || "";
        var script = dialog.script || "";

        if (fieldPrefixes.length === 0) {
            app.alert("Field Prefix cannot be empty.");
            return false;
        }
        if (isNaN(startNum) || startNum < 1) {
            app.alert("Start Number must be a valid positive number.");
            return false;
        }
        if (isNaN(endNum) || endNum < 1) {
            app.alert("End Number must be a valid positive number.");
            return false;
        }
        if (startNum > endNum) {
            app.alert("Start Number must be less than or equal to End Number.");
            return false;
        }
        if (!action) {
            app.alert("Please enter a valid Target Action (e.g., Validate, Calculate).");
            return false;
        }
        if (!script) {
            app.alert("JavaScript Code cannot be empty.");
            return false;
        }

        var validActions = ["Validate", "Calculate", "Keystroke", "Format", "Mouse Up", "Mouse Down", "Focus", "Blur"];
        if (validActions.indexOf(action) === -1) {
            app.alert("Invalid Target Action. Please use one of: " + validActions.join(", "));
            return false;
        }

        var totalSuccessCount = 0;
        var errorMessages = [];

        fieldPrefixes.forEach(function(prefix) {
            if (!prefix || typeof prefix !== "string") {
                errorMessages.push("Skipping invalid prefix: " + prefix);
                return;
            }
            var successCount = 0;
            for (var i = startNum; i <= endNum; i++) {
                var fieldName = prefix + (prefix.endsWith(".") ? "" : "") + i;
                var field = this.getField(fieldName);
                
                if (field) {
                    try {
                        field.setAction(action, script);
                        successCount++;
                    } catch (e) {
                        errorMessages.push("Error setting script for " + fieldName + ": " + e);
                    }
                } else {
                    errorMessages.push("Field not found: " + fieldName);
                }
            }
            totalSuccessCount += successCount;
        });

        if (errorMessages.length > 0) {
            app.alert("Some fields could not be updated:\n" + errorMessages.join("\n"));
            console.println("Operation completed with errors.");
        } else {
            app.alert("Scripts successfully applied to " + totalSuccessCount + " fields across prefixes: " + fieldPrefixes.join(", "));
            console.println("Operation completed successfully.");
        }
        return true;
    } else {
        console.println("Dialog cancelled or failed.");
        return false;
    }
}

function getField(name) {
    return this.getField(name);
}

 

PDF Automation Station
Community Expert
Community Expert
February 24, 2025

I asked you for an example of what you typed into the scpt field.