Adding a Button to VUE datatables - javascript

I looking to add a button to each row in a datatable component in VUE 2
Currently data is feeding from axios request as per below
axios.get('workers/viewall').then(response => this.workerslist = response.data);
Added a prop in the Datatable.vue to give customButtons = True
customButtons: {
default: true
},
And added the below to my Vue file
customButtons: {
hide: false,
icon: 'search',
onclick: function (user_id) {
this.$router.push({
name: 'edit_worker',
params: {user_id: user_id}
});
},
},
Which is put into the data component here:
data: function () {
return {
workerslist: [],
and then column data is as follows:
columndata: [{
label: 'ID',
field: 'id',
numeric: true,
html: false,
},{
label: 'First name',
field: 'fname',
numeric: true,
html: false,
}, {
label: 'Surname',
field: 'sname',
numeric: false,
html: false,
}, {
label: 'Date of Birth',
field: 'dob',
numeric: false,
html: false,
}, {
label: 'Gender',
field: 'gender',
numeric: true,
html: false,
}, {
label: 'Trade',
field: 'trade',
numeric: false,
html: false,
}, {
label: 'Nationality',
field: 'nationality',
numeric: false,
html: true,
}, {
label: 'Telephone',
field: 'telephone',
numeric: false,
html: true,
}, {
label: 'Mobile',
field: 'mobile',
numeric: false,
html: true,
}, {
label: 'Created',
field: 'created_at',
numeric: false,
html: true,
},{
label: 'Edit',
field: 'edit',
numeric: false,
html: true,
}],
It just has to put a button to have a click through at the end of each row

Related

Retuning the value instead of item on filter the object

this is my method: I am trying to change the item.checked from true in to false and i need the same length of element returned. but getting different result.
const headerUpdate = this.tableSchema.headers.map((item) => {
return (item.checked ?? (item.checked = false)) || item;
});
result:
[{…}, {…}, {…}, {…}, true]
last element became true instead of item with false value.
Sample data added
headers: [
{
title: 'Primary Admin User ID',
label: 'adminUserName',
sortable: true,
dir: true,
sortType: 'string',
sortActive: true,
},
{
title: 'Name',
label: 'customerName',
sortable: true,
sortType: 'string',
dir: false,
},
{
title: 'Address',
label: 'address',
sortable: true,
link: false,
dir: false,
sortType: 'string',
disabled: true,
},
{
title: 'Phone Number',
label: 'phoneNum',
sortable: true,
link: false,
dir: false,
sortType: 'string',
disabled: true,
},
{
label: 'CheckBox',
link: false,
dir: false,
sortType: 'string',
disabled: true,
checkBox: true,
checked: false,
},
],
You have to either mutate the array with a forEach, or map and return a whole new object in the callback, because right now you have a kind of hybrid code between the two.
const headerUpdate = this.tableSchema.headers.map((item) => ({
...item,
...item.checked === undefined ? undefined : { checked: false },
}));

toggle show/hide table column and save to localstorage in vue

I would like to show and hide table column dynamically with checkbox and save it the option to localstore in vue 2. I find a jquery version but when I tried to use it did not worked.
I am a beginer in vue.
Thank you for your help.
My vue table:
export default {
extends: axiosGetPost,
props: ['id','tab_name', 'route_name'],
data() {
return {
hidePreLoader: true,
price: '',
purchase_price: '',
selling_price: '',
products: {},
tableOptions: {
tableName: 'products',
columnSelect : true,
columns: [
{
title: 'lang.item_image',
key: 'image',
type: 'images',
source: '/uploads/products',
imagefield: 'imageURL',
sortable: false
},
{title: 'lang.sku', key: 'sku', type: 'text', sortable: true},
{title: 'lang.sku_2', key: 'sku_2', type: 'text', sortable: true},
{title: 'lang.sku_3', key: 'sku_3', type: 'text', sortable: true},
{title: 'lang.sku_4', key: 'sku_4', type: 'text', sortable: true},
{title: 'lang.attribute_values', key: 'attribute_values', type: 'text', sortable: true},
{title: 'lang.quantity', key: 'test', type: 'text', sortable: true},
{title: 'lang.selling_price', key: 'selling_price', type: 'text', sortable: true},
{title: 'lang.receiving_price', key: 'purchase_price', type: 'text', sortable: true},
],
formatting : ['selling_price','purchase_price'],
source: '/products/variantDetails/' + this.id,
},
}
},
I run out of ideas.
Thank you for your help.
For this you need to set defaults so that the checkbox values first try to read from localStorage. Then create a method when the input is clicked to change the value and update the value set into storage.
Vue.use(VueTables.ClientTable);
new Vue({
el: "#app",
data: {
columns: ['name', 'code'],
columnHidden: {
name: localStorage.getItem('name') || false,
code: localStorage.getItem('code') || false
},
data: getData()
},
methods: {
toggleColumn(column) {
this.columnHidden[column] = !this.columnHidden[column];
localStorage.setItem(column, true);
}
}
});
function getData() {
return [{
code: "ZW",
name: "Zimbabwe"
}, {
code: "ZM",
name: "Zambia"
}, {
code: "YE",
name: "Yemen"
}];
}
<div id="app" v-cloak>
<template v-for="column in columns">
<label for=`toggleTable${column}`>{{`Toggle ${column}`}}</label>
<input v-on:click="toggleColumn(column)" id=`toggleTable${column}` type="checkbox" :checked="columnHidden[column]" />
<br />
</template>
<v-client-table :columns="columns" v-model="data">
</v-client-table>
</div>

How to populate koGrid Groups Array on initial load?

How can I populate a koGrid Groups Array? The last line of the following code is throwing an error:
gridOptions: {
data: ko.observableArray([{ name: 'John', title: 'Abc', age: 29, salary: 35000, company: "OATI" }, { name: 'Peter', title: 'XYZ', age: 35, salary: 70000, company: "Infogain" }]),
multiSelect: true,
showGroupPanel: true,
showColumnMenu: false,
showFilter: false,
columnsChanged: this.columnsChanged,
maintainColumnRatios: true,
enablePaging: true,
pagingOptions: this.pagingOptions,
hideChildren: false,
footerVisible: false,
displaySelectionCheckbox: false,
columnWidth: 1000,
columnDefs: ko.observableArray([
{ field: '_sortIndex', visible: false, displayName: "Random Sort", sortDirection: "asc" },
{ field: 'name', visible: true, displayName: "Name", selectable: true, groupIndex: 1, width: 150 },
{ field: 'title', visible: true, displayName: "Title", width: 150 },
{ field: 'age', visible: true, displayName: "Age", width: 150 },
{ field: 'salary', visible: true, displayName: "Salary", agg: "sum", width: 150 },
{ field: 'company', visible: true, displayName: "Company", width: '**' }
]),
groups: ['company'] // this code is throwing error. without this line it is working fine.
}
Can anyone explain what is wrong?

How to obtain data in javaScript before submitting form in JTable

Want to get data from JTable form but when I'm trying to get the data it says undefined.
This is customStudent.js
.......
$(document).ready(function() {
$('#StudentTableContainer').jtable({
title: 'Student List',
paging: true,
pageSize: 10,
sorting: true, //Enable sorting
defaultSorting: 'name ASC',
actions: {
listAction: actionRoom,
deleteAction: 'HallManagementServlet?action=DeleteStudent',
updateAction: 'HallManagementServlet?action=UpdateStudent',
},
fields: {
reg_id: {
title: 'Registration',
key: true,
sort: true,
create: true,
edit: false
},
name: {
title: 'Name',
width: '20%',
edit: true
},
dept_id: {
title: 'Department',
edit: true,
options: 'HallManagementServlet?action=dropDownDepartment',
width: '5%'
},
session: {
title: 'session',
edit: true,
width: '7%'
},
degree_type: {
title: 'Degree type',
width: '10%',
options: {'Bachelors/Honours': 'Bachelors/Honours', 'Masters': 'Masters'},
edit: true,
list: true
},
room_number: {
title: 'Room',
width: '5%',
edit: true,
options: 'HallManagementServlet?action=dropDownRooms'
},
date_of_birth: {
title: 'Date of Birth',
type: 'date',
displayformat: 'yyyy-mm-dd',
edit: true,
list: false
},
blood_group: {
title: 'Blood Group',
width: '10%',
options: {'O-': 'O-', 'O+': 'O+', 'A-': 'A-', 'A+': 'A+', 'B-': 'B-', 'B+': 'B+', 'AB-': 'AB-', 'AB+': 'AB+'},
edit: true,
list: false
},
contact_number: {
title: 'Phone',
width: '10%',
edit: true,
list: true
},
address_line_1: {
title: 'Address line 1',
width: '13%',
edit: true,
list: false
},
address_line_2: {
title: 'Address line 6',
width: '13%',
edit: true,
list: false
},
fathers_name: {
title: 'Father\'s Name',
width: '13%',
edit: true,
list: false
},
mothers_name: {
title: 'Mother\'s Name',
width: '13%',
edit: true,
list: false
},
email: {
title: 'E-mail address',
width: '5%',
edit: true,
list: false
},
hall_id: {
title: 'Hall',
create: false,
edit: false,
list: false
},
admitted_on: {
title: 'Admitted On',
type: 'date',
displayformat: 'yyyy-mm-dd',
create: true,
edit: true,
list: true
},
payment_expires_on: {
title: 'Payment expires on',
width: '11%',
type: 'date',
displayformat: 'yyyy-mm-dd',
create: false,
edit: true,
list: true
},
paymentStatus: {
title: 'Payment Status',
width: '8%',
options: {'Paid': 'Paid', 'Due': 'Due'},
create: false,
edit: false,
list: true
},
imageFile: {
title: "Image Upload",
list: false,
create: true,
edit: false,
input: function(data) {
return '<input id="docBytes" type="file" name="docBytes" accept="image/*"><iframe name="postiframe" id="postiframe" style="display: none" />';
}
}
},
formCreated: function(event, data) {
data.form.find('input[name="reg_id"]').addClass('validate[required,[custom[number]],minSize[10],maxSize[10]');
data.form.find('input[name="name"]').addClass('validate[required,[custom[onlyLetterSp]]');
data.form.find('input[name="mothers_name"]').addClass('validate[[custom[onlyLetterSp]]');
data.form.find('input[name="fathers_name"]').addClass('validate[[custom[onlyLetterSp]]');
data.form.find('input[name="email"]').addClass('validate[custom[email]]');
data.form.validationEngine();
},
//Validate form when it is being submitted
formSubmitting: function(event, data) {
return data.form.validationEngine('validate');
},
//Dispose validation logic when form is closed
formClosed: function(event, data) {
data.form.validationEngine('hide');
data.form.validationEngine('detach');
},
recordsLoaded: function(event, data) {
$('.jtable-data-row').click(function() {
var reg_id = $(this).attr('data-record-key');
window.location.assign("viewstudent.jsp?reg_id=" + reg_id);
});
}
});
//Re-load records when user click 'load records' button.
$('#LoadRecordsButton').click(function(e) {
e.preventDefault();
$('#StudentTableContainer').jtable('load', {
name: $('#name').val(),
reg_id: $('#registration').val(),
dept_id: $('#pd_dept').val(),
session: $('#pd_session').val(),
degree_type: $('#pd_degree_type').val()
});
});
//Load all records when page is first shown
$('#LoadRecordsButton').click();
});
More precisely to speak, I want to get the updated date from here:
payment_expires_on: {
title: 'Payment expires on',
width: '11%',
type: 'date',
displayformat: 'yyyy-mm-dd',
create: false,
edit: true,
list: true
},
What should I do to get the date? After getting the date i want to claculate something and show paymentStatus on Jtable.
updateAction: function(postData) {
var payment_date = [];
console.log("updating from custom function...");
return $.Deferred(function($dfd) {
$.ajax({
url: 'HallManagementServlet?action=UpdateStudent',
type: 'POST',
dataType: 'json',
data: postData,
success: function(data) {
$.each(data, function(entryindex, entry) {
payment_date.push(entry['payment_expires_on']);
});
alert(payment_date);
$dfd.resolve(data);
},
error: function() {
$dfd.reject();
}
});
});
}
Use this custom updateAction. It worked for me.

EXTJS Writer Grid - removal of row - client and serverside

At the moment when I remove a row - it reappears on the client side - refreshing the page I see it has indeed been deleted
Adding a store.reload in the method means it appears again and then disappears when the store is reloaded.
Any help appreciated
// The DataWriter component.
var writer = new Ext.data.JsonWriter({
encode: false
})
Ext.namespace('codeblender');
codeblender.app = function() {
/**
* Render the ground links
*
* #param val
* #param p
* #param record
* #return
*/
function rendererGroundLink(val, p, record) {
var string = record.data.ground;
var newContent = string.replace(/ /g, '-');
return ('' + record.data.ground + '');
}
// Public space
return {
// Public methods
init: function() {
// !Create the data store
var store = new Ext.data.JsonStore({
fields: [{
name: 'id',
type: 'int'
}, {
name: 'division_id',
type: 'int'
}, {
name: 'competition',
type: 'string'
}, {
name: 'date',
type: 'date',
dateFormat: 'Y-m-d'
}, {
name: 'time',
type: 'time'
}, {
name: 'referee',
type: 'string'
}, {
name: 'ground',
type: 'string'
}, {
name: 'team_a',
type: 'string'
}, {
name: 'score_a',
type: 'string'
}, {
name: 'scorer_a',
type: 'string'
}, {
name: 'team_b',
type: 'string'
}, {
name: 'score_b',
type: 'string'
}, {
name: 'scorer_b',
type: 'string'
}],
idProperty: 'id',
messageProperty: 'message',
pruneModifiedRecords: true,
remoteSort: true,
restful: true,
root: 'data',
sortInfo: {
field: 'date',
direction: "DESC"
},
successProperty: 'success',
totalProperty: 'totalCount',
url: '/restfixture',
writer: writer
});
store.load({
params: {
start: 0,
limit: 50,
sort: 'date',
dir: 'DESC'
}
});
// !Create the Team data store
var storeTeam = new Ext.data.JsonStore({
baseParams: {
status: 'Active'
},
fields: [{
name: 'id',
type: 'int'
}, {
name: 'team',
type: 'string'
}],
restful: true,
root: 'data',
sortInfo: {
field: 'team',
direction: "ASC"
},
url: '/restteam'
});
// !Create the Ground data store
var storeGround = new Ext.data.JsonStore({
fields: [{
name: 'id',
type: 'int'
}, {
name: 'ground',
type: 'string'
}],
restful: true,
root: 'data',
url: '/restground'
});
// !Create the Referee data store
var storeReferee = new Ext.data.JsonStore({
fields: [{
name: 'id',
type: 'int'
}, {
name: 'referee',
type: 'string'
}],
restful: true,
root: 'data',
url: '/restreferee'
});
// !Create the column model
var columns = [{
header: 'Division',
sortable: true,
dataIndex: 'division_id',
width: 75,
editor: {
allowBlank: false,
editable: false,
lazyRender: true,
mode: 'local',
store: [
[1, 'Division 1'],
[2, 'Division 2'],
[3, 'Division 3']
],
triggerAction: 'all',
xtype: 'combo'
}
}, {
header: 'Competition',
sortable: true,
dataIndex: 'competition',
editor: {
allowBlank: false,
editable: false,
lazyRender: true,
mode: 'local',
store: ['Season 8', 'Cup 8', 'Season 7', 'Cup 7', 'Season 6', 'Cup 6', 'Season 5', 'Cup 5', 'Season 4', 'Cup 4', 'Season 3', 'Cup 3', 'Season 2', 'Cup 2', 'Season 1', 'Cup 1'],
triggerAction: 'all',
xtype: 'combo'
}
}, {
header: 'Date',
sortable: true,
dataIndex: 'date',
xtype: 'datecolumn',
format: 'Y-m-d',
width: 100,
editor: {
allowBlank: false,
editable: true,
emptyText: 'Date',
format: 'Y-m-d',
xtype: 'datefield'
}
}, {
header: 'Time',
sortable: false,
dataIndex: 'time',
editor: {
allowBlank: false,
editable: false,
format: 'H:i:s',
increment: 5,
minValue: '09:00:00',
xtype: 'timefield'
}
}, {
header: 'Referee',
sortable: true,
dataIndex: 'referee',
editor: {
allowBlank: false,
displayField: 'referee',
editable: false,
emptyText: 'Select Referee',
forceSelection: true,
lazyRender: true,
mode: 'remote',
store: storeReferee,
triggerAction: 'all',
valueField: 'id',
xtype: 'combo'
}
}, {
header: 'Ground',
sortable: true,
dataIndex: 'ground',
renderer: rendererGroundLink,
editor: {
allowBlank: false,
displayField: 'ground',
editable: false,
emptyText: 'Select Ground',
forceSelection: true,
lazyRender: true,
mode: 'remote',
store: storeGround,
triggerAction: 'all',
valueField: 'id',
xtype: 'combo'
}
}, {
header: 'Team A',
sortable: true,
dataIndex: 'team_a',
editor: {
allowBlank: false,
displayField: 'team',
editable: false,
emptyText: 'Select Team A',
forceSelection: true,
lazyRender: true,
mode: 'remote',
name: 'team',
store: storeTeam,
triggerAction: 'all',
valueField: 'id',
xtype: 'combo'
}
}, {
header: 'Score A',
sortable: true,
dataIndex: 'score_a',
editor: {
xtype: 'spinnerfield'
}
}, {
header: 'Scorer A',
sortable: false,
dataIndex: 'scorer_a',
editor: {
xtype: 'textarea'
}
}, {
header: 'Team B',
sortable: true,
dataIndex: 'team_b',
editor: {
allowBlank: false,
displayField: 'team',
editable: false,
emptyText: 'Select Team B',
forceSelection: true,
lazyRender: true,
mode: 'remote',
name: 'team',
store: storeTeam,
triggerAction: 'all',
valueField: 'id',
xtype: 'combo'
}
}, {
header: 'Score B',
sortable: true,
dataIndex: 'score_b',
editor: {
xtype: 'spinnerfield'
}
}, {
header: 'Scorer B',
sortable: false,
dataIndex: 'scorer_b',
editor: {
xtype: 'textarea'
}
}
];
// Create the pager
var pagingBar = new Ext.PagingToolbar({
displayInfo: true,
displayMsg: '{0} - {1} of {2}',
emptyMsg: 'No Data',
pageSize: 50,
store: store
});
// Create the Grid
var grid = new xg.GridPanel({
bbar: pagingBar,
columns: columns,
height: 500,
iconCls: 'icon-grid',
loadMask: {
msg: 'Loading data.',
enabled: true
},
plugins: [rowEditor],
renderTo: 'dbGrid',
sm: new Ext.grid.RowSelectionModel({
singleSelect: true
}),
store: store,
stripeRows: true,
tbar: [{
text: 'Add',
iconCls: 'icon-add',
handler: function() {
var record = new store.recordType({
division_id: 1,
date: (new Date()).clearTime(),
time: '10:00:00',
referee: '',
ground: '',
team_a: '',
score_a: '',
team_b: '',
score_b: ''
});
grid.suspendEvents();
rowEditor.stopEditing();
grid.store.insert(0, record);
grid.getView().refresh();
grid.getSelectionModel().selectRow(0);
rowEditor.startEditing(0);
grid.resumeEvents();
}
}, {
iconCls: 'icon-del',
text: 'Remove Fixture',
handler: function() {
rowEditor.stopEditing();
grid.suspendEvents();
var record = grid.getSelectionModel().getSelected();
if (record) {
store.remove(record);
}
store.reload({}, true);
grid.resumeEvents();
}
}],
title: 'Fixtures',
viewConfig: {
forceFit: true
}
});
}
};
}();
Try:
grid.getView().refresh()
Instead of:
store.reload({}, true);

Categories