Tag Archive form

c#: Multiple Document Interface (MDI)

ตัวอย่างเขียน app แบบมีหลายฟอร์มย่อยอยู่ใน window หลัก หรือที่ฝรั่งเรียกไว้ว่า Multiple Document Interface (MDI)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PrototypesCSharp
{
    public partial class FormMDI : Form
    {
        public FormMDI()
        {
            InitializeComponent();
        }

        public Form TryGetFormByName(string frmName)
        {
            if (panelMDI.Controls.Count > 0)
            {
                panelMDI.Controls.RemoveAt(0);
            }

            var formType = Assembly.GetExecutingAssembly().GetTypes()
                .Where(a => a.BaseType == typeof(Form) && a.Name == frmName)
                .FirstOrDefault();

            if (formType == null)
            {//if no form
                return null;
            }

            Form frm = (Form)Activator.CreateInstance(formType);

            //https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.form.acceptbutton?view=net-5.0

            frm.AutoSize = true;
            frm.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            frm.Height = panelMDI.Height;
            frm.TopLevel = false;
            frm.TopMost = true;
            frm.WindowState = FormWindowState.Maximized;
            frm.Width = panelMDI.Width;

            frm.Show();

            panelMDI.Controls.Add(frm);

            return frm;
        }

        //on menu click
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            try
            {
                String formName = e.ClickedItem.Name.Split(new[] { "toolStripMenuItem" }, StringSplitOptions.None)[1];

                Form frm = TryGetFormByName(formName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //resize form inside when main windows resize
        private void panelMDI_Resize(object sender, EventArgs e)
        {
            foreach (Form frm in panel1.Controls)
            {
                frm.WindowState = FormWindowState.Normal;

                frm.WindowState = FormWindowState.Maximized;
            }
        }

    }
}

code ชุดนี้ทำงานโดยเมื่อ user click บน menuStrip (ไม่ใช้ตัว item นะ) จะอ่าน item name แล้วตัด toolStripMenuItem ออกเพื่อเรียกฟอร์ม ต้องขอขอบคุณ nemesv สำหรับคำตอบในเรื่อง Winforms, create form instance by form name ทำให้เขียน code สะอาดขึ้นเยอะเลย ไม่ต้องมา set ให้ item ทีละตัวแล้ว

joGet: AJAX Subform reload

ตัวอย่างการสร้าง ajax subform ในเรื่อง joGet: AJAX Subform มีโจทย์มาว่า input ที่ผูกกับซับฟอร์มถูกเปลี่ยนค่าจาก javascript ก็คิดว่าค่าใน subform จะเปลี่ยนตามไปด้วย แต่มันกลับไม่เปลี่ยนตาม เพราะ input ค่าเปลี่ยนก็จะทำให้มันโหลดข้อมูลมาใหม่ได้ไม่ยาก แต่มันไม่ทำงาน ลองศึกษาไฟล์ /jw/plugin/org.joget.plugin.enterprise.AjaxSubForm/js/jquery.ajaxsubform.js ดูก็พบว่ามันมีการสั่ง .off เอา event เก่าออกไปก่อน ทำให้แค่เปลี่ยนค่าเฉยๆ มันจะไม่ทำงาน

การสั่ง reload / refresh ajax subform โดยใช้ javascript ทำได้โดย

<button class="btn btn-info" id="refreshBtn" type="button">Reload form</button>
<script>
$(document).ready(function() {

$('#refreshBtn').on('click', function() {

let field1 = FormUtil.getField('field1');
field1.val('72817b0c-ac1430db-671b8000-37df4c8d');
field1.trigger('change');

});

});
</script>

แบบนี้เมื่อนเปลี่ยนค่า field1 subform จะถูกเปลี่ยนค่าตามไปด้วยแล้ว ลองดัดแปลงให้เหมาะกับงานดูนะครับ

joGet: AJAX Subform

AJAX Subform เป็น Form Element ที่ joget เตรียมไว้ให้สามารถใช้ ajax ดึงข้อมูลฟอร์มที่มีมาแสดงได้แบบไม่จำเป็นต้องโหลดทั้งหน้าใหม่ เหมือนระบบที่เราเขียนด้วยตัวเอง

การใช้งานทำได้ง่ายๆ โดยการ

    1. ในหน้า Form Builder ลาก AJAX Subform มาจากด้านซ้ายมือ
    2. คลิก Edit ไอค่อน
    3. กรอกข้อมูล
      ID
      id ของ ajax subform เช่น ajaxSubform
      Form
      เลือกฟอร์มที่ต้องการนำมาแทรกไว้ในหน้านี้
    4. คลิก Next >
    5. ติ๊ก
      Reload Subform when Parent Field value change?
      ติ๊กเพื่อจะให้ ajax ทำงานโหลด ฟอร์มใหม่เมื่อ input ที่ผูกไว้ เปลี่ยนค่า
    6. ผูกฟอร์มทั้งสองไว้ด้วยกัน
      Parent Field to keep Subform ID
      id input ในฟอร์มหลัก ที่จะใช้ลิงค์ให้ sub form ถูกดึงมาแทนที่โดยใช้ ajax
      Subform Field to keep Parent ID
      เป็น input ที่อยู่ใน subform ถ้าไม่มี การ load subform มาจาก server ก็ยังทำงานได้ตามปกติ

ทีนี้มาศึกษาการทำงานกันดูบ้าง

      1. joGet จะแทรกไฟล์ /jw/plugin/org.joget.plugin.enterprise.AjaxSubForm/js/jquery.ajaxsubform.js เพิ่มเข้ามาจากปกติ
      2. จะถูกเรียกใช้โดย javascript ที่เพิ่มเข้ามา เช่น
        <script type="text/javascript">
        $(document).ready(function() {
        $("#ajaxSubform_ajaxsubform_928").ajaxSubForm({
        contextPath: "/jw",
        id: "ajaxSubform",
        label: "",
        formDefId: "sendEmail",
        readOnly: "",
        readOnlyLabel: "",
        noframe: "",
        ajax: "true",
        parentSubFormId: "field1",
        prefix: "",
        hideEmpty: "",
        appId: "prototypes",
        appVersion: "1",
        processId: "",
        nonce: "%EF%BF%BD%00%3B%7D%28%EF%BF%BD%EF%BF%BD%EF%BF%BD",
        collapsible: "",
        collapsibleLabelExpanded: "Hide Details",
        collapsibleLabelCollapsed: "View Details",
        collapsibleExpanded: "true",
        collapsibleNoLoad: ""
        });
        });
        </script>

เมื่อไล่ดู code แล้วมันคือ plugin ที่ extended มาจาก jQuery ajax ตามปกติ ส่ง request ไปยัง /jw/web/json/plugin/org.joget.plugin.enterprise.AjaxSubForm/service โดยส่ง formDefId มีค่าเป็น form id ของ subform, parentSubFormId คือ field ในฟอร์มหลักที่ใช้ผูกกับซับฟอร์ม และจะคืนค่ากลับมาเป็น html ของฟอร์ม ในอนาคตคงได้ใช้เรียก ajax ไปโดยไม่ต้องสร้าง subform ก่อน

อ่านเพิ่มเติม

joGet: ฟอร์มส่งอีเมล์

ตัวอย่างฟอร์มส่งอีเมล์โดยใน joget ผู้ใช้สามารถแนบไฟล์เพิ่มเติม เลือกไฟล์จากที่มีโดยจะมีตัวอย่างไฟล์ที่จะแนบไปด้วย ให้เห็นก่อนตัดสินใจส่งอีเมล์

สร้างฟอร์มที่จะส่งอีเมล์ได้โดยใช้ json

{"className":"org.joget.apps.form.model.Form","properties":{"id":"sendEmail","loadBinder":{"className":"org.joget.apps.form.lib.WorkflowFormBinder","properties":{}},"tableName":"prototypes","description":"","name":"Send Email","postProcessorRunOn":"both","storeBinder":{"className":"org.joget.apps.form.lib.WorkflowFormBinder","properties":{}},"postProcessor":{"className":"","properties":{}},"permission":{"className":"","properties":{}},"noPermissionMessage":""},"elements":[{"elements":[{"elements":[{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"mailTo","workflowVariable":"mailTo","readonlyLabel":"","maxlength":"","encryption":"","validator":{"className":"org.joget.apps.form.lib.DefaultValidator","properties":{"message":"","custom-regex":"","mandatory":"true","type":"email"}},"value":"","label":"To","readonly":"","size":""}},{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"mailCc","readonlyLabel":"","workflowVariable":"mailCc","maxlength":"","encryption":"","validator":{"className":"","properties":{}},"value":"","label":"CC","readonly":"","size":""}},{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"mailBcc","readonlyLabel":"","workflowVariable":"mailBcc","maxlength":"","encryption":"","validator":{"className":"","properties":{}},"value":"","label":"BCC","readonly":"","size":""}},{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"mailSubject","workflowVariable":"mailSubject","readonlyLabel":"","maxlength":"","encryption":"","validator":{"className":"org.joget.apps.form.lib.DefaultValidator","properties":{"message":"","custom-regex":"","mandatory":"true","type":""}},"value":"","label":"Subject","readonly":"","size":""}},{"className":"org.joget.apps.form.lib.TextArea","properties":{"id":"mailMessage","workflowVariable":"mailMessage","readonlyLabel":"","cols":"20","validator":{"className":"org.joget.apps.form.lib.DefaultValidator","properties":{"message":"","custom-regex":"","mandatory":"true","type":""}},"value":"","label":"Message","readonly":"","rows":"5"}},{"className":"org.joget.apps.form.lib.FileUpload","properties":{"id":"mailAttach1","fileType":"","validator":{"className":"","properties":{}},"label":"Attach","attachment":"","multiple":"","readonly":"","maxSize":"","maxSizeMsg":"File size limit exceeded","fileTypeMsg":"Invalid file type","permissionType":"","size":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachName1","workflowVariable":"mailAttachName1","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachPath1","workflowVariable":"mailAttachPath1","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachName2","workflowVariable":"mailAttachName2","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachPath2","workflowVariable":"mailAttachPath2","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachName3","workflowVariable":"mailAttachName3","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachPath3","workflowVariable":"mailAttachPath3","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachName4","workflowVariable":"mailAttachName4","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"mailAttachPath4","workflowVariable":"mailAttachPath4","value":"","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.CustomHTML","properties":{"id":"sendEmailTemplateA","autoPopulate":"","value":"<link href=\"\/jw\/plugin\/org.joget.plugin.enterprise.RichTextEditorField\/css\/jquery.richtext.css\" rel=\"stylesheet\" \/>\n<script src=\"\/jw\/js\/tiny_mce\/jquery.tinymce.js\"><\/script>\n<script src=\"\/jw\/plugin\/org.joget.plugin.enterprise.RichTextEditorField\/js\/jquery.richtext.js\"><\/script>\n<script src=\"\/jw\/assets\/scripts.js\"><\/script>\n<b>File Attached :: <\/b>\n<div class=\"accordion\" id=\"accordionA\"><\/div>\n<script>\n    $(document).ready(function() {\n\n        let mailMessage = $('#mailMessage');\n\n        let message = 'Dear'
+\n            '<br><br>The quick brown fox jumps over the lazy dog<br>' +\n            '<br><br>regard' +\n            '<br><br>Pitt Phunsanit';\n\n        mailMessage.val(message);\n        mailMessage.richtext({\n            \"contextPath\": \"\/jw\"\n        });\n\n        emailAttachment([{\n                \"name\": \"JasperReport 1\",\n                \"url\": \"#request.scheme#:\/\/#request.serverName#:#request.serverPort#\/jw\/web\/json\/plugin\/org.joget.plugin.enterprise.JasperReportsMenu\/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport1&type=pdf&userviewId=prototypes\"\n            },\n            {\n                \"name\": \"JasperReport 2\",\n                \"url\": \"#request.scheme#:\/\/#request.serverName#:#request.serverPort#\/jw\/web\/json\/plugin\/org.joget.plugin.enterprise.JasperReportsMenu\/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport2&type=pdf&userviewId=prototypes\"\n            },\n            {\n                \"name\": \"JasperReport 3\",\n                \"url\": \"#request.scheme#:\/\/#request.serverName#:#request.serverPort#\/jw\/web\/json\/plugin\/org.joget.plugin.enterprise.JasperReportsMenu\/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport3&type=pdf&userviewId=prototypes\"\n            },\n            {\n                \"name\": \"JasperReport 4\",\n                \"url\": \"#request.scheme#:\/\/#request.serverName#:#request.serverPort#\/jw\/web\/json\/plugin\/org.joget.plugin.enterprise.JasperReportsMenu\/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport4&type=pdf&userviewId=prototypes\"\n            }\n        ]);\n\n    });\n<\/script>","label":""}}],"className":"org.joget.apps.form.model.Column","properties":{"width":"100%"}}],"className":"org.joget.apps.form.model.Section","properties":{"id":"SendEmail","loadBinder":{"className":"","properties":{}},"visibilityControl":"","regex":"","visibilityValue":"","storeBinder":{"className":"","properties":{}},"label":"Send Email","permission":{"className":"","properties":{}}}}]}

การทำงานจะมี 2 ส่วนคือ ส่วนที่เรียกใช้ function สำเร็จรูป

<link href="/jw/plugin/org.joget.plugin.enterprise.RichTextEditorField/css/jquery.richtext.css" rel="stylesheet" />
<script src="/jw/js/tiny_mce/jquery.tinymce.js"></script>
<script src="/jw/plugin/org.joget.plugin.enterprise.RichTextEditorField/js/jquery.richtext.js"></script>
<script src="/jw/assets/scripts.js"></script>
<b>File Attached :: </b>
<div class="accordion" id="accordionA"></div>
<script>
$(document).ready(function() {

let mailMessage = $('#mailMessage');

let message = 'Dear' +
'<br><br>The quick brown fox jumps over the lazy dog<br>' +
'<br><br>regard' +
'<br><br>Pitt Phunsanit';

mailMessage.val(message);
mailMessage.richtext({
"contextPath": "/jw"
});

emailAttachment([{
"name": "JasperReport 1",
"url": "#request.scheme#://#request.serverName#:#request.serverPort#/jw/web/json/plugin/org.joget.plugin.enterprise.JasperReportsMenu/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport1&type=pdf&userviewId=prototypes"
},
{
"name": "JasperReport 2",
"url": "#request.scheme#://#request.serverName#:#request.serverPort#/jw/web/json/plugin/org.joget.plugin.enterprise.JasperReportsMenu/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport2&type=pdf&userviewId=prototypes"
},
{
"name": "JasperReport 3",
"url": "#request.scheme#://#request.serverName#:#request.serverPort#/jw/web/json/plugin/org.joget.plugin.enterprise.JasperReportsMenu/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport3&type=pdf&userviewId=prototypes"
},
{
"name": "JasperReport 4",
"url": "#request.scheme#://#request.serverName#:#request.serverPort#/jw/web/json/plugin/org.joget.plugin.enterprise.JasperReportsMenu/service?action=report&appId=prototypes&appVersion=1&key=_&menuId=JasperReport4&type=pdf&userviewId=prototypes"
}
]);

});
</script>
  • let message จะสร้างเนื้อหาอีเมล์เป็น template ให้ก่อน user จะได้ไม่ต้องเขียนเองใหม่ทุกครั้ง
  • .richtext() ทำหน้าที่เปลี่ยน textarea เป็น rich text box แทนที่จะใช้ rich text box ของ joGet เอง เพราะจะไม่มีที่ผูก workflow Variable ได้ (งงกับการออกแบบ tools ของพี่แกจริงๆ)
  • emailAttachment() จะสร้างส่วน ui ให้ user เลือกที่จะแนบไฟล์หรือไม่แนบไฟล์และแสดง preview pdf ให้ดูก่อนที่จะส่งอีเมล์ออกไป

และส่วน javascript ที่แยกออกไปเพื่อใช้ซ้ำในฟอร์มอื่นๆ

/*
pitt phunsanit
email attachment preview
version 1
*/
function emailAttachment(lists) {
let accordionA = $("#accordionA");
let expaned = "";

$.each(lists, function(a, item) {
let itemNo = a + 1;

$("#mailAttachName" + itemNo).val(item.name);
$("#mailAttachPath" + itemNo).val(item.url);

let id = "attach" + itemNo;

if (a == 0) {
expaned = " in";
} else {
expaned = "";
}

let card =
'<div class="accordion-group">' +
'<div class="accordion-heading">' +
'<input checked style="float: left; margin: 10px 10px 0 10px;" type="checkbox" value="' +
itemNo +
'">' +
'<a class="accordion-toggle" data-parent="#accordionA" data-toggle="collapse"  href="#' +
id +
'" style="margin: 0px 10px; width: 80%;">' +
item.name +
'</a><a class="fa fa-download" href="' +
item.url +
'" style="float: right; font-size: 30px; margin: -32px 20px;" target="_blank"></a></div>' +
'<div class="accordion-body collapse' +
expaned +
'" id="' +
id +
'"><div class="accordion-inner">' +
'<iframe frameborder="0" height="842" id="attachIframe" src="' +
item.url +
'" width="100%"></iframe>' +
"</div></div></div>" +
"</div>";
accordionA.append(card);
});

accordionA.on("change", 'input[type="checkbox"]', function() {
let checkbox = $(this);

let itemNo = checkbox.val();

let mailAttachName = $("#mailAttachName" + itemNo);
let mailAttachPath = $("#mailAttachPath" + itemNo);
if (checkbox.is(":checked")) {
mailAttachPath.prop("disabled", false);
mailAttachName.prop("disabled", false);
} else {
mailAttachPath.prop("disabled", true);
mailAttachName.prop("disabled", true);
}
});
}

เรื่องที่เกี่ยข้อง

Joget: แสดงเฉพาะ form / datalist

น้อง (รึเปล่า) ที่ทำงานต้องการจะแสดง datalist ในฟอร์ม ทำให้เกิดการค้นหาข้อมูลกันนิดหนึ่ง แต่จริงๆ แล้วก็มีอยู่ในแอปตัวอย่างของ Joget นั่นละ แต่ไม่ยักกะเขียนไว้ในคู่มือ Datalist Builder

สมมุติว่า url ของหน้าที่แสดง datalist คือ http://localhost:8080/jw/web/userview/crm/crm_userview_sales/_/UsersDashboard ถ้าจะแสดงเฉพาะส่วน body ไม่เอา header และ footer ได้ง่ายๆเพียงแค่ใส่ ?embed=true ไปเท่านั้น คือ http://localhost:8080/jw/web/userview/crm/crm_userview_sales/_/UsersDashboard?embed=true หลังจากนี้ก็จะเหมาะที่จะแสดงใน iframe หรือ เรียกใช้จาก ajax ได้แล้ว

จากนั้นหลังการค้นคว้าเพิ่มเติมก็ได้เจอกับ Embedded Mode ที่สามารถเพิ่ม /embed/ ก่อน /userview/ เช่น http://localhost:8080/jw/web/userview/crm/crm_userview_sales/_/UsersDashboard เป็น http://localhost:8080/jw/web/embed/userview/crm/crm_userview_sales/_/UsersDashboard

วิธีนี้สามารถใช้กับฟอร์มได้เหมือนกัน เช่น http://localhost:8080/jw/web/userview/crm/crm_userview_sales/_/UserForm?id=clark เป็น http://localhost:8080/jw/web/userview/crm/crm_userview_sales/_/UserForm?id=clark&embed=true และ http://localhost:8080/jw/web/userview/crm/crm_userview_sales/_/UserForm?id=clark&embed=true

Joget: แสดงเซ็กชั่นฟอร์มแบบแท็บ

การกำหนดให้แสดง section ของฟอร์มโดยเปลี่ยนค่าใน input เหมือน Joget: กำหนดการแสดงไม่แสดง section ด้วย input มันไม่ค่อยจะเป็นธรรมชาติเท่าไหร่ ผู้ใช้จะคุ้นเคยกับ tabs มากกว่า

ทำได้โดย

  1. ให้ทำตามวิธี Joget: กำหนดการแสดงไม่แสดง section ด้วย input ก่อน
  2. ให้ลาก Custom HTML มาในตำแหน่งที่ต้องการ ใส่ javascript ตามตัวอย่าง
    <ul class="nav nav-tabs" id="tabsA">
    <li class="nav-item">
    <a class="active nav-link show" data-toggle="tab" href="#section1">Section 1</a>
    </li>
    <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section2">Section 2</a>
    </li>
    <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section3">Section 3</a>
    </li>
    </ul>
    <script src="/jw/assets/scripts.js"></script>
    <script>
    $(document).ready(function() {
    
    navSection();
    
    });
    </script>
  3. ไฟล์ javascript ที่เก็บ function แยกเอาไว้ reused ได้หลายๆ ครั้ง
    /*
    pitt phunsanit
    show / hide section with tabs
    version 1
    */
    function navSection() {
    let hash = window.location.hash.substr(1);
    let visibilityControl = $("#visibilityControl");
    let tabsA = $("#tabsA");
    
    if (hash != visibilityControl.val()) {
    $('a[href="#' + hash).click();
    visibilityControl.val(hash);
    }
    
    $("li > a", tabsA).on("click", function() {
    visibilityControl
    .val(
    $(this)
    .attr("href")
    .substr(1)
    )
    .trigger("change");
    });
    }

การแสดงไม่แสดง form section จะเห็นเป็น tabs ธรรมดาๆ ดูเป็นธรรมชาติขึ้นมากกว่าเดิม ตัวอย่างฟอร์ม

{"className":"org.joget.apps.form.model.Form","properties":{"id":"sectionTabs","loadBinder":{"className":"org.joget.apps.form.lib.WorkflowFormBinder"},"tableName":"prototypes","description":"","name":"Section Tabs","storeBinder":{"className":"org.joget.apps.form.lib.WorkflowFormBinder"}},"elements":[{"elements":[{"elements":[{"className":"org.joget.apps.form.lib.HiddenField","properties":{"id":"visibilityControl","workflowVariable":"","value":"section1","useDefaultWhenEmpty":""}},{"className":"org.joget.apps.form.lib.CustomHTML","properties":{"id":"dynamicTabsA","autoPopulate":"","value":"<ul class=\"nav nav-tabs\" id=\"tabsA\">\n    <li class=\"nav-item\">\n        <a class=\"active nav-link show\" data-toggle=\"tab\" href=\"#section1\">Section 1<\/a>\n    <\/li>\n    <li class=\"nav-item\">\n        <a class=\"nav-link\" data-toggle=\"tab\" href=\"#section2\">Section 2<\/a>\n    <\/li>\n    <li class=\"nav-item\">\n        <a class=\"nav-link\" data-toggle=\"tab\" href=\"#section3\">Section 3<\/a>\n    <\/li>\n<\/ul>\n<script src=\"\/jw\/assets\/scripts.js\"><\/script>\n<script>\n    $(document).ready(function() {\n\n        navSection();\n\n    });\n<\/script>","label":""}}],"className":"org.joget.apps.form.model.Column","properties":{"width":"100%"}}],"className":"org.joget.apps.form.model.Section","properties":{"id":"section1","loadBinder":{"className":"","properties":{}},"visibilityControl":"","regex":"","visibilityValue":"","storeBinder":{"className":"","properties":{}},"permission":{"className":"","properties":{}},"label":""}},{"elements":[{"elements":[{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"field1","readonlyLabel":"","workflowVariable":"","maxlength":"","encryption":"","validator":{"className":"","properties":{}},"value":"","label":"Section 1","readonly":"","size":""}}],"className":"org.joget.apps.form.model.Column","properties":{"width":"100%"}}],"className":"org.joget.apps.form.model.Section","properties":{"id":"section1","loadBinder":{"className":"","properties":{}},"visibilityControl":"visibilityControl","regex":"","visibilityValue":"section1","storeBinder":{"className":"","properties":{}},"permission":{"className":"","properties":{}},"label":"Section 1"}},{"elements":[{"elements":[{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"field2","readonlyLabel":"","workflowVariable":"","maxlength":"","encryption":"","validator":{"className":"","properties":{}},"value":"","label":"Section 2","readonly":"","size":""}}],"className":"org.joget.apps.form.model.Column","properties":{"width":"100%"}}],"className":"org.joget.apps.form.model.Section","properties":{"id":"section2","loadBinder":{"className":"","properties":{}},"visibilityControl":"visibilityControl","regex":"","visibilityValue":"section2","storeBinder":{"className":"","properties":{}},"permission":{"className":"","properties":{}},"label":"Section 2"}},{"elements":[{"elements":[{"className":"org.joget.apps.form.lib.TextField","properties":{"id":"field3","readonlyLabel":"","workflowVariable":"","maxlength":"","encryption":"","validator":{"className":"","properties":{}},"value":"","label":"Section 3","readonly":"","size":""}}],"className":"org.joget.apps.form.model.Column","properties":{"width":"100%"}}],"className":"org.joget.apps.form.model.Section","properties":{"id":"section3","loadBinder":{"className":"","properties":{}},"visibilityControl":"visibilityControl","regex":"","visibilityValue":"section3","storeBinder":{"className":"","properties":{}},"permission":{"className":"","properties":{}},"label":"Section 3"}}]}

Joget:กำหนดการแสดงไม่แสดง section ด้วย input

joget ได้เตรียมการแสดงฟอร์และไม่แสดงฟอร์มตามเงื่อนไขไว้โดยวิธีที่ง่ายที่สุดคือ แสดง section ตามค่าใน input ที่มี

  1. ในหน้า form builder ให้ลาก Hidden Field หรือ Text Field มาในตำแหน่งที่ต้องการ ตั้งชื่อเช่น visibilityControl
  2. ไปที่ section ที่ต้องการควบคุมการแสดง คลิก Edit Section
  3. คลิก next
  4. คลิก next
  5. กำหนด Visibility Control Rules โดย
    • Join Type เลือก And หรือ Or ตามเงื่อนไขที่ต้องการ
    • Reverse Value ให้ติ๊กถ้าต้องการให้ทำงานเมื่อ มีค่าตรงข้ามกับค่าใน Field
    • Field ID ที่เก็บสถานะ เช่น visibilityControl
    • Field Value ค่าที่ต้องการนำมาเปรียบเที่ยบ
    • Using Regular Expressions? ถ้าใช้ Regular Expressions เปรียบเทียบเช่น 5|8|2525 จะแสดง section เมื่อค่าใน visibilityControl เท่ากับ 5 หรือ 8 หรือ 2525

ทดลองเปลี่ยนค่าของ visibilityControl และสังเกตุความเปลี่ยนแปลงดู

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>';