Walidator

Walidatory to komponenty użytkownika, umożliwiające sprawdzenie formularza podczas akceptacji zadania oraz zablokowanie akceptacji, gdy jakieś dane nie są prawidłowe. Przykładowe walidatory mogą np.

  • weryfikować, czy kwota została odpowiednio ustawiona
  • weryfikować, czy w zadaniu został dodany komentarz lub dokument.

Stworzone walidatory dostępne są w edytorze procesów i mogą być łatwo wykorzystane w procesie biznesowym umożliwiając tym samym realizacje logiki biznesowej. Ich zachowanie może być dodatkowo konfigurowane za pomocą parametrów. 

Definiowanie walidatora

Walidatory tworzone są w oparciu o ich definicję stworzoną przez użytkownika. Definicja taka musi zawierać następujące elementy:

  1. Adnotację  (jeżeli walidator nie jest definiowany we wtyczce, musi on pochodzić z pakietu com.suncode)
  2. Publiczną metodę oznaczoną adnotacją  z jednym parametrem
  3. Publiczną metodę o nazwie validate, która odpowiada za przeprowadzenie walidacji formularza.

Walidator może również dostarczać skrypt, który buduje wygląd parametrów podczas jego definiowania w PWE. W tym celu należy dodać kolejną adnotację dla klasy  z przekazaną ścieżką do skryptu (z classpath).

Przykładowa definicja przedstawiona jest poniżej:

@Validator
@ComponentsFormScript( "path/example-form.js" )
public class PeselValidator
{
    private final String PESEL_REGEX = "^\\d{11}$";
    
    @Define
    public void definition( ValidatorDefinitionBuilder builder )
    {
        builder
            .id( "pesel-validator" )
            .name( "validator.pesel" )
            .description( "validator.pesel.desc" )
            .category( Categories.TEST )
            .parameter()
                .id( "pesel_param" )
                .name( "validator.pesel.parameter.name" )
                .description( "validator.pesel.parameter.desc" )
                .type( Types.VARIABLE)
                .create();
    }
 
    //Metoda walidująca
    public void validate( @Param( value = "pesel_param" ) Variable pesel, ValidationErrors errors,
                          Translator translator )
    {
        boolean isPesel = Pattern.matches( PESEL_REGEX, (String) pesel.getValue() );
        if ( isPesel == false )
        {
            errors.add( translator.getMessage( "validator.pesel.invalid" ), pesel.getId() );
        }
    }
}

Implementacja funkcji walidującej

Walidator musi posiadać metodę walidującą o nazwie validate. Metoda może posiadać następujące typy parametrów:

  • pojedynczy parametr walidatora - typ parametru musi być zgodny ze zdefiniowanym typem oraz musi być poprzedzony adnotacją ,
  • parametr mapujący dwa parametry tablicowe (klucz, wartość) - typ parametru musi być typu java.util.Map<K,V>, gdzie K to zdefiniowany typ parametru komponentu będącego kluczem, a V to zdefiniowany typ parametru komponentu będącego wartością dla klucza. Parametr musi być oznaczony adnotacją  ze zdefiniowanymi właściwościami (key - id parametry będącego kluczem, value - id parametru będącego wartością).
  • pojedynczy parametr typu  oznaczony adnotacją  - jeżeli posiadamy taki typ, to wstrzyknięty zostanie obiekt DataSourceInstance na podstawie wartości tego parametru, która musi być id źródła danych.
  •  - zawiera wszystkie zdefiniowane parametry walidatora wraz z ich wartościami, jest to alternatywa dla pobierania parametru za pomocą wyżej wspomnianej adnotacji,
  •  - obiekt, w którym ustawiane są wszystkie błędy,
  •  - kontekst walidacji, można z niego odczytać identyfikator procesu i zadania, których dotyczy ta walidacja,
  •  - obiekt przechowujący zmienne formularza wraz z aktualnymi wartościami oraz identyfikator procesu i zadania; jest on w całości tylko do odczytu, nie ma możliwości zmiany wartości zmiennych,
  •  - zmienne kontekstowe dostępne w tym walidatorze. Więcej informacji tutaj,
  •  - translator dla tego komponentu, dzięki któremu wiadomości zwracane przez walidator mogą być tłumaczone. Więcej informacji tutaj,
  •  - obiekt zawierający informacje na temat użytkownika akceptującego zadanie.

W celu przerwania akceptacji zadania i wyświetlenia stosownego komunikatu należy dodać wiadomość do obiektu . Jeżeli żadna wiadomośc nie zostanie dodana, to akceptacja zadania przejdzie do kolejnego etapu.

Rejestracja walidatora we wtyczce

Jeżeli walidator jest definiowany we wtyczce to należy dodatkowo zaznaczyć, że wtyczka ta udostępnia komponenty. W tym celu należy w pliku suncode-plugin.xml dodać wpis:

<!-- Udostępnianie walidatorów --> 
<workflow-components key="components" />

Callback przy błędzie walidatora

Możliwe jest dodanie JavaScriptowej funkcji, która zostanie wywołana zamiast wyświetlenia okienka systemowego po zgłoszeniu błędu przez walidator.

Jeżeli przycisk posiada wiele walidatorów, na pierwszym miejscu zostają wyświetlone błędy (okienka z błędami, podkreślanie zmiennych itp.) pochodzące ze zwykłych błędów walidatorów, a w tym czasie walidatory, który zgłosiły wywołanie callbacka zostaną zignorowane. Jeżeli użytkownik pozbył się wszystkich standardowych błędów, każda kolejna akceptacja zadania wywoła tylko i wyłącznie jeden pojedynczy callback.

Aby dodać callback do komponentu, obok adnotacji  należy dodać adnotację  określającą ścieżkę do skryptu (znajdującego się w resources).

@Validator
@ValidatorsScript( value = "scripts/peselValidatorCallback.js" )
public class PeselValidator

Aby zgłosić callback na formularzu, należy wywołać invokeCallback .

public void validate( @Param( value = "param" ) Variable param, ValidationErrors errors )
    {
		//...
        if ( validatorFailed )
        {
            errors.invokeCallback();
        }
    }

Jeżeli walidator jednocześnie doda błędy oraz zgłosi wywołanie callbacka, błędy zostaną zignorowane przez serwer (zostanie wywołany JavaScriptowy callback). Jeżeli walidator nie posiada adnotacji , przy wywołaniu invokeCallback zostanie rzucony wyjątek.

 

Implementacja callbacka w JavaScripcie jest analogiczna do tworzenia skryptów Akcji.

PW.FormValidators.create('pesel-validator', {
    callback : function() {
        console.log('Pesel validator callback');
		if(ignorePesel) {
			this.confirm();
		}
    }
});

Pierwszy argument funkcji create musi być taki sam, jak id walidatora. Drugim argumentem jest obiekt implementujący metodę callback, która jest wywoływana przy dodaniu błędu w walidatorze.

Jeżeli chcemy zatwierdzić nasz walidator, żeby przepuścić akceptację dalej, musimy wywołać metodę walidatora this.confirm(). Jeżeli zostanie wywołane zatwierdzenie, to automatycznie zostanie wywołany callback kolejnego walidatoro (jeżeli taki będzie). W momencie, gdy wszystkie callbacki zostaną zatweirdzone, to nastąpi akceptacji z pominięciem tych walidatorów.

Przekazanie argumentu do callbacka

Funkcjonalność nie jest jeszcze dostępna.

Metoda invokeCallback pozwala przekazać dowolny obiekt, który następnie może być użyty przez skrypt po stronie przeglądarki. Obiekt ten zostanie skonwertowany do JSONa przez bibliotekę Jackson.

Przykładowe użycie:

Map<String, Object> exampleObject = new HashMap<String, Object>();
exampleObject.put( "prop1", "some text" );
exampleObject.put( "prop2", true );
exampleObject.put( "prop3", 23423 );

errors.invokeCallback( exampleObject );

Po stronie JavaScriptu:

callback : function(exampleObject) {
    console.log(exampleObject.prop1);
    console.log(exampleObject.prop2);
    console.log(exampleObject.prop3);
}

Komunikat błędu lub potwierdzenia walidacji

Możliwe jest określenie w PWE komunikatu błędu walidacji oraz komunikatu potwierdzenia akceptacji formularza pomimo błędu walidacji. Aby w PWE wyświetlone zostały te pola należy w builderze walidatora określić, jakie typy komunikatów mogą zostać skonfigurowane.

@Validator
public class PeselValidator
{
    private final String PESEL_REGEX = "^\\d{11}$";
    
    @Define
    public void definition( ValidatorDefinitionBuilder builder )
    {
        builder
            .id( "pesel-validator" )
            .name( "validator.pesel" )
            .description( "validator.pesel.desc" )
            .category( Categories.TEST )
            .messageTypes( ValidatorMessage.CONFIRMATION, ValidatorMessage.ERROR ) // możliwe będzie skonfigurowanie komunikatu potwierdzenia oraz błędu walidacji
            .parameter()
                .id( "pesel_param" )
                .name( "validator.pesel.parameter.name" )
                .description( "validator.pesel.parameter.desc" )
                .type( Types.VARIABLE)
                .create();
    }
 
    //Metoda walidująca
    public void validate( @Param( value = "pesel_param" ) Variable pesel, ValidationErrors errors,
                          Translator translator )
    {
        boolean isPesel = Pattern.matches( PESEL_REGEX, (String) pesel.getValue() );
        if ( isPesel == false )
        {
            errors.add( translator.getMessage( "validator.pesel.invalid" ), pesel.getId() );
        }
    }
}

Enum  określa, które z komunikatów mogą zostać skonfigurowane w PWE. Komunikaty te działają jak parametry typu String, a więc możliwe jest używanie w nich wartości zmiennych, funkcji itd.

W metodzie execute walidatora możliwe jest pobranie dwóch nowych obiektów:

  •  - obiekt przechowujący tytuł i tekst potwierdzenia
  •  - obiekt przechowujący tekst błędu

Obiekty te należy samemu dodać do błędów oraz potwierdzeń walidacji. Przykładowe użycie:

public void validate( @Param( value = "param" ) Variable param, ValidationErrors errors,
                      Translator translator, DefinedError error, DefinedConfirmation confirmation )
    {
        String value = param.getValue().toString();
        if ( /* warunek - błąd walidacji */ )
        {
            errors.add( error );
        }
        else if ( /* warunek - mimo błędu zapytanie o potwierdzenie akceptacji zadania */ )
        {
            errors.addConfirmation( confirmation );
        }
    }

 

Validator

Validators are user components that allow you to check a form when accepting a task and block acceptance when some data is not correct. Examples of validators can, for example.

  • verify that the amount has been set correctly
  • verify that a comment or document has been added to the task

The created validators are available in the process editor and can be easily used in a business process, thus enabling the execution of business logic. Their behavior can be further configured using parameters.

Defining a validator

Validators are created based on their definition created by the user. Such a definition must contain the following elements:

  1. Annotation (if the validator is not defined in the plugin, it must come from the com.suncode package)
  2. A public method annotated with  a single parameter
  3. A public method called validate, which is responsible for performing form validation.

The validator can also provide a script that builds the appearance of parameters when it is defined in the PWE. To do this, add another annotation for the class  with the path to the script passed in (from classpath).

An example definition is shown below:

@Validator
@ComponentsFormScript( "path/example-form.js" )
public class PeselValidator
{
    private final String PESEL_REGEX = "^\\d{11}$";
    
    @Define
    public void definition( ValidatorDefinitionBuilder builder )
    {
        builder
            .id( "pesel-validator" )
            .name( "validator.pesel" )
            .description( "validator.pesel.desc" )
            .category( Categories.TEST )
            .parameter()
                .id( "pesel_param" )
                .name( "validator.pesel.parameter.name" )
                .description( "validator.pesel.parameter.desc" )
                .type( Types.VARIABLE)
                .create();
    }
 
    //Metoda walidująca
    public void validate( @Param( value = "pesel_param" ) Variable pesel, ValidationErrors errors,
                          Translator translator )
    {
        boolean isPesel = Pattern.matches( PESEL_REGEX, (String) pesel.getValue() );
        if ( isPesel == false )
        {
            errors.add( translator.getMessage( "validator.pesel.invalid" ), pesel.getId() );
        }
    }
}

Validate function implementation

The validator must have a validating method named validate. The method can have the following parameter types:

  • a single validator parameter - the type of the parameter must be consistent with the defined type and must be preceded by an annotation ,
  • parameter mapping two array parameters (key, value) - the type of the parameter must be of type java.util.Map<K,V>, where K is the defined type of the component parameter being the key, and V is the defined type of the component parameter being the value for the key. The parameter must be annotated  with defined properties (key - id of the parameter being the key, value - id of the parameter being the value).
  • a single parameter of the type  marked with an annotation  -  if you have such a type, the DataSourceInstance object will be injected based on the value of this parameter, which must be the data source id.
  •  - contains all the defined validator parameters with their values, this is an alternative to retrieving a parameter using the above mentioned annotation,
  •  - object, in which all errors are set,
  •  - validation context, you can read from it the identifier of the process and task affected by this validation,
  •  - an object that stores the variables of the form with their current values and the process and task identifier; it is entirely read-only, it is not possible to change the values of the variables,
  •  - context variables available in this validator. More information here,
  •  - translator for this component, so that messages returned by the validator can be translated. More information here,
  •  - object containing information about the user accepting the task.

 

In order to stop acceptance of the task and display the appropriate message, add a message to the object . If no message is added, the task acceptance will proceed to the next stage.

Registration of the validator in the plugin

If the validator is defined in the plugin, then you need to additionally indicate that the plugin provides components. To do this, add an entry in the suncode-plugin.xml file:

<!-- Sharing validators --> 
<workflow-components key="components" />

Callback on validator error

It is possible to add a JavaScript function that will be called instead of displaying a system window when a validator reports an error.

If the button has multiple validators, the errors (error boxes, variable underlining, etc.) from the usual validator errors are displayed first, and at that time the validators that reported the callback will be ignored. If the user has gotten rid of all the standard errors, each subsequent acceptance of the task will only call one single callback.

To add a callback to a component, next to the annotation  add an annotation specifying the path to the script (located in resources).

@Validator
@ValidatorsScript( value = "scripts/peselValidatorCallback.js" )
public class PeselValidator

To report a callback on the form, call invokeCallback with .

public void validate( @Param( value = "param" ) Variable param, ValidationErrors errors )
    {
		//...
        if ( validatorFailed )
        {
            errors.invokeCallback();
        }
    }

If the validator simultaneously adds errors and reports a callback invocation, the errors will be ignored by the server (a JavaScript callback will be called). If the validator does not have annotation ,

an exception will be thrown when invokeCallback is called.

 

The implementation of callback in JavaScript is analogous to the creation of Actions scripts.

PW.FormValidators.create('pesel-validator', {
    callback : function() {
        console.log('Pesel validator callback');
		if(ignorePesel) {
			this.confirm();
		}
    }
});

The first argument of the create function must be the same as the id of the validator. The second argument is the object that implements the callback method, which is called when an error is added to the validator.

If you want to validate the validator to let the acceptance continue, you must call the validator method this.confirm(). If the validation is called, the callback of the next validator (if any) will automatically be called. Once all the callbacks have been validated, then the acceptance will happen, bypassing these validators.

Forwarding an argument to a callback

The functionality is not available yet.

The invokeCallback method allows you to forward any object, which can then be used by a browser-side script. This object will be converted to JSON by the Jackson library.

Example usage:

Map<String, Object> exampleObject = new HashMap<String, Object>();
exampleObject.put( "prop1", "some text" );
exampleObject.put( "prop2", true );
exampleObject.put( "prop3", 23423 );

errors.invokeCallback( exampleObject );

JavaScript side:

callback : function(exampleObject) {
    console.log(exampleObject.prop1);
    console.log(exampleObject.prop2);
    console.log(exampleObject.prop3);
}

Validation error or confirmation message

It is possible to specify in the PWE a validation error message and a form acceptance confirmation message despite the validation error. In order to display these fields in the PWE, you need to specify in the validator builder which types of messages can be configured.

@Validator
public class PeselValidator
{
    private final String PESEL_REGEX = "^\\d{11}$";
    
    @Define
    public void definition( ValidatorDefinitionBuilder builder )
    {
        builder
            .id( "pesel-validator" )
            .name( "validator.pesel" )
            .description( "validator.pesel.desc" )
            .category( Categories.TEST )
            .messageTypes( ValidatorMessage.CONFIRMATION, ValidatorMessage.ERROR ) // it will be possible to configure confirmation message and validation error
            .parameter()
                .id( "pesel_param" )
                .name( "validator.pesel.parameter.name" )
                .description( "validator.pesel.parameter.desc" )
                .type( Types.VARIABLE)
                .create();
    }
 
    //Metoda walidująca
    public void validate( @Param( value = "pesel_param" ) Variable pesel, ValidationErrors errors,
                          Translator translator )
    {
        boolean isPesel = Pattern.matches( PESEL_REGEX, (String) pesel.getValue() );
        if ( isPesel == false )
        {
            errors.add( translator.getMessage( "validator.pesel.invalid" ), pesel.getId() );
        }
    }
}

Enum  determines which messages can be configured in PWE. These messages act as parameters of String type, so it is possible to use values of variables, functions, etc. in them.

In the execute method of the validator, it is possible to retrieve two new objects:

  •  - object storing title and confirmation text
  •  - object storing the text of the error

These objects should be added to errors and validation confirmations. Example usage:

public void validate( @Param( value = "param" ) Variable param, ValidationErrors errors,
                      Translator translator, DefinedError error, DefinedConfirmation confirmation )
    {
        String value = param.getValue().toString();
        if ( /* condition - validation error */ )
        {
            errors.add( error );
        }
        else if ( /* condition - despite the error, asking for confirmation of task acceptance */ )
        {
            errors.addConfirmation( confirmation );
        }
    }