Versions Compared

Key

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

...

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);
					//we add break; so that it stops iterating after the first result is returned
                    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);

...