I am using datatables 1.10.11.
As per the documentation, i can set the rowId using following syntax:
$('#myTable').DataTable( {
rowId: 'staffId'
} );
I am not creating datatable using Ajax.
I have two text boxes and "Add" button on left hand side and one datatable on right hand side. When i click on "Add", a new row is added to datatable. I hope that makes sense.
I need unique id attribute for each row for my use. I have tried doing so but no success at all.
According to documentation, this feature is available since DataTables 1.10.8
Did anyone solved this problem? Any help will be appreciated.
Thanks.
For add ID to tr element you con use rowId and especify the column that contain your id.
$('#myTable').DataTable(
{
columns: [
{data:"staffId"},//Remember specified the column
{data:"position"},
{data:"office"},
{data:"age"},
{data:"date"},
{data:"salary"}
],
rowId: 'staffId' //Reference to column data
});
For your button add, you should create the object and add to Table using row.add and draw for show in your table, for example:
$("#btnAdd").on("click",function(){
var rowID = $("#rowId").val();//Get value of TextBox
var new_object = {
staffId: rowID, //New rowId
position: 'Developer',
office: "Peru",
age: 25,
date: "2016/03/25",
salary: "$ 58.200"
};
myTable.row.add(
new_object
).draw();
});
Result: https://jsfiddle.net/cmedina/7kfmyw6x/65/
Related
Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.
// Clone a row
theTable = tmxdijit.registry.byId(tableName);
firstRow = theTable.collection.data[theTable.collection.data.length-1];
firstRowDom = theTable.row(firstRow.id);
var cloneRow = json.stringify(firstRow);
cloneRow = json.parse(cloneRow);
// Get the row I want to add before
var theSelected = Object.keys(theTable.selection)[0];
if(theSelected.length > 0) {
var theRowID = theSelected[0];
}
theTable.collection.add(cloneRow, {beforeId: theRowID});
theTable.renderArray([cloneRow]);
There are two general ways to handle data insertion. One is to manually add data to an array, ensure it's properly sorted, and then tell the grid to render the array. A better way is to use an OnDemandGrid with a trackable store.
For dgrid/dstore to support simple dynamic insertion of rows, make sure the store is trackable, and that data items have some unique id property:
var StoreClass = Memory.createSubclass(Trackable);
var store = new StoreClass({ data: whatever });
var grid = new OnDemandGrid({
columns: { /* columns */ },
collection: store
});
By default dstore assumes the id property is "id", but you can specify something else:
var store = new StoreClass({ idProperty: "name", data: whatever });
If you want the data to be sorted, a simple solution is to set a sort on the grid (the grid will sort rows in ascending order using the given property name):
grid.set('sort', 'name');
To add or remove data, use the store methods put and remove.
var collection = grid.get('collection');
collection.put(/* a new data item */);
collection.remove(/* a data item id */);
The grid will be notified of the store update and will insert or remove the rows.
The dgrid Using Grids and Stores tutorial has more information and examples.
Instead of this, why don't you add the data directly to the grid store? See if this helps
https://dojotoolkit.org/reference-guide/1.10/dojox/grid/example_Adding_and_deleting_data.html
Adding and Deleting data
If you want to add (remove) data programmatically, you just have to add (remove) it from the underlying data store. Since DataGrid is “DataStoreAware”, changes made to the store will be reflected automatically in the DataGrid.
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.Button");
.
<div>
This example shows, how to add/remove rows
</div>
<table data-dojo-type="dojox.grid.DataGrid"
data-dojo-id="grid5"
data-dojo-props="store:store3,
query:{ name: '*' },
rowsPerPage:20,
clientSort:true,
rowSelector:'20px'
style="width: 400px; height: 200px;">
<thead>
<tr>
<th width="200px"
field="name">Country/Continent Name</th>
<th width="auto"
field="type"
cellType="dojox.grid.cells.Select"
options="country,city,continent"
editable="true">Type</th>
</tr>
</thead>
</table>
<div data-dojo-type="dijit.form.Button">
Add Row
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// set the properties for the new item:
var myNewItem = {type: "country", name: "Fill this country name"};
// Insert the new item into the store:
// (we use store3 from the example above in this example)
store3.newItem(myNewItem);
</script>
</div>
<div data-dojo-type="dijit.form.Button">
Remove Selected Rows
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// Get all selected items from the Grid:
var items = grid5.selection.getSelected();
if(items.length){
// Iterate through the list of selected items.
// The current item is available in the variable
// "selectedItem" within the following function:
dojo.forEach(items, function(selectedItem){
if(selectedItem !== null){
// Delete the item from the data store:
store3.deleteItem(selectedItem);
} // end if
}); // end forEach
} // end if
</script>
</div>
.
#import "{{ baseUrl }}dijit/themes/nihilo/nihilo.css";
#import "{{ baseUrl }}dojox/grid/resources/nihiloGrid.css";
I am trying to add color to the cell of w2ui grid.
After following the documentation, I am able to change the color of the cell and the row (but individually).
For a single cell:
records: [
{ recid: 1, fname: 'Jane', lname: 'Doe', email: 'jdoe#gmail.com', sdate: 384052483664, style: {3:'background-color: yellow; color: white;'}}
]
For a single row:
records: [
{ recid: 1, fname: 'Jane', lname: 'Doe', email: 'jdoe#gmail.com', sdate: 384052483664, style: 'background-color: red; color: white;'}
]
Till this part it's okay because am hardcoding the records.
Question:
I am loading data from the server and I am putting rules based on some conditions and I want to change color accordingly.
What I understood is that, I have to add style on server only( I am using php and mysql, btw).
Below is my sample code:
$Query = "SELECT #curRow := #curRow + 1 as id ,`x`, `y`, `z`, `a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`, `i`
FROM `table_name` JOIN (SELECT #curRow := 0) r";
//echo $Query;
$code=mysqli_query($link,$Query);
$data = array();
while($row = mysqli_fetch_assoc($code))
{
if($row["id"]==1)
{
//$row['expanded']="'spinner'";
//$object = (object) ['style' => "{ 5: 'color': 'red'; 'background-color': 'whilte' }"];
//$row['style']=$object;
$row['style']= "3:'background-color: red; color: black;'";
}
//var_dump ($row);
$data[] = $row;
}
$arr = array("total" => count($data),
"records" => $data);
Assueme if($row["id"]==1) is one of the rule, so over here am trying to add style part. If you see the code, I have tried multiple ways to add style to it. It's just not working. But if am printing the rows using php, I get the row exactly the way it's supposed to code( See the code for single cell style stated above). But it's not reflecting in the table.
Second quesstion
I will like to have row colored in one color and on top of that, i'll like to color one individual cell differently( two different rules, one for rows and one for coloumns). Since I was not able to achieve the first requirement, I didnt spend much time on this issue.
Third question
How can I make the height of the row dynamic? Let's say I have a column name response, I have assigned a fixed width to it, when the content of that row exceeds the width, it shows ... after the available width. I want to show it in next line. Is it possible to do so?
Thanks.
To answer your first question:
style has to be a JSON object when it arrives on the client side, so on the server side, it must be an array that's later on passed to json_encode()
$row['style'] => array('5' => 'background-color: red; color: black;');
...
$result = json_encode($row);
To answer your second question:
The latest version of w2ui 1.5 supports both class and style attributes on a record.
So, to color a row and color a single cell in the row differently, you could use:
records: [
{ recid: 1, fname: 'Jane', lname: 'Doe', class: 'my-css-class-for-the-row', style: {3: 'background-color: yellow; color: white;'} }
];
style and class can both be either a string or an object, so you could also do it the other way around and use style to color the whole row and class to color specific cells.
To answer your third question:
Rows can not have a dynamic height, because of virtual scrolling. That means, all rows must have the same height. You can however change the height of all rows with
grid.recordHeight = 40; // height in pixels
Again, this requires the latest 1.5 version of w2ui and it looks quirky if used together with column groups.
I am trying to get the database ID of the current row while clicking a button.
I have seen a few examples relating to this aspect and have tried many but it seems that they mostly relate to the legacy table tools extension whereas I am making use of the Editor.
Using the idSrc option from the Editor manual I recieve a server side response in JSON that contains the databases id/primary key value:
{
"data":[
{
"id":"1",
"name":"Test Name",
}
],
"options":[],
"files":[]
}
Now I am trying to get that value by clicking a button that is attached to row via the API function: row().id()
Within the example for this function it provides a clear example of how the rows id value (now the database id?) can be obtained:
var table = $('#myTable').DataTable();
$('#myTable').on( 'click', 'tr', function () {
var id = table.row( this ).id();
alert( 'Clicked row id '+id );
});
So I have implemented this as follows:
var editor;
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "/names.php",
table: "#example",
idSrc: "id",
fields: [ {
label: "Name:",
name: "name"
} ]
});
var table = $('#example').DataTable( {
dom: "Bfrtip",
ajax: "/names.php",
columns: [
{ data: "name" }
]
});
$('#example').on( 'click', 'tr', function () {
var id = table.row( this ).id();
alert( 'Clicked row id ' + id );
});
});
The problem here though is that when I click on the row (tr) it prompts as follows: Clicked row id undefined
Why am I getting back an undefined value when it should be sending back the row id?
When instances your DataTable, you must indicate the id field rowId, which should be indicated as the name of your columns
var table = $('#example').DataTable( {
dom: "Bfrtip",
ajax: "/names.php",
columns: [
{ data : "id" },//id is the name of your data
{ data: "name" }
],
rowId: 'id' //Here assign the id to your table
});
Result: https://jsfiddle.net/cmedina/7kfmyw6x/17/
As #CMedina pointed out, rowId stipulates which value in the JSON data is used as each rows id attribute.
Here is the code used to get the rows ID value which is prefixed with row_:
$('#example').on( 'click', 'tr', function () {
// Get the rows id value
var id = table.row( this ).id();
// Filter for only numbers
id = id.replace(/\D/g, '');
// Transform to numeric value
id = parseInt(id, 10);
// So instead of returning the actual id which is row_1
// We get back just the primary key which is 1
alert( 'Clicked row id '+id );
});
I have a enhanced grid, i want to edit the grid contents and once clicked on Update link, i have to pass newly typed values to the java spring controller where i have logic to save updated values in database. But issue is after i type the value in enhanced grid i need to click somewhere in the grid or make focus on other field so that newly typed value is passed to the spring controller. If i type the new value and the cell is in edit mode and directly click on UPDATE link present in column4 of grid, the old value is passed to the spring controller. Please suggest what changes to be made so that once the mouse is out of the focus of the cell, the newly typed value should save in store and that value should be sent to spring controller when UPDATE link is clicked on column4 of grid.
Please find the fiddle : http://jsfiddle.net/740L0y43/7/
enhanced grid code:
require(['dojo/_base/lang', 'dojox/grid/EnhancedGrid', 'dojo/data/ItemFileWriteStore', 'dijit/form/Button', 'dojo/dom', 'dojo/aspect', 'dojo/domReady!'],
function (lang, EnhancedGrid, ItemFileWriteStore, Button, dom, aspect) {
/*set up data store*/
var data = {
identifier: "id",
items: [{
id : 1,
col2 : "aa",
col3 : "bb",
col4 : "cC"
}]
};
var store = new ItemFileWriteStore({
data: data
});
/*set up layout*/
var layout = [
[{
'name': 'Column 1',singleClickEdit:'true', editable:'true',
'field': 'id',
'width': '100px'
}, {
'name': 'Column 2',singleClickEdit:'true', editable:'true',
'field': 'col2',
'width': '100px'
}, {
'name': 'Column 3',singleClickEdit:'true', editable:'true',
'field': 'col3',
'width': '200px'
}, {
'name': 'Column 4',formatter: updateDetails,
'field': 'col4',
'width': '150px'
}]
];
/*create a new grid*/
var grid = new EnhancedGrid({
id: 'grid',
store: store,
structure: layout,
sortInfo: -1,
});
/*append the new grid to the div*/
grid.placeAt("gridDiv");
/*Call startup() to render the grid*/
grid.startup();
aspect.after(grid, 'renderRow', grid.sort);
var id = 2;
var button = new Button({
onClick: function () {
console.log(arguments);
store.newItem({
id: id,
col2: "col2-" + id,
col3: "col3-" + id,
col4: "col4-" + id
});
id++;
}
}, "addRow");
});
var updateDetails = function(value, rowIndex) {
var col2 = this.grid.getItem(rowIndex).col2;
alert("col2 updated value : " + col2);
return "<a href=\"<%=request.getContextPath()%>/updateInfo.htm?col2="+col2 +"\">" + "UPDATE";
};
spring controller code:
#RequestMapping(value = "/updateInfo", method = RequestMethod.GET)
public ModelAndView updateInfo(HttpServletRequest request,
HttpServletResponse response, #ModelAttribute MyDTO myDto,
#RequestParam("col2") String col2, #RequestParam("col2") String col2){
System.out.println("col2 value: " + col2);
System.out.println("col3 value: " + col3);
//when i type some value in COlumn2/Column3 of enhanced grid and column is still in edit mode then on click of UPDATE , new value is not passed to spring controller, its passing the old value.
...
...
//logic to save in DB
}
This line:
return "<a href=\"<%=request.getContextPath()%>/updateInfo.htm?col2="+col2 +"\">" + "UPDATE";
is returning an anchor with the href as "/contextPath/updateInfo.html?col2=aa". That renders it and that's it; that URL is never changing. Then, when you click on UPDATE, it sends what was in there when the page was rendered, not what the current value in your table is.
If you want to have the current value be sent, you should have your href be "#" and have an onclick="updateValue(1)" like this:
UPDATE
where 1 is the row number.
Then, in your update value function, you'd send an ajax request to update the value. Since you're using dojo, check this out: http://dojotoolkit.org/documentation/tutorials/1.8/ajax/
Here's what your function might look like (some pseudo code, some comments to describe behavior):
function updateValue(rowNum){
//var row = data.items.getRow(rowNum); or something like this
//Call ajax here and send the new row values
}
After messing with dojo for about an hour, and struggling with dojo's scoping and how to call a function that has access to the data grid and/or it's data store (sorry..I had 0 experience with dojo before this question)...here's your easy way out, OP:
http://jsfiddle.net/hm8gpz6o/
The important parts:
EnhancedGrid was NOT re-rendering the formatter generated cell when your data store was updated. This seems like a problem with dojo's EnhancedGrid.
I added the following (onApplyCellEdit will fire when a cell is updated):
/*create a new grid*/
var grid = new EnhancedGrid({
id: 'grid',
store: store,
structure: layout,
sortInfo: -1,
onApplyCellEdit: function(inValue, inRowIndex, inFieldIndex){
refreshGrid();
}
});
And finally, refreshGrid() will force a re-render of the whole grid. I hate that I have to do this:
function refreshGrid(){
grid.startup();
}
Please see the fiddle for the full working example.
I want to show serial number as first column in jqgrid.since, database records doesn't has contigous 'ids', I can't use it.
Is there any simple way to accomplish this?
Update:
sample code:
$(document).ready(function()
{
$("#list").jqGrid(
{
url:'<%=Url.class_variable_get(:##baseurl) %>/address_books/show.json',
datatype:'json',
mtype:'get',
colNames:['Id','Name','Email Id','Number'],
colModel:[
{name:'address_book_id',index:'address_book_id',sorttype:'int',sortable:true,width:100},
{name:'name',index:'name',sortable:true,width:300},
{name:'email',index:'email',sortable:true,width:265},
{name:'number',index:'number',sorttype:'int',sortable:true,width:300},
],
pager:$('#pager'),
emptyrecords: "No Records to display",
pginput:true,
pgbuttons:true,
rowNum:10,
rowList:[5,10,20,30],
viewrecords:true,
sortorder: "desc",
//multiselect:true,
loadonce:true,
gridview:false,
sortname:'name',
caption: " Contacts List",
jsonReader: {
repeatitems : false,
cell:"",
id: "0"
},
height: 80
});
$("#list").jqGrid('navGrid','#pager',{edit:false,add:false,del:false,search:true},{multipleSearch:true});
});
This question/answer should contain information on how to redraw the jqgrid based on redefined table data: jqGrid add new column
Regarding the addition of a you might add a time stamp to each of the records, or even the value of a counter; something like:
var recordsSet = [];
$.each(databaseRecords, function(i, record) {
record.idx = Date.now();
record._id = i;
recordSet.push(record);
});
/* code to populate or redraw using update recordSet array jqgrid here */
You shoud then be able to assign either the _id field or the idx field (sample property names only) to the index property of your column models in the call to jqgrid.