Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Usages

Use as Form Load Binder
Anchor
Form Load Binder
Form Load Binder

Injected Variables:

    • element - Element that this binder is tie to. (org.joget.apps.form.model.Element)

    • primaryKey - The primary key provided by the element to load data. (java.lang.String)

    • formData - The data holder of the whole form. (org.joget.apps.form.model.FormData)

Expected

...

Return Object:

    • An org.joget.apps.form.model.FormRowSet object which contains one org.joget.apps.form.model.FormRow object. 

...

Code Block
languagejava
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.joget.apps.app.service.AppUtil;
import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.commons.util.LogUtil;
  
public FormRowSet load(Element element, String username, FormData formData) { 
    FormRowSet rows = new FormRowSet();
    if (username != null && !username.isEmpty()) {
        Connection con = null;
        try {
            // retrieve connection from the default datasource
            DataSource ds = (DataSource)AppUtil.getApplicationContext().getBean("setupDataSource");
            con = ds.getConnection();
         
            // execute SQL query
            if(!con.isClosed()) {
                PreparedStatement stmt = con.prepareStatement("SELECT username, firstName, lastName, email from dir_user where username=?");
                stmt.setObject(1, username);
                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    FormRow row = new FormRow();
                    System.out.println(rs.getObject("username") );
                    row.setProperty("username", (rs.getObject("username") != null)?rs.getObject("username").toString():"");
                    row.setProperty("firstName", (rs.getObject("firstName") != null)?rs.getObject("firstName").toString():"");
                    row.setProperty("lastName", (rs.getObject("lastName") != null)?rs.getObject("lastName").toString():"");
                    row.setProperty("email", (rs.getObject("email") != null)?rs.getObject("email").toString():"");
                    
                    rows.add(row);
                    break;
                }
            }
        } catch(Exception e) {
            LogUtil.error("Sample app - Form 1", e, "Error loading user data in load binder");
        } finally {
            //always close the connection after used
            try {
                if(con != null) {
                    con.close();
                }
            } catch(SQLException e) {/* ignored */}
        }
    }
    return rows;
}
  
//call load method with injected variable
return load(element, primaryKey, formData);

...

    • element - Element that this binder is tie to. (org.joget.apps.form.model.Element)
    • primaryKey - The primary key provided by the element to load data. (java.lang.String)
    • formData - The data holder of the whole form. (org.joget.apps.form.model.FormData)

Expected

...

Return Object:

    • An org.joget.apps.form.model.FormRowSet object which contains one or more org.joget.apps.form.model.FormRow object. All FormRow objects are expected to have "value" and "label" property.

...

    • values - Dependency values of the controlling field. (java.lang.String[])

Expected

...

Return Object:

    • An org.joget.apps.form.model.FormRowSet object which contains one or more org.joget.apps.form.model.FormRow object. All FormRow objects are expected to have "value" and "label" property.

...

    • element - Element that this binder is tie to. (org.joget.apps.form.model.Element)
    • rows - Data to be store. Contains only one org.joget.apps.form.model.FormRow object. (org.joget.apps.form.model.FormRowSet)
    • formData - The data holder of the whole form. (org.joget.apps.form.model.FormData)

Expected

...

Return Object:

    • Same org.joget.apps.form.model.FormRowSet object which stored.

...

Do some calculation before storing the data using Workflow Form Binder.

Code Block
languagejava
 

 

Use as Form Validator

Injected Variables:

...

import java.text.DecimalFormat;
import org.joget.apps.app.service.AppUtil;
import org.joget.apps.form.model.Element

...

;
import org.joget.apps.form.model.FormData

...

Expected Outcome:

    • A boolean value to indicate the validation pass or fail.

Samples:

Compare the submitted value with the value of another field.

Code Block
languagejava
import java.util.Arrays;
import org.joget.apps.appform.servicemodel.AppUtilFormRow;
import org.joget.apps.form.model.ElementFormRowSet;
import org.joget.apps.form.model.FormFormStoreBinder;
import org.joget.appsplugin.formbase.model.FormDataPluginManager;
import org.joget.apps.form.service.FormUtil;

public booleanFormRowSet validatestore(Element element, FormDataFormRowSet formDatarows, String[]FormData valuesformData) {
    boolean result = true;

    //getcheck the fieldrows 1is valuenot fromempty formbefore datastore objectit
    Stringif field1Id(rows != "field1"; null && !rows.isEmpty()) {
    Form form = FormUtil.findRootForm(element);  //Get the submitted data
    Element field1    FormRow row = FormUtilrows.findElement(field1Id, form, formDataget(0);

    if (field1 != null) {
        //getString valueunitPrice of field 1= row.getProperty("unitPrice");
        String[] compareValuesunit = FormUtilrow.getElementPropertyValues(field1, formDatagetProperty("unit");

        //compare
 the value of  field 2 and fielddouble 1total are= equals0;
        if (!Arrays.equals(values, compareValues)) try {
            Stringdouble idprice = FormUtilDouble.getElementParameterNameparseDouble(elementunitPrice);
            formData.addFormError(id, "Value not equal!!!!"int unit = Integer.parseInt(unit);
            result = false;

         } 
  total = }price else* {unit;
        //ignore} if the field 1 not exist
catch (Exception e) {}
       } 

      return result; 
}

//callformat validatethe methodtotal withto injected2 variable
return validate(element, formData, values);

Use as Form Multi Row Load Binder

Injected Variables:

...

decimal
        DecimalFormat df = new DecimalFormat("#.00");
        row.setProperty("total", df.format(total));
    
        //Reuse Workflow Form Binder to store data
        PluginManager pluginManager = (PluginManager) AppUtil.getApplicationContext().getBean("pluginManager");
        FormStoreBinder binder = (FormStoreBinder) pluginManager.getPlugin("org.joget.apps.form.

...

lib.

...

WorkflowFormBinder");
        binder.store(element, rows, formData);
    }
    
    return rows;
}

//call store method with injected variable
return store(element, rows, formData);

Use as Form Validator

Injected Variables:

    • element - Element that this validator is tie to. (

Expected Return Object:

    • An org.joget.apps.form.model.FormRowSet object which contains one or more org.joget.apps.form.model.FormRow object. 

Samples:

Load default grid data from another table if current record does not have any grid data.

Code Block
 

 

Use as Form Multi Row Store Binder

Injected Variables:

    • Element)
    • values - The submitted values of the element. (java.lang.String[])
    • formData - The data holder of the whole formelement - Element that this binder is tie to. (org.joget.apps.form.model.ElementFormData)rows - Data to be store. Contains one or more org.

Expected Return Object:

    • A boolean value to indicate the validation pass or fail.

Samples:

Compare the submitted value with the value of another field.

Code Block
languagejava
import java.util.Arrays;
import org.joget.apps.

...

app.

...

service.AppUtil;
import org.joget.apps.form.model.

...

Element;
import org.joget.apps.form.model.

...

Expected Return Object:

...

Form;
import org.joget.apps.form.model.

...

Samples:

Create users based on the grid data.

Code Block
 

 

Use as Form Multi Row Validator

Injected Variables:

...

FormData;
import org.joget.apps.form.

...

service.FormUtil;

public boolean validate(Element element, FormData formData, String[] values) {
    boolean result = true;

    //get field 1 value from form data object
    String field1Id = "field1";
    Form form = FormUtil.findRootForm(element);
    Element field1 = FormUtil.findElement(field1Id, form, formData);

    if (field1 != null) {
        //get value of field 1
        String[] compareValues = FormUtil.getElementPropertyValues(field1, formData);

        //compare the value of field 2 and field 1 are equals
        if (!Arrays.equals(values, compareValues)) {
            String id = FormUtil.getElementParameterName(element);
            formData.addFormError(id, "Value not equal!!!!");
            result = false;
        } 
    } else {
        //ignore if the field 1 not exist
    }

    return result; 
}

//call validate method with injected variable
return validate(element, formData, values);

Use as Form Multi Row Load Binder

Injected Variables:

    • element - Element that this binder is tie to. (org.joget.apps.form.model.Element)
    • primaryKey - The primary key provided by the element to load data. (java.lang.String)
    • formData - The data holder of the whole form

Expected Return Object:

    • A boolean value to indicate the validation pass or fail.

Samples:

Validate the sum of a column values are less than 1000.

Code Block
 

 

Use as Form Permission

Injected Variables:

    • user - User object of current logged in user (org.joget.directory.model.User)
    • requestParams - Request parameters map of current HTTP Request (java.util.Map)

Expected Return Object:

    • A boolean value to indicate the user is authorized.

Samples:

Check the current user's username are same with the form field "creator" value. The following sample using Form Hash Variable to retrieve form field value.

Code Block
import java.util.Map;
import org.joget.directory.model.User;

public boolean isAuthorized(User user, Map params) { 
    //using hash variable to get "creator" field value and escapes it with java syntax, then compare with current username
    return "#form.crm_account.creator?java#".equals(user.getUsername());
}

//call isAuthorized method with injected variable
return isAuthorized(user, requestParams);

Use as Form Post Submission Processing Tool

Injected Variables:

    • workflowAssignment - The workflow activity assignment object of the saving form. Null when the form is not an assignment form. (org.joget.workflow.model.WorkflowAssignment)
    • pluginManager - Plugin Manager service bean for convenient usage. (org.joget.plugin.base.PluginManager)
    • appDef - App definition of the process. (org.joget.apps.appform.model.AppDefinitionFormData)
    • request - Http Request object of current Http Request. (javax.servlet.http.HttpServletRequest)

Expected Return Object:

    • None

Samples:

Reuse Email tool to send separate email to each users.

Code Block
 

 

Use as Process Participant

Injected Variables:

    • pluginManager - Plugin Manager service bean for convenient usage. (org.joget.plugin.base.PluginManager)
    • workflowActivity - Workflow Activity that trying to retrieves assignee. (org.joget.workflow.model.WorkflowActivity)

Expected Return Object:

    • A java.util.Collection of username in java.lang.String to be assign to the Workflow Activity.

Samples:

        Randomly assign an user in a department to a workflow activity.

Expected Return Object:

    • An org.joget.apps.form.model.FormRowSet object which contains one or more org.joget.apps.form.model.FormRow object. 

Samples:

Load default grid data from another table if current record does not have any grid data.

Code Block
import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet
Code Block
languagejava
import java.util.ArrayList;
import java.util.Collection;
import org.joget.apps.appform.service.AppUtilFormUtil;
import org.joget.directoryplugin.modelbase.UserPluginManager;
import org.joget.directory.model.service.ExtDirectoryManager;
import org.joget.workflowapps.form.model.WorkflowActivityFormLoadBinder;

public CollectionFormRowSet getAssignees(WorkflowActivity activityload(Element element, String primaryKey, FormData formData) { 
    CollectionString assigneesdefaultFormDefId = new ArrayList();
    
    ExtDirectoryManager directoryManager = (ExtDirectoryManager) pluginManager.getBean("directoryManager");"default_grid_entry"; //change this to the form id used to store default grid data
    
String formDefId =  String deptId = "D-005"grid_entry";
  //change this 
to the form id //Getused totalto userstore ingrid departmentdata
    LongString totalforeignKey = directoryManager.getTotalUsers(null, null, deptId, null, null, null, null); "fk"; //change this to the foreign key 
    
    //GetFormRowSet randomf number= from 0 to the total number of users in departmentnew FormRowSet();
    f.setMultiRow(true);

    // Reuse Multi Row Binder to load data
    intPluginManager randompluginManager = (intPluginManager) FormUtil.getApplicationContext(Math).randomgetBean("pluginManager") * total;
    FormLoadBinder binder = (FormLoadBinder) pluginManager.getPlugin("org.joget.plugin.enterprise.MultirowFormBinder");
    
    //GetLoad usersfrom usingthe directorygrid managertable
    Collection userList = directoryManager.getUsers(null, null, deptId, null, null, null, null, "firstName", false, random, 1);
    for(Object u : userList){binder.setProperty("formDefId", formDefId);
    binder.setProperty("foreignKey", foreignKey);
    f = binder.load(element, primaryKey, formData);
    
    User//if userno =grid (User) u;
        assignees.add(user.getUsername()data is retrieved, get from default table
    if (f == null || f.isEmpty()) {
        binder.setProperty("formDefId", defaultFormDefId);
    }
    
     return assignees;
}

//call getAssignees method with injected variable
return getAssignees(workflowActivity);

...

   //set the foreign key value to empty
        f = binder.load(element, "", formData);
    }
    return f;
}

//call load method with injected variable
return load(element, primaryKey, formData);

Use as Form Multi Row Store Binder

Injected Variables:

    • workflowAssignment - The workflow tool activity assignment objectelement - Element that this binder is tie to. (org.joget.apps.workflowform.model.WorkflowAssignmentElement)
    • pluginManager - Plugin Manager service bean for convenient usage. (rows - Data to be store. Contains one or more org.joget.apps.pluginform.base.PluginManager)appDef - App definition of the processmodel.FormRow object. (org.joget.apps.appform.model.AppDefinitionFormRowSet)
    • request - Http Request object of current HTTP Request. Not available if the tool is trigger by Deadline. (javax.servlet.http.HttpServletRequestformData - The data holder of the whole form. (org.joget.apps.form.model.FormData)

Expected Return Object:

...

    • Same org.joget.apps.form.model.FormRowSet object which stored.

Samples:

Start a new process in the same app with current record idBulk create users based on the grid data.

Code Block
languagejava
 

 

Use as Userview Permission

Injected Variables:

...

import java.util.HashSet;
import java.util.Set;
import org.joget.

...

apps.

...

app.service.AppUtil;
import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.commons.util.LogUtil;
import org.joget.commons.util.StringUtil;
import org.joget.directory.model.Role;
import org.joget.directory.model.User;
import org.joget.directory.dao.RoleDao;
import org.joget.directory.dao.UserDao;
import org.joget.directory.model.service.DirectoryUtil;
import org.joget.directory.model.service.UserSecurity;
 
public FormRowSet store(Element element, FormRowSet rows, FormData formData) {
    try {
        UserSecurity us = DirectoryUtil.getUserSecurity();
        RoleDao roleDao = (RoleDao) AppUtil.getApplicationContext().getBean("roleDao");
        UserDao userDao = (UserDao) AppUtil.getApplicationContext().getBean("userDao");
        
        for (FormRow row : rows) {
            //Get the submitted data for each grid row
            String username = row.getProperty("username");
            String firstName = row.getProperty("firstName");
            String lastName = row.getProperty("lastName");
            String email = row.getProperty("email");
            String password = row.getProperty("password");
            
            User user = new User();
            user.setId(username);
            user.setUsername(username);
            user.setTimeZone("0");
            user.setActive(1);
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setEmail(email);
            
            //Check if there is user security implementation, using it to encrypt password
            if (us != null) {
                user.setPassword(us.encryptPassword(username, password));
            } else {
                user.setPassword(StringUtil.md5Base16(password));
            }
            user.setConfirmPassword(password);
            
            //set user role
            Set roleSet = new HashSet();
            roleSet.add(roleDao.getRole("ROLE_USER"));
            user.setRoles(roleSet);
            
            userDao.addUser(user);
            if (us != null) {
                us.insertUserPostProcessing(user);
            }
        }
    } catch (Exception e) {
        LogUtil.error("Sample app - Bulk Create Users form", e, "Store user error!!");
    }
    return rows;
}
 
//call store method with injected variable
return store(element, rows, formData);

Use as Form Multi Row Validator

Injected Variables:

    • element - Element that this validator is tie to. (org.joget.apps.form.model.Element)
    • rows - Submitted data. Contains one or more org.joget.apps.form.model.FormRow object. (org.joget.apps.form.model.FormRowSet)
    • formData - The data holder of the whole form. (org.joget.apps.form.model.FormData)

Expected Return Object:

    • A boolean value to indicate the validation pass or fail.

Samples:

Validate the sum of a column values are less than 1000.

Code Block
import java.util.Arrays;
import org.joget.apps.app.service.AppUtil;
import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.Form;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.apps.form.service.FormUtil;
 
public boolean validate(Element element, FormRowSet rows, FormData formData) {
    boolean result = true;
    if (rows != null && !rows.isEmpty()) {
        int total = 0;
        
        //Sum the values from column "amount"
        for (FormRow row : rows) {
            try {
                int amount = Integer.parseInt(row.getProperty("amount"));
                total += amount;
            } catch (Exception e) {}
        }
        
        //if amount larger than 1000
        if (total > 1000) {
            String id = FormUtil.getElementParameterName(element);
            formData.addFormError(id, "Total amount should not larger than 1000!!!!");
            result = false;
        }
    }
 
    return result;
}
 
//call validate method with injected variable
return validate(element, rows, formData);

Use as Form Permission

Injected Variables:

    • user - User object of current logged in user (org.joget.directory.model.User)
    • requestParams - Request parameters map of current HTTP Request (java.util.Map)

Expected Return Object:

    • A boolean value to indicate the user is authorized.

Samples:

Check the current user's username are same with the form field "creator" value. The following sample using Form Hash Variable to retrieve form field value.

Code Block
import java.util.Map;
import org.joget.directory.model.User;

public boolean isAuthorized(User user, Map params) { 
    //using hash variable to get "creator" field value and escapes it with java syntax, then compare with current username
    return "#form.crm_account.creator?java#".equals(user.getUsername());
}

//call isAuthorized method with injected variable
return isAuthorized(user, requestParams);

Use as Form Post Submission Processing Tool

Injected Variables:

    • workflowAssignment - The workflow activity assignment object of the saving form. Null when the form is not an assignment form. (org.joget.workflow.model.WorkflowAssignment)
    • pluginManager - Plugin Manager service bean for convenient usage. (org.joget.plugin.base.PluginManager)
    • appDef - App definition of the process. (org.joget.apps.app.model.AppDefinition)
    • request - Http Request object of current Http Request. (javax.servlet.http.HttpServletRequest)

Expected Return Object:

    • None

Samples:

Reuse Email tool to send separate email to each users. The following script is for a form not mapped to workflow assignment, therefore workflowAssignment is not available.

Code Block
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.joget.apps.app.model.AppDefinition;
import org.joget.apps.app.service.AppPluginUtil;
import org.joget.apps.app.service.AppUtil;
import org.joget.plugin.base.ApplicationPlugin;
import org.joget.plugin.base.Plugin;
import org.joget.plugin.base.PluginManager;
import org.joget.plugin.property.model.PropertyEditable;
 
public Object execute(AppDefinition appDef, HttpServletRequest request) {
    String[] emails = new String[]{"test1@joget.org", "test2@joget.org"};
    
    //Reuse Email Tool to send separated email to a list of users;
    Plugin plugin = pluginManager.getPlugin("org.joget.apps.app.lib.EmailTool");
    
    //Get default properties (SMTP setting) for email tool
    Map propertiesMap = AppPluginUtil.getDefaultProperties(plugin, null, appDef, null);
    propertiesMap.put("pluginManager", pluginManager);
    propertiesMap.put("appDef", appDef);
    propertiesMap.put("request", request);
    
    ApplicationPlugin emailTool = (ApplicationPlugin) plugin;
    
    //send email
    for (String email : emails) {
        propertiesMap.put("toSpecific", email);
        propertiesMap.put("subject", "This is a test email for " + email);
        propertiesMap.put("message", "Email content for " + email);
        
        //set properties and execute the tool
        ((PropertyEditable) emailTool).setProperties(propertiesMap);
        emailTool.execute(propertiesMap);
    }
    
    return null;
}
 
//call execute method with injected variable
return execute(appDef, request);

Use as Process Participant

Injected Variables:

    • pluginManager - Plugin Manager service bean for convenient usage. (org.joget.plugin.base.PluginManager)
    • workflowActivity - Workflow Activity that trying to retrieves assignee. (org.joget.workflow.model.WorkflowActivity)

Expected Return Object:

    • A java.util.Collection of username in java.lang.String to be assign to the Workflow Activity.

Samples:

        Randomly assign an user in a department to a workflow activity.

Code Block
languagejava
import java.util.ArrayList;
import java.util.Collection;
import org.joget.apps.app.service.AppUtil;
import org.joget.directory.model.User;
import org.joget.directory.model.service.ExtDirectoryManager;
import org.joget.workflow.model.WorkflowActivity;

public Collection getAssignees(WorkflowActivity activity) { 
    Collection assignees = new ArrayList();
    
    ExtDirectoryManager directoryManager = (ExtDirectoryManager) pluginManager.getBean("directoryManager");
    
    String deptId = "D-005";
    
    //Get total user in department
    Long total = directoryManager.getTotalUsers(null, null, deptId, null, null, null, null);
    
    //Get random number from 0 to the total number of users in department
    int random = (int) (Math.random() * total);
    
    //Get users using directory manager
    Collection userList = directoryManager.getUsers(null, null, deptId, null, null, null, null, "firstName", false, random, 1);
    for(Object u : userList){
        User user = (User) u;
        assignees.add(user.getUsername());
    }
    
    return assignees;
}

//call getAssignees method with injected variable
return getAssignees(workflowActivity);

Use as Process Tool 
Anchor
Use as Process Tool
Use as Process Tool

Injected Variables:

    • workflowAssignment - The workflow tool activity assignment object. (org.joget.workflow.model.WorkflowAssignment)
    • pluginManager - Plugin Manager service bean for convenient usage. (org.joget.plugin.base.PluginManager)
    • appDef - App definition of the process. (org.joget.apps.app.model.AppDefinition)
    • request - Http Request object of current HTTP Request. Not available if the tool is trigger by Deadline. (javax.servlet.http.HttpServletRequest)

Expected Return Object:

    • None

Samples:

Start a new process in the same app with current record id.

Code Block
languagejava
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.joget.apps.app.model.AppDefinition;
import org.joget.apps.app.service.AppService;
import org.joget.apps.app.service.AppUtil;
import org.joget.workflow.model.service.WorkflowManager;
import org.joget.workflow.model.WorkflowAssignment;
import org.joget.workflow.model.WorkflowProcess;
 
public Object execute(WorkflowAssignment assignment, AppDefinition appDef, HttpServletRequest request) {
    AppService appService = (AppService) AppUtil.getApplicationContext().getBean("appService");
    WorkflowManager workflowManager = (WorkflowManager) AppUtil.getApplicationContext().getBean("workflowManager");
    
    //get current record id
    String recordId = appService.getOriginProcessId(assignment.getProcessId());
    
    //get process
    WorkflowProcess process = appService.getWorkflowProcessForApp(appDef.getAppId(), appDef.getVersion().toString(), "process2");
    
    //start process
    workflowManager.processStart(process.getId(), null, null, null, recordId, false);
    
    return null;
}
 
//call execute method with injected variable
return execute(workflowAssignment, appDef, request);

Use as Userview Permission

Injected Variables:

    • user - User object of current logged in user (org.joget.directory.model.User)
    • requestParams - Request parameters map of current HTTP Request (java.util.Map)

Expected Return Object:

    • A boolean value to indicate the user is authorized.

Samples:

Check the user is in a group and is an admin user.

Code Block
languagejava
import java.util.Collection;
import java.util.Map;
import org.joget.apps.app.service.AppUtil;
import org.joget.directory.model.Group;
import org.joget.directory.model.User;
import org.joget.directory.model.service.ExtDirectoryManager;
import org.joget.workflow.model.service.WorkflowUserManager;
import org.joget.workflow.util.WorkflowUtil;
public boolean isAuthorized(User user, Map params) { 
    //if no logged in user
    if (user == null) {
        return false;
    }
    //check current user is admin
    boolean isAdmin = WorkflowUtil.isCurrentUserInRole(WorkflowUserManager.ROLE_ADMIN);
    
    //check current user is in group "G-001"
    boolean inGroup = false;
    
    ExtDirectoryManager directoryManager = (ExtDirectoryManager) AppUtil.getApplicationContext().getBean("directoryManager");
    Collection groups = directoryManager.getGroupByUsername(user.getUsername());
    if (groups != null) {
        String groupId = "G-001";
        for (Group g : groups) {
            if (groupId.equals(g.getId())) {
                inGroup = true;
            }
        }
    }
    
    return isAdmin && inGroup;
}
  
//call isAuthorized method with injected variable
return isAuthorized(user, requestParams);

Best Practices

1. Only import classes that are needed

Do not use wildcard in import statement. It giving a very bad performance in Bean Shell interpreter to search the whole package and loads it in memory.

Don't:

Code Block
languagejava
import java.util.*;

Do:

Code Block
languagejava
import java.util.Collection;

2. Do not need to mention the type of element of a collections

Bean Shell interpreter cannot recognise the element type syntax of collections class like Collection, Map, List, Set and etc.

Don't:

Code Block
languagejava
Map<String, String> map = new HashMap<String, String>();

Do:

Code Block
languagejava
Map map = new HashMap();

3. Indents your script nicely and

Expected Return Object:

    • A boolean value to indicate the user is authorized.

Samples:

Check the user is in a group and is an admin user.

Code Block
languagejava
 

 

Best Practices

1. Only import classes that are needed

Do not use wildcard in import statement. It giving a very bad performance in Bean Shell interpreter to search the whole package and loads it in memory.

Don't:

Code Block
languagejava
import java.util.*;

Do:

Code Block
languagejava
import java.util.Collection;

2. Do not need to mention the type of element of a collections

Bean Shell interpreter cannot recognise the element type syntax of collections class like Collection, Map, List, Set and etc.

Don't:

Code Block
languagejava
Map<String, String> map = new HashMap<String, String>();

Do:

Code Block
languagejava
Map map = new HashMap();

3. Indents your script nicely and follows the Java Code Conventions

...

Code Block
languagejava
try {
    //do something
} catch (Exception e) {
    LogUtil.error("CRM app - Backend userview", e, "Error retrieving user department in Report category permission");
}

7. Consider to make it as a plugin instead of using Bean Shell

 {
    //do something
} catch (Exception e) {
    LogUtil.error("CRM app - Backend userview", e, "Error retrieving user department in Report category permission");
}

7. Consider to make it as a plugin instead of using Bean Shell

If your script need to reuse for multiple times in an app or can be used by others app in future development, please consider to make your Bean Shell script as a plugin instead of copy and paste it multiple times across your app. Bean Shell script is harder to maintain in this case. Imagine that you want to make a change, you will have to update all the places that are using the same script as well. Beside that, a normal plugin implementation will have better performance than a script running by a Bean Shell interpreter.

8. Reuse existing plugins in your code to make it cleaner and easy to maintain

If partial of your script can be done by existing plugins in Joget Workflow, you can reuse the plugin in stead of writting it again. 

To reuse a plugin, you can retrieve the plugin using PluginManager, then set it properties and execute it.

Example: 

  1. Reuse Multi Row Binder plugin to load data
  2. Reuse Email Tool to send email

 If your script need to reuse for multiple times in an app or can be used by others app in future development, please consider to make your Bean Shell script as a plugin instead of copy and paste it multiple times across your app. Bean Shell script is harder to maintain in this case. Imagine that you want to make a change, you will have to update all the places that are using the same script as well. Beside that, a normal plugin implementation will have better performance than a script running by a Bean Shell interpreter.

More samples

Children Display