ตัวอย่างการดึงฐานข้อมูลมาแสดงเป็น select box โดยใช้ Bean Shell
- ใน Form Binder คลิก selectbox ที่ต้องการ
- Or Choose Options Binder เลือกเป็น Bean Shell Form Binder
- คลิก next จะเปลี่ยนไปหน้า Edit Select Box > Configure Bean Shell Form Binder > Advanced Options ให้นำ code ไปใส่ไว้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 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.apps.form.service.FormUtil; import org.joget.commons.util.LogUtil; public FormRowSet load(Element element, String primaryKey, FormData formData) { FormRowSet rows = new FormRowSet(); 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()) { String sql = "SELECT PROVINCE_ID AS value, TRIM(PROVINCE_NAME) AS label FROM province ORDER BY PROVINCE_NAME ASC" ; PreparedStatement stmt = con.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); FormRow option = new FormRow(); option.setProperty(FormUtil.PROPERTY_LABEL, "please select" ); //option.setProperty(FormUtil.PROPERTY_VALUE, (String) rs.getObject("value").toString()); rows.add(option); while (rs.next()) { FormRow option = new FormRow(); option.setProperty(FormUtil.PROPERTY_LABEL, (String) rs.getObject( "label" )); option.setProperty(FormUtil.PROPERTY_VALUE, (String) rs.getObject( "value" ).toString()); rows.add(option); } } } catch (Exception e) { LogUtil.error( "Sample app - Form 1" , e, "Form Options 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); |
การเซ็ต value ของ option บางครั้งต้องแปลง integer เป็น string ด้วย เช่น option.setProperty(FormUtil.PROPERTY_VALUE, (String) rs.getObject(“value”).toString());
About the author