Jquery learning notes-how to use jqgrid (edit, delete, update, and add)

Source: Internet
Author: User

In the morning, jqgrid released version 3.6.2. I checked Chang log and showed me the release of the Chinese package.

A few days ago for this headache, Do You Want To according to grid. local-en.js to the Chinese, did not expect to have a Chinese package directly. The official website is generally better than what you do.

: Http://www.trirand.com/blog? Page_id = 6

Modify the reference statement in the Self-written JSP file after downloading.

<SCRIPT src = "../JS/i18n/grid. locale-en.js" type = "text/JavaScript"> </SCRIPT>

Change

<SCRIPT src = "../JS/i18n/grid. locale-cn.js" type = "text/JavaScript"> </SCRIPT>

Start running tomcat, And it turns into Chinese. Haha! Great!

Note that if you are an avid fan, you can directly reference the original package under the src directory in JSP (so that you can debug the jqgrid source code ), in addition to the JSP file mentioned above, there is also a JS file to be modified, that is: src/grid. loader. JS

    var modules = [        { include: true, incfile:'i18n/grid.locale-en.js'}, // jqGrid translation

To be modified

    var modules = [        { include: true, incfile:'i18n/grid.locale-cn.js'}, // jqGrid translation

That's all!

Use jqgrid to modify data

Jqgrid can be used in three ways. Let's modify the data displayed in jqgrid. The three methods are as follows:
Cell editing -- only one cell content can be modified. (All images are from jqgrid wiki or jqgrid demo)


Inline editing -- allows you to directly modify the data of a row in jqgrid.


Form editing -- A New editing window is displayed for editing and adding


For the time being, let's take a look at how to make jqgrid data editable?
In fact, it is very easy to set several attributes in the colmodel attribute of jqgrid:
Editable
The optional values are true or false. The default value is false. Indicates whether the data in this column can be edited. Note that the hidden fields of jqgrid cannot be edited even if this attribute is set to true. In cell editing and inline editing modes, you can only modify these fields by setting them to visible. In form editing mode, you can use the editoptions parameter to set whether to modify hidden columns.
Edittype
Optional values: 'text', 'textea ', 'select', 'checkbox', 'Password', 'click', 'image', 'file', and 'custom '. The default value is text.
According to the name, we can see that this attribute sets the HTML style of the editing box. For example, you can set it to a text value and set attributes such as size and maxlength in editoptions. The HTML style is similar to <input type = "text" size = "10" maxlength = "15"/>.
Note the following:
When setting the checkbox, You need to specify the value in editoptions. The first value should be the value at the time of checked. For example, editoptions: {value: "Yes: No"} sets the checkbox editing box. When selected, the value is yes, and when not selected, the value is no. We recommend that you set this value.
When setting select, the Select drop-down box value needs to be set in editoptions.
One way is to use a string to set the value attribute of editoptions, such as editoption: {value: "Fe: FedEx; In: intime; TN: TNT "}, this sets three optional values for the drop-down box. Note: values are represented before the colon, while values are displayed after the colon.
The second method is to use an object to set the value attribute of editoptions. In this case, the value must be included in {}, such as editoptions: {value: {1: 'one ', 2: 'two '}}.
The third method is to set the dataurl parameter for editoptions. It indicates the select value, which is obtained through a URL, such as the return value of an Ajax request. In this case, the URL return values must include the select and option HTML tags. Like this: <SELECT> <option value = "1"> one </option> <option value = "2"> two </option> </SELECT>. in this case, you can also set whether to allow multiple selections, size, and so on in editoptions.
When setting an image, the src attribute of editoptions is used to specify the image address.
The custom type is to use a function to specify the elements to be edited and return the value to be submitted.
The function definition is described in editoptions. custom_element is used to specify which function is used to create an edit box. Note that the function must return a new Dom element. The parameter value is a value, the other is the editoptions value of colmodel.
The other is custom_value. This function is used to return the value of this edit box after editing. The parameter of this function is an element object. The Calling format is as follows:
<SCRIPT>
// Create an input box
Function myelem (value, options ){
VaR El = Document. createelement ("input ");
El. type = "text ";
El. value = value;
Return El;
}

// Obtain the value
Function myvalue (ELEM ){
Return $ (ELEM). Val ();
}
Jquery ("# grid_id"). jqgrid ({
...
Colmodel :[
...
{Name: 'price',..., Editable: True, edittype: 'custom', editoptions: {custom_element: myelem, custom_value: myvalue }},
...
]
...
});
</SCRIPT>

Editoptions
In addition to the editoptions options described above, we can also set defaultvalue and so on. More complicated things, such as dataevents, will not be introduced.
Editrules
Editrules is used to set additional attributes of colmodel that can be used to edit columns. Most of the time, it is used to verify the legality of user input before submission to the server. For example, editrules: {edithidden: True, required: True ....}.
Optional attributes include:
Edithidden: valid only in form editing mode. If it is set to true, the hidden fields can be modified.
Required: Set whether the field can be blank (required) during editing ).
Number: Set to true. If the input value is not a number or is null, an error is returned.
Integer:
Minvalue:
Maxvalue:
Email:
URL: Check whether the URL address is valid.
Date:
Time:
Custom: if it is set to true, it is verified by a custom JS function. The function is defined in custom_func.
Custom_func: The value passed to the function. One is the value to be verified, and the other is the name attribute value defined in colmodel. The function must return an array. One is the verification result, either true or false, and the other is the prompt string when a verification error occurs. Such as [false, "Please enter valid value.
Example of custom Verification:
<SCRIPT>
Function mypricecheck (value, colname ){
If (value <0 & value> 20)
Return [false, "Please enter value between 0 and 20"];
Else
Return [true, ""];
}

Jquery ("# grid_id"). jqgrid ({
...
Colmodel :[
...
{Name: 'price',..., editrules: {custom: True, custom_func: mypricecheck...}, Editable: true },
...
]
...
});
</SCRIPT> <function mypricecheck (value, colname) {If (value <0 & value> 20) return [false, "Please enter value between 0 and 20"]; else return [true, ""];} jquery ("# grid_id "). jqgrid ({
... Colmodel :[... {Name: 'price ',..., editrules: {custom: True, custom_func: mypricecheck ....}, editable: true},...]...}); //>

Formoptions(Only valid in form editing mode). It is used to re-Sort edit elements in form. It can also add information before or after editing elements (for example, some prompt information, or a red * indicates that it must be filled in, and so on ).
Optional attributes are as follows:
Elmprefix: string value. If it is set, some content (probably HTML content) appears after the edit box)
Elmsuffix: string value. If it is set, some content (probably HTML content) appears before the edit box)
Label: string value. If this parameter is set, the value in colnames is replaced and displayed as the label of the edit box.
Rowpos: Numeric value that determines the position of an element row in Form (relative to the text label again with the text-label)
Colpos: Numeric value, which determines the position of the element column in Form (relative to the label again with the label)
The two edit boxes can have the same rowpos value, but the colpos value is different. This will put the two edit boxes in the same row of form.
NOTE: If rowpos and colpos values are set, we strongly recommend that you set these values for all other editing elements.

---- This article is just an explanation of the doc document. There is not much of your own stuff. Next, I will make an example of form editing. The meat scene is coming soon ......

 

Let's talk about the basic knowledge of jqgrid editing. The following is an example of the form editing-based editing mode.

There are several main ways to edit the form editing mode: editgridrow -- used to modify the record, editgridrow function. Passing a 'new' parameter indicates adding a record; viewgridrow indicates viewing the record details; delgridrow deletes a record.

These methods are called in the same way as other functions in jqgrid. (You can use the new API call method and use the function name as the first parameter.) Note that the options parameters of each function call have some differences, for details, refer to the document. In addition, the data and format that each function submits to the server are different. The following uses editgridrow as an example.

The call method of editgridrow is as follows:

Jquery ("# grid_id"). editgridrow (rowid, properties); or the following method jquery ("# grid_id"). jqgrid ('editgridrow', rowid, properties );

Rowid indicates the row to be edited, and properties indicates an array containing various attributes and events. (For details about attributes and events, refer to the document. We will not translate them here .) After the call, what data is submitted to the server?

The submitted data mainly includes:

1. Each edited "field: Value" pair. This is not easy to understand. In fact, it means to submit some data in post mode. The data name is the name attribute defined in colmodel, and the value is the value we enter in the pop-up window. (Of course, this requires us to define these variables in the server action and encapsulate them in the pojo object for processing .)

2. contains a value of "ID: rowid" to indicate which Id keyword record is modified (ID = _ Empty when a record is added );

3. contains a value of "Edit: edit" to indicate whether to edit or add a record (when adding a record, add = add)

4. Other advanced situations, such as using the editdata object or implementing the onclicksubmit event processing. The format of the submitted data is complex.

To add a new record, call editgridrow as follows:

jQuery("#grid_id").editGridRow( "new", properties );

Now let's take a look at how we implement it in JSP files.

First of all, this example and the example in the previous article have changed a lot. It mainly includes adding a column in jqgrid as an operation column and adding two operations: Edit and delete. A button (Custom button) is added to export the query result to CSV, but the specific backend server function is not implemented. The query and add functions are displayed separately as a button behind jqgrid. For specific differences, you can refer to the example in my other article jqgrid multi-field query.

$ (). Ready (function (){
$ ("# Grid"). jqgrid ({
URL: 'queryallbrand. action ',
Datatype: "JSON ",
Mtype: 'post ',
Colnames: ['operation', 'brand id', 'brand Code', 'brand name', 'availability ', 'last modification time'],
Colmodel :[
{Name: 'act ', index: 'act', width: 110, search: false, sortable: false, Editable: false },
{Name: 'brandid', index: 'brandid', width: 90, Editable: false },
{Name: 'code', index: 'code', width: 110,
Editable: True,
Edittype: 'text ',
Editoptions: {size: 10, maxlength: 15 },
Editrules: {required: true },
Formoptions: {elmprefix :'(*)'}
},
{Name: 'brandname', index: 'brandname', width: 100,
Editable: True,
Edittype: 'text ',
Editoptions: {size: 10, maxlength: 15 },
Editrules: {required: true },
Formoptions: {elmprefix :'(*)'}
},
{Name: 'status', index: 'status', width: 80,
Editable: True,
Edittype: 'checkbox ',
Editoptions: {value: "1:0 "},
Editrules: {required: true },
Formoptions: {elmprefix :'(*)'}
},
{Name: 'lastmodifieddatetime', index: 'lastmodifieddatetime', width: 100, Editable: false}
],
Rownum: 3

 

The following error message is displayed: Error status: "OK". Error code: 900. In fact, the modified (new) record is saved to the database correctly. See:

Why? It has been a headache for several days. I carefully read the documents on jqgrid Wiki and Google many articles. I still cannot find the corresponding instructions or solutions.

Later I studied the source code of jqgrid. The src/grid. formedit. js file contains the postit function, which contains the following code:

if(Status != "success") {    ret[0] = false;    if ($.isFunction(rp_ge.errorTextFormat)) {        ret[1] = rp_ge.errorTextFormat(data);    } else {        ret[1] = Status + " Status: '" + data.statusText + "'. Error code: " + data.status;    }} else {    // data is posted successful    // execute aftersubmit with the returned data from server    if( $.isFunction(rp_ge.afterSubmit) ) {        ret = rp_ge.afterSubmit(data,postdata);    }}

It seems that the problem is in this place. Therefore, we assume that the addition, deletion, and modification operations of jqgrid require the server to return content.

I guess jqgrid requires the server to return status content that contains success or failure. So I modified the return value of the action class and method:

Public String modifybrand () {string result = "success"; try {mproductbrand MPB = new mproductbrand (); MPB. setbrandname (BrandName); MPB. setcode (CODE); MPB. setstatus (Status); MPB. setlastmodifieddatetime (New timestamp (system. currenttimemillis (); If (success! = NULL & found. equals ("edit") {// edit MPB. setbrandid (New INTEGER (ID); this. brandservice. modifybrand (MPB);} else if (else! = NULL & found. equals ("add") {// added mproductbrand mproductbrand1 = This. brandservice. locatebybrandcode (MPB. getcode (). tostring (). trim (). touppercase (); mproductbrand mproductbrand2 = This. brandservice. locatebybrandname (MPB. getbrandname (). tostring (). trim (); If (mproductbrand1.getbrandid () = NULL & mproductbrand2.getbrandid () = NULL) // check whether {This exists. brandservice. addbrand (MPB);} else {log. warn ("Brand code or brand name already exists"); Result = "error" ;}} catch (exception ex) {ex. printstacktrace (); log. warn ("failed to modify"); Result = "error";} httpservletresponse response = servletactioncontext. getresponse (); response. setcontenttype ("text/JSON; charset = UTF-8"); try {printwriter out = response. getwriter (); jsonobject JSON = new jsonobject (); JSON. put ("status", result); out. print (JSON. tostring ();} catch (exception E) {e. printstacktrace (); log. Error ("error: cannot create printwriter object! ");} Return NULL ;}

Run the command again. The editing window is automatically closed and the page is automatically reloaded. Good!

But I have been wondering how the server returns ??? I took a closer look at the jqgrid demo and wanted to study the PHP file to see how it was done in the example. In addition, the jqgrid demo editing example does not actually submit the modification content to the server. For security reasons ......

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.