Tag Archive value

joget: Bean Shell Form Binder

ตัวอย่างการใช้ bean shell ดึงค่าจาก database มาแสดง

สร้าง table app_fd_prototype โดยใช้

--
-- Table structure for table `app_fd_prototype`
--

CREATE TABLE `app_fd_prototype` (
`id` varchar(255) NOT NULL,
`dateCreated` datetime DEFAULT NULL,
`dateModified` datetime DEFAULT NULL,
`c_Checkbox` longtext NOT NULL,
`c_DatePicker` longtext NOT NULL,
`c_FileUpload` longtext NOT NULL,
`c_HiddenField` longtext NOT NULL,
`c_PasswordField` longtext NOT NULL,
`c_Radio` longtext NOT NULL,
`c_SelectBox` longtext NOT NULL,
`c_TextArea` longtext NOT NULL,
`c_TextField` longtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `app_fd_prototype`
--

INSERT INTO `app_fd_prototype` (`id`, `dateCreated`, `dateModified`, `c_Checkbox`, `c_DatePicker`, `c_FileUpload`, `c_HiddenField`, `c_PasswordField`, `c_Radio`, `c_SelectBox`, `c_TextArea`, `c_TextField`) VALUES
('399895e8-ac15e1b1-2ddac962-1ca1ea8b', '2017-10-02 00:00:00', '2017-10-27 00:00:00', 'permanent', '10/09/2017', '04a972cda3440360b437a67d3a0dbb9d.jpg ', 'HiddenField	', 'PasswordField', 'male', 'programmer', 'โปรแกรมเมอร์ธรรมดาที่อยากเขียนสิ่งที่ไม่ธรรมดา ลูกค้า ผู้ชมเข้ามาดูต้องบอกว่า ดี แจ๋ง ง่าย แต่คนเขียนต้องไม่ลำบากกับชีวิต', 'pitt phunsanit');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `app_fd_prototype`
--
ALTER TABLE `app_fd_prototype`
ADD PRIMARY KEY (`id`);
COMMIT;

สร้างฟอร์มโดยใช้

{"className":"org.joget.apps.form.model.Form","properties":{"id":"BeanShellFormBinder","loadBinder":{"className":"org.joget.apps.form.lib.BeanShellFormBinder","properties":{"useAjax":"","script":"import java.sql.Connection;\r\nimport java.sql.PreparedStatement;\r\nimport java.sql.ResultSet;\r\nimport java.sql.SQLException;\r\nimport javax.sql.DataSource;\r\nimport org.joget.apps.app.service.AppUtil;\r\nimport org.joget.apps.form.model.Element;\r\nimport org.joget.apps.form.model.FormData;\r\nimport org.joget.apps.form.model.FormRow;\r\nimport org.joget.apps.form.model.FormRowSet;\r\nimport org.joget.commons.util.LogUtil;\r\n\r\npublic FormRowSet load(Element element, String primaryKey, FormData formData) {\r\n    FormRowSet rows = new FormRowSet();\r\n    if (primaryKey != null && !primaryKey.isEmpty()) {\r\n        Connection con = null;\r\n        try {\r\n            \/*retrieve connection from the default datasource*\/\r\n            DataSource ds = (DataSource)AppUtil.getApplicationContext().getBean(\"setupDataSource\");\r\n            con = ds.getConnection();\r\n\r\n            \/*execute SQL query*\/\r\n            if(!con.isClosed()) {\r\n                String sql = \"SELECT c_Checkbox, c_DatePicker, c_FileUpload, c_HiddenField, c_PasswordField, c_Radio, c_SelectBox, c_TextArea, c_TextField FROM app_fd_prototype WHERE id = ?\";\r\n                PreparedStatement stmt = con.prepareStatement(sql);\r\n                stmt.setObject(1, primaryKey);\r\n\r\n                ResultSet rs = stmt.executeQuery();\r\n                while (rs.next()) {\r\n                    FormRow row = new FormRow();\r\n \r\n                System.out.println(rs.getObject(\"c_Checkbox\"));\r\n\r\n                    row.put(\"Checkbox\", (rs.getObject(\"c_Checkbox\") != null) ? rs.getObject(\"c_Checkbox\").toString() : \"\");\r\n                    row.put(\"DatePicker\", (rs.getObject(\"c_DatePicker\") != null) ? rs.getObject(\"c_DatePicker\").toString() : \"\");\r\n                    row.put(\"FileUpload\", (rs.getObject(\"c_FileUpload\") != null) ? rs.getObject(\"c_FileUpload\").toString() : \"\");\r\n                    row.put(\"HiddenField\", (rs.getObject(\"c_HiddenField\") != null) ? rs.getObject(\"c_HiddenField\").toString() : \"\");\r\n                    row.put(\"PasswordField\", (rs.getObject(\"c_PasswordField\") != null) ? rs.getObject(\"c_PasswordField\").toString() : \"\");\r\n                    row.put(\"Radio\", (rs.getObject(\"c_Radio\") != null) ? rs.getObject(\"c_Radio\").toString() : \"\");\r\n                    row.put(\"SelectBox\", (rs.getObject(\"c_SelectBox\") != null) ? rs.getObject(\"c_SelectBox\").toString() : \"\");\r\n                    row.put(\"TextArea\", (rs.getObject(\"c_TextArea\") != null) ? rs.getObject(\"c_TextArea\").toString() : \"\");\r\n                    row.put(\"TextField\", (rs.getObject(\"c_TextField\") != null) ? rs.getObject(\"c_TextField\").toString() : \"\");\r\n \r\n                    rows.add(row);\r\n                    break;\r\n                }\r\n            }\r\n        } catch(Exception e) {\r\n            LogUtil.error(\"Sample app - Form 1\", e, \"Error loading user data in load binder\");\r\n        } finally {\r\n            \/*always close the connection after used*\/\r\n            try {\r\n                if(con != null) {\r\n                    con.close();\r\n                }\r\n            } catch(SQLException e) {\/*ignored*\/}\r\n        }\r\n    }\r\n    return rows;\r\n}\r\n \r\n\/*call load method with injected variable*\/\r\nreturn load(element, primaryKey, formData);"}},"description":"","tableName":"prototype","postProcessorRunOn":"both","name":"Bean Shell Form Binder","postProcessor":{"className":"","properties":{}},"storeBinder":{"className":"","properties":{}},"permission":{"className":"","properties":{}},"noPermissionMessage":""},"elements":[{"elements":[{"elements":[{"className":"org.joget.apps.form.lib.CheckBox","properties":{"id":"Checkbox","workflowVariable":"","readonlyLabel":"","optionsBinder":{"className":"","properties":{}},"validator":{"className":"","properties":{}},"controlField":"","value":"","label":"Checkbox","readonly":"","options":[{"grouping":"","value":"freelance","label":"freelance"},{"grouping":"","value":"permanent","label":"permanent"}]}},{"className":"org.joget.apps.form.lib.DatePicker","properties":{"readonlyLabel":"","validator":{"className":"","properties":{}},"endDateFieldId":"","label":"Date Picker","format":"","startDateFieldId":"","allowManual":"","id":"DatePicker","workflowVariable":"","value":"","dataFormat":"","readonly":"","yearRange":"c-10:c+10","currentDateAs":""}},{"className":"org.joget.apps.form.lib.FileUpload","properties":{"id":"FileUpload","fileType":"","validator":{"className":"","properties":{}},"label":"FileUpload","attachment":"","readonly":"","multiple":"","permissionType":"","fileTypeMsg":"Invalid file type","maxSizeMsg":"File size limit exceeded","maxSize":"","size":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"HiddenField","workflowVariable":"","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.PasswordField","properties":{"id":"TextField","readonlyLabel":"","maxlength":"","validator":{"className":"","properties":{}},"value":"","label":"TextField","readonly":"","size":""}},{"className":"org.joget.apps.form.lib.Radio","properties":{"id":"Radio","workflowVariable":"","readonlyLabel":"","optionsBinder":{"className":"","properties":{}},"validator":{"className":"","properties":{}},"controlField":"","value":"","label":"Radio","readonly":"","options":[{"grouping":"","value":
"female","label":"female"},{"grouping":"","value":"male","label":"male"}]}},{"className":"org.joget.apps.form.lib.SelectBox","properties":{"id":"SelectBox","readonlyLabel":"","workflowVariable":"","optionsBinder":{"className":"","properties":{}},"validator":{"className":"","properties":{}},"value":"","controlField":"","label":"SelectBox","multiple":"","readonly":"","options":[{"grouping":"","value":"programmer","label":"programmer"},{"grouping":"","value":"tester","label":"tester"}],"size":""}},{"className":"org.joget.apps.form.lib.TextArea","properties":{"id":"TextArea","cols":"20","readonlyLabel":"","workflowVariable":"","validator":{"className":"","properties":{}},"value":"","label":"TextArea","readonly":"","rows":"5"}},{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"TextField","readonlyLabel":"","workflowVariable":"","maxlength":"","encryption":"","validator":{"className":"","properties":{}},"value":"","label":"TextField","readonly":"","size":""}}],"className":"org.joget.apps.form.model.Column","properties":{"width":"100%"}}],"className":"org.joget.apps.form.model.Section","properties":{"id":"section1","label":"Section"}}]}

ใส่ Edit Form > Advanced > Configure Bean Shell Form Binder

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 primaryKey, FormData formData) {
FormRowSet rows = new FormRowSet();
if (primaryKey != null && !primaryKey.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()) {
String sql = "SELECT c_Checkbox, c_DatePicker, c_FileUpload, c_HiddenField, c_PasswordField, c_Radio, c_SelectBox, c_TextArea, c_TextField FROM app_fd_prototype WHERE id = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setObject(1, primaryKey);

ResultSet rs = stmt.executeQuery();
while (rs.next()) {
FormRow row = new FormRow();

System.out.println(rs.getObject("c_Checkbox"));

row.put("Checkbox", (rs.getObject("c_Checkbox") != null) ? rs.getObject("c_Checkbox").toString() : "");
row.put("DatePicker", (rs.getObject("c_DatePicker") != null) ? rs.getObject("c_DatePicker").toString() : "");
row.put("FileUpload", (rs.getObject("c_FileUpload") != null) ? rs.getObject("c_FileUpload").toString() : "");
row.put("HiddenField", (rs.getObject("c_HiddenField") != null) ? rs.getObject("c_HiddenField").toString() : "");
row.put("PasswordField", (rs.getObject("c_PasswordField") != null) ? rs.getObject("c_PasswordField").toString() : "");
row.put("Radio", (rs.getObject("c_Radio") != null) ? rs.getObject("c_Radio").toString() : "");
row.put("SelectBox", (rs.getObject("c_SelectBox") != null) ? rs.getObject("c_SelectBox").toString() : "");
row.put("TextArea", (rs.getObject("c_TextArea") != null) ? rs.getObject("c_TextArea").toString() : "");
row.put("TextField", (rs.getObject("c_TextField") != null) ? rs.getObject("c_TextField").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);

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)

jQuery: upload แบบ ajax

ตัวอย่างการใช้ jQuery upload ไฟล์แบบ ajax

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>jQuery: form > send file</title>
    <link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <style>
        .progressbar {
            background: #c00000;
            clear: both;
            height: 10px;
            width: 0;
        }

        .progressLoaded {
            width: 50px;
        }

        .progressLoaded::after {
            content: " bytes";
        }

        .progressPercent {
            width: 50px;
        }

        .progressPercent::after {
            content: " %";
        }

        .progressTotal {
            float: left;
            width: 50px;
        }

        .progressTotal::after {
            content: " bytes";
        }

        .progressTotal::before {
            content: " of ";
        }
    </style>
</head>

<body>
    <h1>upload file with ajax</h1>
    <form action="values.php" class="form-horizontal" enctype="multipart/form-data" id="formA" method="post">
        <div class="form-group">
            <label class="col-sm-2 control-label" for="socialidI">หมายเลขบัตรประชาชน</label>
            <div class="col-sm-10">
                <input class="form-control" id="socialidI" maxlength="13" name="socialid" placeholder="หมายเลขบัตรประชาชน" type="number">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label" for="photoI">ภาพถ่าย</label>
            <div class="col-sm-10">
                <input class="form-control" id="photoI" name="photo" placeholder="upload file" type="file">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-10 text-right">
                <button type="submit" class="btn btn-success">ส่งข้อมูล</button>
            </div>
        </div>
    </form>
    <div class="col-sm-12">
        <h4>Progress</h4>
        <div class="progressLoaded"></div>
        <div class="progressTotal"></div>
        <div class="progressPercent"></div>
        <div class="progressbar"></div>
    </div>
    <div class="col-sm-12" id="resultA"></div>
    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script>
        function xhrProgress(xhr) {
            if (xhr.upload) {
                // For handling the progress of the upload
                xhr.upload.addEventListener('progress', function (e) {
                    if (e.lengthComputable) {
                        $('.progressTotal').html(e.total);
                        $('.progressLoaded').html(e.loaded);

                        percentComplete = parseInt((e.loaded / e.total * 100), 10);
                        $('.progressPercent').html(percentComplete);
                        $('.progressbar').css("width", percentComplete + '%');
                    }
                }, false);
            }
            return xhr;
        }

        $(function () {

            var formA = $('#formA');

            formA.submit(function (event) {
                event.preventDefault();

                $.ajax({
                    "beforeSend": function (jqXHR, settings) {
                        /* แยกตัวแปรไว้ตรวจสอบข้อมูล */
                        var params = settings.data;

                        if (settings.data.get('socialid') == '') {

                            jqXHR.abort();
                            alert('กรุณากรอกหมายเลขบัตรประชาชน');

                            return false;
                        }

                        if (settings.data.get('photo').name == '') {

                            jqXHR.abort();
                            alert('กรุณาอัพโหลดรูปภาพ');

                            return false;
                        }

                    },
                    "contentType": false,
                    "data": new FormData(formA[0]),
                    "method": "POST",
                    "processData": false,
                    "success": function (data, textStatus, jqXHR) {
                        $('#resultA').html(data);
                    },
                    "url": "values.php",
                    "xhr": function () {
                        return xhrProgress($.ajaxSettings.xhr());
                    },

                });

            });

        });
    </script>
</body>

</html>

ไฟล์ที่รอรับข้อมูล

<?php
echo 'FILE<pre>', print_r($_FILES, true), '</pre>';
echo 'GET<pre>', print_r($_GET, true), '</pre>';
echo 'POST<pre>', print_r($_POST, true), '</pre>';

วิธีนี้ใช้ความสามารถใหม่ FormData ที่ใช้กับ browser เก่าแก่กว่า Internet Explorer 10 หรือ Edge ไม่ได้ ดูเพิ่มเติม

jQuery: ส่ง form แบบ ajax ชั้นสูง

ก่อนที่จะใช้ jQuery ส่งข้อมูลแบบ ajax ออกไป อาจจะใช้ javascript ทำงานเบื้องต้นก่อนได้เช่น การตรวจสอบข้อมูล (validation) ว่า user ได้ทำการกรอกข้อมูลตามที่จำเป็นครบรึเปล่า หรือนำข้อมูลออกไปจากแบบฟอร์ม โดยที่ไม่ต้องไปทำในฝั่ง server

ใน jQuery Ajax สามารถทำได้โดยการระบุ “beforeSend” ตาม code ตัวอย่าง

$.ajax({
    "beforeSend": function(jqXHR, settings) {

        /* ใส่ตัวแปรเข้าไปเพิ่ม */
        settings.data += '&ajax=true';

        /* แยกตัวแปรไว้ตรวจสอบข้อมูล */
        var params = new URLSearchParams(settings.data);

        /* บังคับกรอกข้อมูล */
        if (params.get('way') == 'socialid' && params.get('socialid') == '') {

            jqXHR.abort();
            alert('กรุณากรอกหมายเลขบัตรประชาชน');

            return false;
        } else if (params.get('way') == 'phone' && params.get('phone') == '') {

            jqXHR.abort();
            alert('กรุณากรอกหมายเลขโทรศัพท์');

            return false;
        }

        if (params.get('amount') == '') {

            jqXHR.abort();
            alert('กรุณากรอกจำนวนเงิน');

            return false;
        }

        /* เอาข้อมูลที่ไม่ต้องการส่งออก */
        settings.data = RemoveParameterFromUrl(settings.data, 'way');
        settings.data = RemoveParameterFromUrl(settings.data, 'way');
        if (params.get('way') == 'socialid') {
            settings.data = RemoveParameterFromUrl(settings.data, 'phone');
        } else {
            settings.data = RemoveParameterFromUrl(settings.data, 'socialid');
        }

    },
    "data": formA.serialize(),
    "method": "POST",
    "success": function(data, textStatus, jqXHR) {
        $('#resultA').html(data);
    },
    "url": "values.php",
});

เราจะดูข้อมูลที่รวบรวมมาได้ใน object settings.data และสามารถต่อ string เพิ่มเข้าไปได้เหมือนการต่อ string

settings.data += '&ajax=true';

การที่จะแยกข้อมูลออกมาสามารถใช้

var params = new URLSearchParams(settings.data);

แบ่งข้อมูลออกมาเป็น array เพื่อใช้ตรวจสอบข้อมูลหรือจะนำไปใช้ในการเปลี่ยนแปลงข้อมูล เช่นเดียวกันก็สามารถ delete ลบข้อมูลที่ไม่ได้การออกไปได้โดยใช้ function

function RemoveParameterFromUrl(url, parameter) {
    return url.replace(new RegExp('^([^#]*\?)(([^#]*)&)?' + parameter + '(\=[^&#]*)?(&|#|$)'), '$1$3$5').replace(/^([^#]*)((\?)&|\?(#|$))/, '$1$3$4');
}

ตัวอย่าง form เขียนโดยยกกรณีโอนเงินโดยใช้ พร้อมเพย์ (PromptPay) ที่ user จะเลือกได้ว่าจะโอนเงินโดยใช้ บัตรประชาชน หรือหมายเลขโทรศัพท์ของผู้รับแทนที่จะใช้หมายเลขบัญชี

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>jQuery: Advance Form Send</title>
    <link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>

<body>
    <h1>พร้อมเพย์ (PromptPay)</h1>
    <form action="values.php" class="form-horizontal" id="formA" method="post">
        <div class="form-group">
            <label class="col-sm-2 control-label">โอนเงินด้วย</label>
            <div class="col-sm-10">
                <div class="radio">
                    <label>
                        <input checked name="way" type="radio" value="socialid"> หมายเลขบัตรประชาชน
                    </label>
                </div>
                <div class="radio">
                    <label>
                        <input name="way" type="radio" value="phone"> หมายเลขโทรศัพท์
                    </label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label" for="socialidI">หมายเลขบัตรประชาชน</label>
            <div class="col-sm-10">
                <input class="form-control" id="socialidI" maxlength="13" name="socialid" placeholder="หมายเลขบัตรประชาชน" type="number">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label" for="phoneI">หมายเลขโทรศัพท์</label>
            <div class="col-sm-10">
                <input class="form-control" id="phoneI" maxlength="11" name="phone" placeholder="หมายเลขโทรศัพท์" type="tel">
            </div>
        </div>
        <div class="form-group">
            <label for="amount" class="col-sm-2 control-label">จำนวนเงิน</label>
            <div class="col-sm-10">
                <div class="input-group">
                    <input class="form-control" id="amount" max="5000" min="0" name="amount" placeholder="จำนวนเงิน" type="number">
                    <div class="input-group-addon">&#3647;</div>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-10 text-right">
                <button type="submit" class="btn btn-success">โอนเงิน</button>
            </div>
        </div>
    </form>
    <div class="col-sm-12" id="resultA"></div>
    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script>
        function RemoveParameterFromUrl(url, parameter) {
            return url.replace(new RegExp('^([^#]*\?)(([^#]*)&)?' + parameter + '(\=[^&#]*)?(&|#|$)'), '$1$3$5').replace(/^([^#]*)((\?)&|\?(#|$))/, '$1$3$4');
        }

        $(function () {
            var formA = $('#formA');

            formA.submit(function (event) {
                event.preventDefault();

                $.ajax({
                    "beforeSend": function (jqXHR, settings) {

                        /* ใส่ตัวแปรเข้าไปเพิ่ม */
                        settings.data += '&ajax=true';

                        /* แยกตัวแปรไว้ตรวจสอบข้อมูล */
                        var params = new URLSearchParams(settings.data);

                        /* บังคับกรอกข้อมูล */
                        if (params.get('way') == 'socialid' && params.get('socialid') == '') {

                            jqXHR.abort();
                            alert('กรุณากรอกหมายเลขบัตรประชาชน');

                            return false;
                        } else if (params.get('way') == 'phone' && params.get('phone') == '') {

                            jqXHR.abort();
                            alert('กรุณากรอกหมายเลขโทรศัพท์');

                            return false;
                        }

                        if (params.get('amount') == '') {

                            jqXHR.abort();
                            alert('กรุณากรอกจำนวนเงิน');

                            return false;
                        }

                        /* เอาข้อมูลที่ไม่ต้องการส่งออก */
                        settings.data = RemoveParameterFromUrl(settings.data, 'way');
                        settings.data = RemoveParameterFromUrl(settings.data, 'way');
                        if (params.get('way') == 'socialid') {
                            settings.data = RemoveParameterFromUrl(settings.data, 'phone');
                        } else {
                            settings.data = RemoveParameterFromUrl(settings.data, 'socialid');
                        }

                    },
                    "data": formA.serialize(),
                    "method": "POST",
                    "success": function (data, textStatus, jqXHR) {
                        $('#resultA').html(data);
                    },
                    "url": "values.php",
                });
            });
        });
    </script>
</body>

</html>

และฝั่ง server side ที่ควรจะมีการ validation ตรวจสอบข้อมูลซ้ำอีกครั้งเพื่อความมั่นใจ แต่ตัวอย่างนี้จะแสดงข้อมูลที่ทางฝั่ง server ได้รับเท่านั้น เพื่อให้เห็นการ edit แก้ข้อมูลที่ส่งไป

<?php
echo 'GET<pre>', print_r($_GET, true), '</pre>';
echo 'POST<pre>', print_r($_POST, true), '</pre>';

เลือกช่วงข้อมูล

ระบบที่ทำจะมีการตรวจสอบข้อมูลที่ป้อนเข้ามา โดยบังคับให้ป้อนข้อมูลเข้ามาตามค่าข้อมูลที่มีอยู่ แต่ถ้าจะต้องมา loop เช็กว่าข้อมูลตัวนี้มีในฐานข้อมูลรึเปล่า ก็เสียเวลาและเปลืองทรัพยากร จากการสังเกตุข้อมูลจะอยู่เป็นช่วงๆ เช่น 1 – 5, 8 – 12, 1982 – 2016

ถ้ารู้ช่วงข้อมูล ก็จะตรวจได้ว่าข้อมูลที่ป้อนเข้ามาอยู่ในช่วงที่กำหนดหรือไม่

ไปเจอ Select a range of values ลองแก้ตามได้

WITH Grouped AS ( -- Identify groups

                 SELECT D.bank_id,
                        grp = D.bank_id - ROW_NUMBER() OVER (
                                                             ORDER BY D.bank_id)
                 FROM banks AS D)
SELECT STUFF ( ( -- Concatenate items in the current group

                SELECT [text()] = ',' + CONVERT(varchar(11), G2.bank_id)
                FROM Grouped AS G2
                WHERE G2.grp = Grouped.grp
                ORDER BY G2.bank_id
                FOR XML PATH ('') ) -- Remove initial comma
 , 1, 1, '' )
FROM Grouped
GROUP BY Grouped.grp;

ผลลัพธ์
1,2,3,4,5,6
8,9,10,11,12,13,14
16,17,18,19,20,21,22,23,24,25,26,27,28,29
31,32,33,34,35,36,37,38,39,40
43,44

ได้เป็นกลุ่มก็จริงแต่ อยากได้ id เริ่มต้นถึง id สุดท้ายของแต่ละกลุ่มเท่านั้น ลองแก้มั่วๆดู

WITH Grouped AS
  ( SELECT D.bank_id,
           grp = D.bank_id - ROW_NUMBER() OVER (
                                                ORDER BY D.bank_id)
   FROM banks AS D)
SELECT MIN(Grouped.bank_id) AS start_id,
       MAX(Grouped.bank_id) AS end_id
FROM Grouped
GROUP BY Grouped.grp

ผลลัพธ์
start_id end_id
———– ———–
1 6
8 14
16 29
31 40
43 44

ได้ตามที่ต้องการเลย

Ajax Jquery Tinymce Serialize

เวลาใช้ jQuery serialize() ดึงข้อมูลจากฟอร์ม ถ้ามี WYSIWYG Editor อยู่ หลายๆครั้ง จะได้ข้อมูลไม่ครบ เพราะช่องที่เรากรอกข้อมูลลงไป จริงๆแล้วมันไม่ใช้ textarea แต่จะเป็นอีก layer ที่อยู่ข้างบนอีกที ถ้าจะเอาข้อมูลออกมาต้องคัดลอกข้อมูลกลับไปที่ textarea ก่อน
ถ้าเป็น tinymce ใช้คำสั่ง tinyMCE.get(‘ ไอดี ของ textarea’).getContent()

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tinymce & Jquery serialize By Pitt Phunsanit</title>
</head>

<body>
<form id="plus" method="post" action="somepage">
  <textarea name="article" id="articleId" style="width:100%"></textarea>
  <input type="submit">
</form>
<script src="assets/jQuery/jquery.min.js"></script>
<script src="assets/tinymce/tiny_mce.js"></script>
<script>
$(function(){
	$('#plus').submit(function(event){
		event.preventDefault();
		$('#articleId').val(tinyMCE.get('articleId').getContent());
		alert('after '+$('#articleId').serialize());
	});
});

tinyMCE.init({
	mode : "textareas",
	theme : "simple"
});
</script>
</body>
</html>