Help Needed: Acrobat Folder Level Scripting Error
Copy link to clipboard
Copied
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);
}
}
Copy link to clipboard
Copied
Please provide an example of what you are entering into the item id "scpt" dialog field.
Copy link to clipboard
Copied
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);
}
Copy link to clipboard
Copied
I asked you for an example of what you typed into the scpt field.
Copy link to clipboard
Copied
checkHolidays();
Copy link to clipboard
Copied
There's no such method in the code you posted.
Edited: Sorry, I see now that's the code you applied, not the one you called.
Also, you should get rid of the getField function you declared. It serves no purpose and can conflict with the existing one that already exists with that name. If you want a utility function that returns a field give it a unique name.
Copy link to clipboard
Copied
What error do you get?
Copy link to clipboard
Copied
Pop-Up Message:
"Please select a Field Prefix."
Console Error Log:
Before execDialog
Dialog initialized
Commit function called
After execDialog, result: ok, dialog.results: {}
Copy link to clipboard
Copied
Here screenshoot.
Copy link to clipboard
Copied
Your video does not show that the error popup and shows that it worked.
Copy link to clipboard
Copied
In fact, it shows the script working just fine... You specified that the Calculate event should be set, and that's what it showed. What did you want to achieve, if not that?
Copy link to clipboard
Copied
Having replaced the manual entry fields in Step 1 and Step 3 with dropdown lists, a new affliction has manifested itself, this time in the form of an error.
Attached screen shot.
Copy link to clipboard
Copied
These lines of code are producing the popup because fieldPrefix is not defined properly anywhere before it in the script.
if (!fieldPrefix) {
app.alert("Please select a Field Prefix.");
Copy link to clipboard
Copied
It's very hard to help you without seeing the actual code. Each time you update it and get an error you have to share it for further help.
Copy link to clipboard
Copied
Automating Script Injection in Acrobat Forms
When working with Acrobat forms, manually adding scripts to multiple fields (e.g., buttons, drop-down lists) via the properties tab can be tedious. To streamline this, I created a utility that automates script injection at the folder level.
How It Works:
- Select a field series and apply a script to all in seconds.
- Instead of manually setting properties for each field, this tool does it in bulk.
Current Features:
- Manually input the target field name.
- Define start and end numbers for field series.
- Enter the target action manually.
- Paste the script and apply it across selected fields instantly.
Planned Improvement:
I aimed to use drop-downs for field selection and target actions but haven’t implemented them yet.
Would love feedback and suggestions!
Attached is the semi-automatic script that I still use.
// 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);
}

