CMDBuild Forum

Auto increment code attribute

Hi Community,

Is there a way to automatically raise the code field in numbers?
Of course I can use javascript to profide it with an auto value. But is there a way to read out the value of the previous record so that I can increase that value?

I would really appreciate it if you had an example to help me with.

Kind regards,

Frans Erich

The way that can be implemented would be the following:

first you will have to create a class called “counter” and inside you can use the “Description” attribute as a counter.
The following code must be added to the “Description” attribute to the auto value to obtain the id of said value to obtain it later.

//prints the element id to the console
console.log(api.record.id);

then in the attribute where you want to create the auto increment value, in the auto value section add the following code

// If the attribute you want to modify is called in another way, you replace the "Description"
if (api.getValue("Description") == null){
    // the getRemoteCard asks for two parameters, the name of the class that you created in the previous step and the value that the console.log gave you from the previous step
    api.getRemoteCard('counter', '######').then(function (rec) {
        // this refers to the Description attribute of the class you created in the previous step, if you called it something else replace
        let counterID= rec.get("Description");
        //this sets the value to the attribute you are wanting to increment. I particularly set it to show NC-2023-N01 but you can change it
        // basically new Date().getFullYear() returns the current year and String(parseInt(counterID) +1).padStart(2,"0")
        // Basically String(parseInt(counterID) +1).padStart(2,"0") converts the variable "counterID" to an integer, adds 1 to it, converts it back to a string and adds a 0 at the beginning so that it remains 01 and not 1 only
        api.setValue(`NC-${new Date().getFullYear()}-N${String(parseInt(counterID) +1).padStart(2,"0")}`);
    });
}

I clarify that in step one the console.log that will show the id once you create the first value, save it and edit it again, otherwise it shows you null.

The only thing that is missing is that the value of the counter class that was created at the beginning is updated, I did not get information to be able to update the value of an attribute of another class, if you get it I would appreciate it if you share it.
If I get it, I’ll share it with you here how to add it to this.
but it’s ok to start
The latter could be added to the properties of the class, in the form triggers section so that the value increases only if a new card is created, but as indicated before, I did not succeed.

PD: sorry for my english, i use google translator to translate the text from spanish to english

how do you create the counter class?