Ext-JS: How to disable cell editing for individual cells in a grid? - javascript

I am now building a web application with Ext-JS 4.0.2, and I am using a editable grid to control the data to be shown for a table on the same page.
To make the grid editable, I followed the API documentation and used the following:
selType: 'cellmodel',
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2
})
]
However, for this grid, there are several cells that are not supposed to be changed.
I could simply let the event handler change the data back to the right state once it is changed in the grid, but this seems to be hacky, hard to maintain, and unreadable. Is there any better way to do this? I read the API but cannot find any useful attributes.
UPDATE
As for this particular app, just disable the first row would work. But I am also interested in choose several grid and make them not editable (imagine a Sudoku game with a grid).

As I've understand from comments you want to make first row not editable. There is ugly but quick solution. Assign to your plugin beforeedit handler. And when event is being fired check what row is being edited. If first - return false:
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2,
listeners: {
beforeedit: function(e, editor){
if (e.rowIdx == 0)
return false;
}
}
})
]
Check out docs for beforeedit.
UPDATE
Docs say that beforeedit has such set of params:
beforeedit( Ext.grid.plugin.Editing editor, Object e, Object options )
But there is mistake. The correct sequance is:
beforeedit( Object e, Ext.grid.plugin.Editing editor, Object options )
I've updated example due to this fact.

You can specify ColumnModel to declare editable and not editable columns:
var cm = new Ext.grid.ColumnModel({
columns: [{
dataIndex: 'id',
header: 'id',
hidden: true
},{
dataIndex: '1',
header: '1',
editor: new Ext.form.TextField({})
},{
dataIndex: '2',
header: '2',
editor: new Ext.form.NumberField({})
},{
dataIndex: '3',
header: '3'
}]
});
var grid = new Ext.grid.EditorGridPanel({
store: store,
clicksToEdit: 2,
cm: cm
...
In this example column id is unvisible, columns 1 and 2 editable (with text and number editors) and column 3 is not editable.
UPDATE:
Prevent row editing:
grid.on('beforeedit', function(event) {
if (event.row == 0) {
this.store.rejectChanges();
event.cancel = true;
}
}, grid);

As Ziyao Wei mentioned the documentation for the beforeEdit event is wrong. However you need to reference the 'editor' parameter to get the row index and other values, not the first object parameter 'e'.
Updated example:
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2,
listeners: {
beforeedit: function(e, editor){
if (editor.rowIdx == 0)
return false;
}
}
})
]

Related

Disable movement of columns in agGrid

I'm using AgGrid table in my application. Here is the demo. According to the documentation i want to stop movement of the columns. For this i used:
suppressMovable: true
The above code I used here:
columnDefs: [
{
headerName: 'Athlete', //the generic name of header
children: [
{
field: 'athlete', //children header from generic header
width: 150,
suppressMovable:true
},
{
field: 'age',
lockVisible: true,
cellClass: 'locked-visible',
suppressMovable:true
},
{
field: 'country',
width: 150,
},
{ field: 'year' },
{ field: 'date' },
{ field: 'sport' },
],
...
suppressMovable:true, it works, and the athlete and age columns aren't possible to be moved like others, but this code also disable the movement of the main column: Athlete. So when i try to switch the place of Athlete and Medals columns, i can't, but i don't want this, i want to set this 2 main columns as movable.Question: How to disable movement of columns inside the Athlete and Column, but to keep the movement functionality of these 2 main columns?
Out of the box answer is you can't.
If any child is fixed, then AG Grid doesn't allow moving the group.
you can write custom event listener(if possible) to change the suppressMovable property of child columns while the parent column is being dragged and then again set them to not movable/suppressMovable to true. else you can programatically move all columns in a group using moveColumnByIndex(from,to)

Change Extjs Grid Validation Text

I'm looking at an older project that is using ExtJS. Admittedly, I'm not too familiar with this framework so I learn as I go and as I am asked to fix things. My issue is that there is a grid and each column uses allowBlank: false. This causes a tooltip box to display with some info about what field(s) need to be populated. This all works great, but I am trying to change that text in that tooltip i.e. "Error", "Benefit Category Name: This field is required", and I can't seem to make this work. How can I target and change that text? I'll include a screenshot of the grid and tooptip that I am talking about for reference. I am also using ExtJS version 6.
Here is a sample of one of the grid columns:
columns: [
{
dataIndex: 'benefit_category_name',
text: 'Benefit Category Name',
flex: 1,
editor: {
xtype: 'combo',
store: new Ext.data.ArrayStore({
fields: [
'benefit_category_id',
'benefit_category_name',
],
data: [],
}),
queryMode: 'local',
valueField: 'benefit_category_name',
displayField: 'benefit_category_name',
emptyText: 'Select one',
listeners: {
select: 'handleComboChange',
},
itemId: 'benefit_category_id',
allowBlank: false,
listeners: {
renderer: function(value, metaData) {
metaData.tdAttr = Ext.String.format('data-qtip="{0}"', value);
return value;
}
}
}
},
{
...
}
]
I tried to use the metaData property I read about in some other posts, but I can't seem to change the tooptip text (Error, Benefit Category Name: This field is required).
Here is a screenshot of the tooltip mentioned. I know this is an older framework, but any tips I could get would be useful. Thanks for your time.
Thats a simple validation example with custom message.
Ext.create({
xtype: 'textfield',
allowBlank:false, // will show required message - remove key to display vtypeText only
validateBlank: true,
vtype: 'alpha', // check for available types or create / extend one
vtypeText: 'Please change to what you want ...',
renderTo: Ext.getBody()
})
Details:
https://docs.sencha.com/extjs/6.5.3/classic/Ext.form.field.VTypes.html
https://fiddle.sencha.com/fiddle/3770

EXTJS 4.2 - Grid Panel Multiple grid sorting

When a grid panel sort is triggered on column 'Email', how do I force a ASC sort on column 'Name' first and then for EXTJS to perform a sort on column 'Email' next.
I found the following example which is in the right direction.. http://cdn.sencha.com/ext/gpl/4.2.0/examples/grid/multiple-sorting.html
...but I cannot see how I would implement this in a gridpanel when a user clicks on a column sort, the example uses buttons against the store directly...the only event I think I can use is gridpanel sortchange but it is a post sort event.
I create a fiddle example https://fiddle.sencha.com/#fiddle/imt where I put a sorter in the store
sorters: [{
property: 'Name',
direction: 'ASC'
}],
but after playing around with the other columns sorts in the grid, the sorter does not prioritize on 'Name' anymore.
Any recommendations ?
How about using the headerclick event on the grid. This takes the clicked column config as one of the params so based on that you could apply your own custom sorting to the underlying store.
But is it really a problem sorting twice? Otherwise you could override the headertriggerclick event of Ext.grid.header.ContainerView.
sortchange: function (ct, column, direction, eOpts ) {
var store = column.up('gridpanel').getStore();
store.sort([{
property : 'name',
direction: 'ASC'
}, {
property : column.dataIndex,
direction: direction
}]);
}
The problem was with the naming of the fields. You capitalized 'Name' in the sorters, but the actual field is 'name'.
fields: [
{name:'name'},
{name:'summaryId'},
{name: 'id'},
{name:'email'},
{name:'phone'},
],
When I changed it to 'name', it sorted with that and any other sorters supplied.
sorters: [{
property: 'name',
direction: 'ASC'
},{
property:'email',
direction: 'DESC'
}],

Create another toolbar in kendo grid

I am using Kendo library for grid. I want to have a toolbar in that grid.
I have followed this link -
http://demos.kendoui.com/web/grid/toolbar-template.html
and created a toolbar at the top
I also want to add another toolbar at the bottom of grid. Below or above pagination bar. I could not find any way to create this extra toolbar. Please help.
There are two ways of getting it:
You let Kendo UI generate in the top and then you move it to the bottom
You generate it to the bottom.
The first approach is fast and if you don't need header toolbar is the best. Just add the following code:
$("#grid).data("kendoGrid").wrapper.append($(".k-toolbar"));
See it here : http://jsfiddle.net/OnaBai/WsRqP/1/
The second approach -using as base the example that you mention in your original question- would be something like this:
Step 1: Define a template, you might use the same than in the example:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<label class="category-label" for="category">Show products by category:</label>
<input type="search" id="category" style="width: 150px"/>
</div>
</script>
Step 2: Initialize the grid, as you are doing now (in my case I will not include the toolbar as header but only as footer):
var grid = $("#grid").kendoGrid({
dataSource: {
type : "odata",
transport : {
read: "http://demos.kendoui.com/service/Northwind.svc/Products"
},
pageSize : 20,
serverPaging : true,
serverSorting : true,
serverFiltering: true
},
height : 430,
sortable : true,
pageable : true,
columns : [
{ field: "ProductID", title: "Product ID", width: 100 },
{ field: "ProductName", title: "Product Name" },
{ field: "UnitPrice", title: "Unit Price", width: 100 },
{ field: "QuantityPerUnit", title: "Quantity Per Unit" }
]
}).data("kendoGrid");
Step 3: Add a dataBound handler for creating the footer after the grid has been initialized. We have to do it on dataBound otherwise the Grid is still not correctly formatted and the footer will look wrong. I've implemented creating the footer toolbar in a separate function to do not mess dataBound in case you do more stuff here.
dataBound : function () {
initFooterToolbar(this, kendo.template($("#template").html()));
}
Step 4: Implement this initFooterToolbar:
function initFooterToolbar(grid, template) {
if (!this._footer) {
this._footer = $("<div class='k-toolbar k-grid-toolbar k-widget'></div>")
.append(template);
grid.wrapper.append(this._footer);
// Other code for initializing your template
...
}
}
What initFooterToolbar does is first check that it has not already been initialized otherwise if you do pagination of refresh the data you might end-up with multiple footer toolbars.
Finally append the toolbar to grid.wrapper.
So the important part for creating a footer toolbar is invoking grid.wrapper.append(...) and doing it when the grid is already created.
The original example modified here : http://jsfiddle.net/OnaBai/WsRqP/
I avoid using kendo toolbars and just make an external 1 which you can then tweak with greater control.
For example,
#Html.DropDownList("Year", (SelectList)ViewBag.YearList, "All years")
transport: {
read: {
url: '#Url.Action("_List", "Applications")',
data: refreshGridParams,
type: 'POST'
},
function refreshGridParams() {
return {
Year: $('#Year').val()
};
}
$('#Year').change(function () {
theGrid.dataSource.read({
Year: $('#Year').val()
});
});
Then in my controller,
[HttpPost]
public JsonResult _List(int? Year, int skip, int take)
{
Last
_db.Blargh.Where(w => w.Year== Year).Skip(skip).Take(take).ToList().ForEach(x => { waList.Add(new WAListDTO(x)); });
This should cover all the core code needed but means you can keep adding as many toolbars/dropdowns/datepickers/text searchs or etc and just alter each stage to include the additional data.
Here is another hack which uses column footertemplate. When databound is triggered, footertemplate table is arranged to have one column with colspan equals to the number of grid columns.
http://plnkr.co/edit/1BvMqSC7tTUEiuw4hWZp
$("#grid").kendoGrid({
columns:[{
field:'name',
footerTemplate : "Row Count: #= data.name.count #"
},{
field:'age'
}],
dataSource: new kendo.data.DataSource({
aggregate: [{
field:"name",
aggregate: "count"
}],
data: [{
name: "Jane",
age: 31
}, {
name: "John",
age: 33
}]
}),
dataBound: function() {
var footer = this.wrapper.find('.k-footer-template');
footer.children(":first").attr('colspan', this.columns.length);
footer.children().not(':first').remove();
}
});

ExtJS grid with pagination, instead of combobox

I am creating a list of items, that are in combobox, but I am asked to create it with grid and to include pagination. Is it possible to create a grid with list of items, and then select them like in dropdown menu (with multiselect feature) and when clicked a submit button get the values and process it through php file.?
My thoughts: Grid is for displaying list of information, and the text in grid can be link text. But as far as I know you can't select item from grid then process by clicking submit buttons.
Anyways, whats the best way of doing it? And if its not possible with neither one of the methods, can I use multiselect to make the list? With displayfield and valuefield?
Well, you can add checkbox to each item in grid and then do some action to selected items.
Ext.define('Your.items.Grid' ,{
extend: 'Ext.grid.Panel',
title : 'Grid with checkboxes',
store: 'Items',
// This line adds checkboxes
selModel: Ext.create('Ext.selection.CheckboxModel'),
columns: [
// Some columns here
],
initComponent: function() {
this.dockedItems = [{
xtype: 'toolbar',
items: [{
itemId: 'process',
text: 'Process',
action: 'process' // Bind to some action and then process
}]
},
{ // Here is pagination
xtype: 'pagingtoolbar',
dock:'top',
store: 'Items',
displayInfo: true,
displayMsg: 'Displaying items {0} - {1} of {2}',
emptyMsg: "No items to display"
}];
this.callParent(arguments);
}
});
Hope I understood your question correctly

Categories

Resources