Bootstrap-Table: Expand rows that are not hidden - javascript

I have filters set up that will hide certain rows of my bootstrap-table. I have also implemented the "expandAllRows" method to display all detail-views; however, this method will expand ALL rows including those that are hidden by my filters.
How would I modify bootstrap-table.min.js in order to only show the detail-views of the rows that are visible?
I believe I need to modify the line from bootstrap-table.min.js but not sure how:
...{key:"expandAllRows",value:function(){for(var t=this.$body.find("> tr[data-index][data-has-detail-view]"),e=0;e<t.length;e++)this.expandRow(i.default(t[e[).data("index"))}...
I am using the bootstrap-table buttons method to add the custom buttons for expanding and collapsing the rows. See below:
function buttons() {
var $table = $('#table')
var $expand = $('#expand')
var $collapse = $('#collapse')
return {
btnExpand: {
text: 'Expand All Rows',
icon: 'fas fa-angle-double-down',
event: function() {
$table.bootstrapTable('expandAllRows')
},
attributes: {
title: 'Expand all rows'
}
},
btnCollapse: {
text: 'Collapse All Rows',
icon: 'fas fa-angle-double-up',
event: function() {
$table.bootstrapTable('collapseAllRows')
},
attributes: {
title: 'Collapse all rows'
}
}
}
}

Rather than modify bootstraps' functions, maybe you could just circumvent them by renaming the attribute when you filter them. Something like this
function filter(keyword) {
// your current filter logic, which hides the rows that don't match
// in this example, you have hidden them with the class 'hidden-row'
let hiddenRows=$("tr.hidden-row[data-has-detail-view='true']");
hiddenRows.each( function() {
$(this).attr({
'data-has-detail-view-hidden': 'true'
})
.removeAttr('data-has-detail-view');
})
}
function clearFilters() {
// your logic, then
let hiddenRows=$("tr.hidden-row[data-has-detail-view-hidden='true']");
hiddenRows.each( function() {
$(this).attr({
'data-has-detail-view': 'true'
})
.removeAttr('data-has-detail-view-hidden')
.removeClass('hidden-row');
})
}

Related

ag-grid: Using Javascript, find the row id for a given data

I have a list of employees and I want to find the “id” of the row where firstName=Bob which is unique. In other words, I know the firstName supplied as “Bob” and now, I just need to find the row id using Javascript for ag-grid.
According to the documentation https://www.ag-grid.com/javascript-grid/accessing-data/ and I see that the rowNode can be got by using
getRowNodeId: data => data.id,
But I am just unable to to send the parameters (Bob), so that ag-grid finds and puts the id in some assigned variable. I think foreachloop is unnecessary to iterate each and every row, in case if the dataset is too big, then it will be an overhead.
I have the index.html file and a cellRenderer script as shown below. When the circle icon is clicked, I get the row Id correctly, but I am unable to retrieve the firstName, lastName etc.
I tried in two ways (i) writing the evenlistener inside the cellRenderer class, but most convenient for is to take this event listener as a function out of the cell Renderer file. (ii) So, I added a function called getAlert() which you can see as commented. Nothing works for me.
index.html
<div id="myGrid" style="height: 800px; width:100%;" class="ag-theme-alpine"></div>
<script>
var colSpan = function (params) {
return params.data === 2 ? 3 : 1;
};
const columnDefs = [
{ headerName:'FIRST NAME',field: "firstName", width:100, cellClass: 'my-class', colSpan: colSpan,},
{ headerName:'LAST NAME',field: "lastName", cellClass: 'my-class', flex: 6,},
{ headerName:'DESIGNATION (%)',field: "designation", cellClass: 'my-class', flex: 1,},
{ headerName:'INFO', field: "row_id",flex: 2, cellRenderer: 'infoCellRenderer'},
{ headerName:'COMMAND',field: "action",flex: 2,},
];
// let the grid know which columns and what data to use
const gridOptions = {
defaultColDef: {
resizable: true,
},
columnDefs: columnDefs,
getRowNodeId: data => data.id,
onGridReady: event => console.log('The grid is now ready'),
components:{
infoCellRenderer: InfoCellRenderer,
},
};
/*function getAlert(params)
{
console.log(params.node.firstName+","+params.firstName+","+params.value);
}*/
document.addEventListener('DOMContentLoaded', function () {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
//gridOptions.api.refreshView();
agGrid
.simpleHttpRequest({
url: 'XXXXXXX',
})
.then((data) => {
gridOptions.api.setRowData(data);
});
});
</script>
cellRenderer class
class InfoCellRenderer {
constructor() {}
// gets called once before the renderer is used
init(params) {
// create the cell
this.eGui = document.createElement('div');
this.eGui.innerHTML = '<i class="fas fa-info-circle"></i>';
// get references to the elements we want
this.circleValue = this.eGui.querySelector('.circle');
// add event listener to button
this.cellValue = this.getValueToDisplay(params);
//this.eventListener = () => getAlert('${params}');
this.eventListener = () => console.log(`${params.node.id},${params.node.firstName},${params.node.row_id}`);
this.circleValue.addEventListener('click', this.eventListener);
}
getGui() {
return this.eGui;
}
// gets called whenever the cell refreshes
refresh() {
// set value into cell again
this.cellValue = this.getValueToDisplay(params);
//this.eValue.innerHTML = this.cellValue;
// return true to tell the grid we refreshed successfully
return true;
}
// gets called when the cell is removed from the grid
destroy() {
// do cleanup, remove event listener from button
if(this.circleValue) {
// check that the button element exists as destroy() can be called before getGui()
this.circleValue.removeEventListener('click', this.eventListener);
}
}
getValueToDisplay(params) {
return params.valueFormatted ? params.valueFormatted : params.value;
}
}
if firstName is unique you can do as followed:
this.gridOptions.getRowNodeId = data => {
return data.firstName;
};
this code tells ag-grid to use firstName as its internal row Id. so you can easily get the row by:
const node = this.gridApi.getRowNode('Bob');
see link (note // ********* comments ) for full example
gridOptions.api.getModel().forEachNode(
function(rowNode, index){
if (rowNode.data.firstName == "Bob") {
row_index = index;
row = gridOptions.api.getModel().rowsToDisplay[row_index];
data_dict = row.data;
// do something with your row data, data_dict
}
}
);

Problem with variable scope in nested Backbone views

I have a parent view which contains a Backgrid view. In the parent view's initialize section I define a variable isWellSelected. The variable is toggled in the Backgrid column logic when a tickbox is checked. I am able to watch the variable toggled when a box is ticked and unticked.
However, once an event fires the variable is no longer in scope for the event to see. I suspect I may need to pass the variable to the Backrgrid view but I am unsure how to do that correctly. Please advise.
app.wellCollectionView = Backbone.View.extend({
template: _.template($('#wellTemplate').html()),
initialize: function() {
this.isWellSelected = false;
// isWellSelected toggled to true when a tickbox is checked in the columns block.
var columns = [...];
// instantiate collection
var wellCollection = new app.wellCollection;
// Set up a grid view to use the pageable collection
var wellGrid = new Backgrid.Grid({
columns: columns,
collection: wellCollection
});
// Initialize the paginator
var paginator = new Backgrid.Extension.Paginator({
collection: wellCollection
});
// Render the template
this.$el.html(this.template());
// Render the grid
this.$el.append(wellGrid.render().el);
this.$el.append(paginator.render().$el);
wellCollection.fetch({reset: true}).then(function () {...});
},
events: {
'click #EvaluateWell': function(){
this.evalWell(event, this.isWellSelected);
console.log("In events - isWellSelected: " + this.isWellSelected);}
},
// More stuff
}
Constructive feedback welcome.
Thanks!
Adding a snippet for "columns" as per JT's request:
var columns = [
{
name: '',
label: 'Select',
cell: Backgrid.BooleanCell.extend({
events : {
'change': function(ev){
var $checkbox = $(ev.target);
var $checkboxes = $('.backgrid input[type=checkbox]');
if($checkbox.is(':checked')) {
$checkboxes.attr("disabled", true);
this.isWellSelected = true;
// Disable all checkboxes but this one
$checkbox.removeAttr("disabled");
} else {
// Enable all checkboxes again
$checkboxes.removeAttr("disabled");
this.isWellSelected = false;
}
}
}
})
}, {
name: "api",
label: "API",
editable: false, // Display only!
cell: "string"
}, {
name: "company",
label: "Operator",
editable: false, // Display only!
cell: "string"
}];

Enabling custom button (disabled by default) when row is selected

I have a DataTable displaying data for Branches with two custom buttons defined: Add and Update. They are initialized at the top of the Javascript section
var buttons;
var tblBranch;
$.fn.dataTable.ext.buttons.add = {
className: 'button-add',
text: "Add Branch",
action: function (dt) {
onBtnAddClicked()
}
};
$.fn.dataTable.ext.buttons.update = {
className: 'button-update',
text: "Update",
action: function (dt) {
onBtnUpdateClicked()
}
};
I'd like to disable the Edit button on page load and only enable it to be clickable when a row has been selected. Problem is, I'm using custom buttons and I can't find anything on datatables.net about how to enable/disable them depending on conditions. So far what I've tried is this:
tblBranch = $("#tblBranches").DataTable({
dom: 'Blfrtip',
buttons: {
buttons :[
'add', 'update'
]
}
select: true;
})
$("#tblBranches tbody").on('click', 'tr', function () {
if (tblBranch.row(this).hasClass('selected')) {
$('button-update').removeClass("DTTT_disabled");
}
else {
table.$('tr.selected').removeClass('selected');
$('button-update').addClass("DTTT_disabled");
}
});
But I don't know what the code to disable the Edit button when the page loads should be like, and I've looked here, here, here and here.
Thanks for any guidance.
The last link you are referring to hold the solution you are looking for. But the documentation is a little bit vague, guess it need a solid example. It is not clear how you create the buttons (you show both methods) but below is an inline example, it would work with constructor as well. Simply give the button a class, like .edit and set it to disabled from start :
var table = $('#example').DataTable( {
dom: 'Bfrtip',
select: true,
buttons: [
{
text: 'Edit',
className: 'edit',
enabled: false,
action: function (e, dt, node, config) {
//do something
}
},
{
text: 'Add',
action: function (e, dt, node, config) {
//do something
}
}
]
})
Then use the Select plugins select and deselect events to update the enabled status of the .edit button :
$('#example').on('select.dt deselect.dt', function() {
table.buttons( ['.edit'] ).enable(
table.rows( { selected: true } ).indexes().length === 0 ? false : true
)
})
demo -> https://jsfiddle.net/pmee6w2L/

kendo grid dynamic field-editable definition

I have kendo-ui grid, with some fields.
I need one of the fields to be editable on add new row, and not editable on update row.
I try to change data-source definitions before add row, and change it back before update.
But the changing doesn't help.
Is there any way to do it?
Here is what I tried to do:
var schema = {
data: 'results',
model: {
id: 'GroupCode',
fields: {
GCode: { editable: false },
GroupPrincipalId: { editable: false },
GroupPrincipalName: { editable: false },
ChildCount: { editable: true },
}
}
};
onAddClick: function(){
var gridElement = ('#myGrid').data('kendoGrid');
gridElement.dataSource.options.schema.model.fields.GroupPrincipalId.editable = true;
gridElement.dataSource.options.schema.model.fields.GroupPrincipalName.editable = true;
gridElement.addRow();
}
(onAddClick is called by my custom adding-button, not related to kendo-adding-logic);
You can use the approach described here:
http://www.telerik.com/forums/making-column-as-readonly-on-update-and-editable-on-insert-in-grid
When create button is pressed you mark a variable as isCreating and in the edit section you check it and if is false you disable the requiered field/fields.

Toolbar menu in Kendo UI grid cell, which row was menu clicked from?

I have a Kendo UI grid in which the first column contains a menu where the user can select an Action to perform on the item.
I am using a Kendo UI toolbar, with only the overflow icon (I could not find a better option, there seems to be no standalone drop down menu in the suite).
HTML:
<div ng-controller="myController">
<div kendo-grid="lineGrid" k-options="lineGridOptions"></div>
</div>
MyController.js, column definitions:
columns: [{
field: "Action",
template: "<div id='lineToolbarDiv' kendo-toolbar='lineToolbar' k-options='lineToolbarOptions' class='button-group-toolbar'></div>",
width: "80px",
attributes: { lineNo: "#= lineNo #" }
}, {
field: "itemNo", title: "Item #"
}
],
MyController.js, toolbar definition:
$scope.lineToolbarOptions = {
items: [{
type: "button", id: "menuItemA", text: "Do A", overflow: "always"
}, {
type: "button", id: "menuItemB", text: "Do B", overflow: "always"
}],
click: function (e) {
console.log("click", e.target.text());
if (e.id.indexOf("menuItemA") === 0) {
alert(e.id);
} else if (e.id.indexOf("menuItemB") === 0) {
alert(e.id);
}
}
};
Plunker: http://plnkr.co/edit/FJJmoKyAh3JoOVicUGKB?p=preview
Question: In the above click handler for the toolbar, how do I know what row they used the menu on?
Also, if there is a cleaner standalone Kendo menu or similar (that matches the blueopal theme), that could be of interest (and might make this easier).
For solving your question you need to know that in click event handler this refer to the toolbar and this.element is the HTML element.
If you do:
click: function(e) {
// Get the HTML row (tr) that contains the toolbar
var row = this.element.closest("tr");
// Get its index in the table
console.log("row", row.index());
...
}
If you need to get access to the data item in the Grid DataSource you should use dataItem method in KendoUI grid. This is something like:
click: function(e) {
// Get the HTML row (tr) that contains the toolbar
var row = this.element.closest("tr");
// Get its index in the table
console.log("row", row.index());
// Get the item from the Grid DataSource
var item = $scope.lineGrid.dataItem(row);
// Show it in the console
console.log("item", item);
...
}

Categories

Resources