> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://docs.flokzu.com/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# Advanced Scripts

# Data Validation

### Validate an identity card's numbers

Some countries implement algorithms for validating identity document numbers. These algorithms can be reproduced in Javascript:
```javascript
function validateId(){
var ID = Flokzu.getFieldValue( [[Id Number]] ); 
var patron = /[\.\-]/ig; 
ID = ID.replace(patron, ""); 
var Coefs = [2,9,8,7,6,3,4,1]; 
var arrayID = ID.split( "" ); 
var Sum = 0;
var length = ID.length;
	for (i=0;i<length-1;i++){
	Sum = Sum + Coefs[i]*arrayID[i];
	}
	Sum = Sum + Coefs[7]*arrayID[length-1]; 	
		if ( (Sum % 10) != 0 ){
		swal({type : 'error' , title : 'Error!' , text: 'Alert: Incorrect Id'});
	}
}
Flokzu.onChange( [[Id Number]], validateId);
```

### Validate identity card's numbers for table fields

```javascript
function VerifyID(msg, data){
	var Array_CI = $(Flokzu.getAllColumnValues( [[Employee::Employee Id]] ));
	var Entries = ( Array_CI ).length;
	for(i=0; i<Entries; i++){
    	ID = Array_CI[i].innerText;
    	ID_Result = validateId(ID);
    	if(ID_Result == false){
        	Flokzu.error( [[Employee]] , "The number "+ID+" isn't valid." );
   		 swal({type : 'error' , title : 'Error!' , text: "The number "+ID+" isn't valid."});
   	 }
    }
}
Flokzu.onTableChange([[Employee::Employee Id]], VerifyID);
```

# Dates
### Calculate the Difference between two dates and show the result in days, months or years

```javascript
function ChangeDate(msg, data){

var Date1= dateFns.parse(Flokzu.getFieldValue([[Date1]]), 'yyyy/MM/dd', new Date());
var Date2= dateFns.parse(Flokzu.getFieldValue([[Date2]]), 'yyyy/MM/dd', new Date());
var years= dateFns.differenceInYears(Date2, Date1);


Date1= dateFns.addYears(Date1, years);
var months= dateFns.differenceInMonths(Date2,Date1);


Date1=dateFns.addMonths(Date1,months);
var days=dateFns.differenceInDays(Date2,Date1);



Flokzu.setFieldValue([[Days]], days);
Flokzu.setFieldValue([[Months]], months);
Flokzu.setFieldValue([[Years]], years);
}

Flokzu.onChange([[Date2]], ChangeDate);
Flokzu.onChange([[Date1]], ChangeDate);
```

||| IMPORTANT: The Date 1 field should be prior to the Date 2 field

# Identifier

Obtain the process instance identifier's number and insert it into a field

```javascript
function copyReference(){
   var x = $('#fkz_ref').text();
   x = x.substring(x.lastIndexOf('-') + 1)
   Flokzu.setFieldValue([[FIELD]] , x);
}

Flokzu.onInit(copyReference);
```

||| Valid for tasks different than the initial one (Launch Process) since the instance's Id isn't created at that point yet.

### Customize the identifier
For example, add the current year to the identifier "ABC-123" (2022-ABC-123):

```javascript
function identificador(){
    var id=Flokzu.getFieldValue([[Standard ID]])
    var num=id + "-" + dateFns.format(new Date(), 'yyyy')
    Flokzu.setFieldValue([[Custom ID]],num)
}
Flokzu.onInit(identificador);
```

# TABLES

### Iterate and copy cells's values from a table field into text a field

```javascript
function iteratecolumn(msg, data){   
  var rowCounter = 1;
    $( Flokzu.getAllColumnValues( [[Table::Column]] ) ).each(  
        function(){  
            var colValue = $(this).attr('value');
            if(rowCounter == 1){
                Flokzu.setFieldValue([[Field 1]],colValue);
            }else if (rowCounter == 2){
                Flokzu.setFieldValue([[Field 2]],colValue);
            }else if (rowCounter == 3){
                Flokzu.setFieldValue([[Field 3]],colValue);
            }
            rowCounter ++;
		}
	)
}
Flokzu.onAction(iteratecolumn);
```

Example:

```javascript
function iterateTable(msg, data){   
    $( Flokzu.getAllColumnValues( [[table::column]] ) ).each( 
        function(){  
            //Throw an alert with the value
            alert( $(this).attr('value') ); 
        }
    );   
}
Flokzu.onTableChange( [[table::column]] , iterateTable );
```

### Iterate a date-type column in a table and set a field with the minimum date from that column. 

```javascript
function TD1 Expiration(msg, data){ 
    Flokzu.setFieldValue([[Balance Valid Until]],''); 
    $( Flokzu.getAllColumnValues([[Balance::Balance Closing Date]])).each( 
        function(){  
            var date= moment($(this).attr('value'), "DD/MM/YYYY");
            var expiration= moment(Flokzu.getFieldValue([[Balance Valid Until]]), "DD/MM/YYYY");
            if(Flokzu.getFieldValue([[Balance Valid Until]])=='' || expiration.isBefore(date)){
                Flokzu.setFieldValue([[Balance Valid Until]],$(this).attr('value'));
 
            } else {
 
            }
        }
    );   
}
Flokzu.onTableChange([[Balance::Balance Closing Date]], TD1 Expiration);
```

# Others

### Buttons - Set a field as required according to a selected button

```javascript
function functionName(msg, button) {
  if (button == 'Delete') {
       Flokzu.setRequired([[Field]]);
    }
}

Flokzu.onAction(functionName);
```

### Sweet Alert with buttons and alert messages

```javascript
function sweetAlert() {
       var Field1= Flokzu.getFieldValue([[Field Name 1]]);
       var Field2= Flokzu.getFieldValue([[Field Name 2]]);
       if (Field1=="Yes" && Field2=="Yes"){
			
		    swal({
			  title: "Insert title here",
			  text: "insert text message here",
			  type: "warning",
			  showCancelButton: true,
			  confirmButtonColor: "#DD6B55", //Red confirm button
			  confirmButtonText: "Yes",
			  cancelButtonText: "No",
			  closeOnConfirm: false,
			  closeOnCancel: false
			},
			function(isConfirm){
			  if (isConfirm) {
				swal("Ok!", "insert message here", "success");
				} else {
				swal("Insert Title Here", "Insert message here" , "error");
			  }
			});
			

        }
}
Flokzu.onChange([[Field1]], sweetAlert);
Flokzu.onChange([[Field2]], sweetAlert); 
```

### Modify a number format, insert currency symbol or decimals

```javascript
const number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 €"

// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "￥123,457"

// limit to three Yesgnificant digits
console.log(new Intl.NumberFormat('en-IN', { maximumYesgnificantDigits: 3 }).format(number));
// expected output: "1,23,000"
```









