Assign a unique id to OFORMS

24 January 2023 By Serge 0 49

ONLYOFFICE products allow us to effortlessly create and operate with fillable forms. In our previous post, we showed you a macro that converts CSV/TXT data into a fillable combo box.

This time, we will make electronic documentation more organized by building a macro that assigns a unique id to a fillable form.

Assign a unique id to OFORMS


In our new project, we will implement a similar concept we used with the macro mentioned above.

The macro code is the following:

With a new macro, we will also incorporate the InsertContent method. It inserts an element right where the cursor is positioned. However, this time, the inserted content is different.

Building the macro

To create this content, we add the generate function. There we create the key variable and set it to blank. Later on, it will store the generated value. Also, we add the data variable. It contains uppercase and lowercase letters and numbers. Those are the building blocks of our unique id:

Then we add a for loop which performs 12 iterations. Each iteration returns a unique value. So 12 iterations produce 12 unique characters for the id. Then we use the Math.random method to get a unique index at each iteration. After that, we use this index with the charAt method to retrieve a unique character from the data variable. We assign the result to the key variable and return it for further use. Then we invoke the generate function and assign it to the id variable:

Now we need to insert the generated content into our document. First, we target the active form:

After that, we create a paragraph and add a text element to it. We wrap our generated content in this element by passing the id variable in the parameters:

Then we insert it. The InsertContent method embeds an element right at the cursor position. We also specify the KeepTextOnly property. By setting it to true we can prevent any possible positioning issues:

The entire macro code is the following:

Now, let’s run our macro and see how it works!

We hope you will find this macro useful and incorporate it into your workflow. ONLYOFFICE macros are extremely versatile and allow users to manipulate documents in various ways. This macro is just one of the many examples of what can be achieved by implementing our API methods.

We kindly encourage you to experiment and embark on your own projects. Don’t hesitate to ask questions or share your ideas with us. We are open to discussion and cooperation. Best of luck in your exploratory endeavors!

Add a comment