PDA

View Full Version : [CLOSED] Set RowSelectionModel on a inserted row.



PriceRightHTML5team
Oct 08, 2013, 9:47 AM
Hi Mine is as razor view engine application.
I have a gridpanel to which I have applied script for inserting row in gridpanel.

var r = Ext.create('TestGridModel', storeData);
var storeSt = Ext.getStore('Store1');
storeSt.insert(rowindex + 1, r); // insert a new record into the store
addedRecords.push({ "PageNo": pageNo, "rowIndex": rowindex + 1, "record": r });
App.TestGrid.editingPlugin.startEditByPosition({ row: rowindex, column: 0 });

the above code works fine.
The issue I am facing is - I am not able to select the inserted row either through mouse click or key board up down.
I have

Html.X().CellEditing().Listeners(ls => ls.BeforeEdit.Fn = "cellEdit")
when ever user dbl click a cell in added row for cell editing I use following script

var rowIndex = App.TestGrid.getSelectionModel().selected.items[0].index;//Get the selected row index
to get edit rowindex in rowindex variable. Unforcunatly the original row cell gets changed for editing.

Daniil
Oct 08, 2013, 12:21 PM
Hi @PriceRightHTML5team,

Please don't rely on a record's index. I mean here:

...selected.items[0].index

It is not in API.

Please clarify do you use in the cellEdit function? An index of edited row is passed an an argument of a BeforeEdit listener.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.grid.plugin.CellEditing-event-beforeedit

PriceRightHTML5team
Oct 08, 2013, 1:03 PM
Hi Daniil,
I changed the script to get rowindex from


App.TestGrid.getSelectionModel().selected.items[0].index;
to

e.rowIdx;

I still face the same issue.
If the rowIdx of original row is 2 I inserted row at index "3"


var r = Ext.create('TestGridModel', storeData);
var storeSt = Ext.getStore('Store1');
storeSt.insert(rowindex + 1, r);
App.TestGrid.editingPlugin.startEditByPosition({ row: rowindex, column: 0 });

in cellEdit function ("BeforeEdit listener") the rowIdx is 2 itself even though when I double click on newly added row (I suppose rowIdx should have been "3").

Daniil
Oct 08, 2013, 3:11 PM
Could you, please, provide a test case? Maybe, there is a bug.

PriceRightHTML5team
Oct 09, 2013, 5:53 AM
Hi Daniil,
Following is my cshtml

@{
ViewBag.Title = "Test";
var X = Html.X();
Layout = "~/Views/Shared/_Layout.cshtml";
}
@System.Web.Optimization.Scripts.Render("~/RP/bundles/RPScripts")

@(Html.X().ResourceManager(ViewBag.ManagerConfig as MvcResourceManagerConfig).RenderStyles(ResourceLoc ationType.None))
<h2>Test</h2>



@(
Html.X().FormPanel().ID("FRM").Items(
Html.X().GridPanel().ID("TestGrid")
.Title("Editable GridPanel")
.Width(600)
.Height(350)
.Store(Html.X().Store().PageSize(3).Listeners(ls => ls.Load.Fn = "storeLoad")
.ID("Store1")
.Proxy(Html.X().AjaxProxy()
.Url(Url.Action("GetData"))
.Reader(Html.X().JsonReader().Root("data"))
)
.Model(Html.X().Model().IDProperty("IdCol").Name("TestGridModel")
.IDProperty("IdCol")
.Fields(
new ModelField("IdCol", ModelFieldType.Int),
new ModelField("NameCol", ModelFieldType.String),
new ModelField("AgeCol", ModelFieldType.Int)
)
)

)
.ColumnModel(
Html.X().Column()
.Text("IdCol")
.DataIndex("IdCol")
.Flex(1),
Html.X().Column()
.Text("NameCol")
.DataIndex("NameCol")
.Editor(Html.X().TextField().Listeners(ls => ls.Blur.Fn = "cellTxtBlur")),
Html.X().Column()
.Text("AgeCol")
.DataIndex("AgeCol")
.Editor(Html.X().NumberField().Listeners(ls => ls.Blur.Fn = "cellBlur"))
)
.SelectionModel(Html.X().RowSelectionModel().ID("TestGridRowSelectionModel"))
.Plugins(
Html.X().CellEditing().Listeners(ls => ls.BeforeEdit.Fn = "cellEdit")
)
.BottomBar(Html.X().PagingToolbar().ID("PageBar").HideRefresh(true))
.Listeners(l => l.ItemContextMenu.Handler = "onContextMenu(e,this.store.getAt(index),index,#{Gr idPriceEntryContextMenu})")

.Features
(
Html.X().RowWrap())
))
@(
X.Container(
).ID("cntButton").Items(X.Button().ID("btnSave").Text("Save").Type(ButtonType.Submit).Handler("Save")
))
@(X.Menu().ID("GridPriceEntryContextMenu").Width(100).MaxHeight(50)
.Items(X.MenuItem()
.Text(PR.Resources.RP.RP.PEContextAddRow)
.Listeners(l => l.Click.Handler = "onClick(this,'Add Row')")
))
<script>
function Save() {
for (var i = 0; i < changedRows.length; i++) {
alert("PKColValue : " + changedRows[i].PKColValue + " Field : " + changedRows[i].Field + " New Value : " + changedRows[i].NewValue);
}
}
var addedRecords = [];
var changedRows = [];
var fieldname = null;
var pageNo = 0;
var cellEdit = function (editor, e) {
for (var i = 0; i < changedRows.length; i++) {
if (changedRows[i].IsEdited == false) {
changedRows.splice(i, 1);
}
}
fieldname = e.field;
pageNo = $('#PageBar').find('input[type="text"]').val();
var rowIndex = e.rowIdx;//App.TestGrid.getSelectionModel().selected.items[0].index;//Get the selected row index
//var pageSize = '@Convert.ToInt32(PriceRight.Settings.PropertyRead er.GetProperty("GRID_PAGE_SIZE"))'
var pageSize = 3;
if (pageNo > 1) {
rowIndex = rowIndex - ((pageNo - 1) * pageSize);
}
changedRows.push({ "IsEdited": false, "Field": e.field, "PageIndex": pageNo - 1, "RowIndex": rowIndex, "PKColValue": e.view.store.data.items[rowIndex].data.IdCol, "NewValue": "" });
return true;
}

var cellBlur = function (object) {
changedRows[changedRows.length - 1].NewValue = object.lastValue;
changedRows[changedRows.length - 1].IsEdited = true;

}

var cellTxtBlur = function (object) {
changedRows[changedRows.length - 1].NewValue = object.lastValue;
changedRows[changedRows.length - 1].IsEdited = true;

}

var storeLoad = function () {
for (var i = 0; i < App.TestGrid.store.getCount() ; i++) {
for (var j = 0; j < changedRows.length; j++) {
if (App.TestGrid.store.getAt(i).get('IdCol') == changedRows[j].PKColValue) {
App.TestGrid.store.getAt(i).set(changedRows[j].Field, changedRows[j].NewValue);
}
}

}
var pageNo = $('#PageBar').find('input[type="text"]').val();
var storeSt = Ext.getStore('Store1');
for (var i = 0; i < addedRecords.length; i++) {
if (addedRecords[i].PageNo==pageNo) {
storeSt.insert(addedRecords[i].rowIndex, addedRecords[i].record);
}
}
}



var rowindex = null;
var paras = new Array();
var storeData = null;
var originalRecord = null;

// opens application specific context menu
var onContextMenu = function (e, currentRecord, index, priceEntryMenu) {
rowindex = index;
e.preventDefault();
var rec = currentRecord;
originalRecord = currentRecord.data;
storeData = JSON.parse(JSON.stringify(currentRecord.data));
priceEntryMenu.dataRecord = rec.data;
priceEntryMenu.showAt(e.getXY());
};

// On Selecting a option from application specific contextmenu Adds a new row to price entry grid , Deletes a row respectively
var onClick = function (grid, text) {
if (text == "Add Row") {
storeData.IsAddedRow = true;
var r = Ext.create('TestGridModel', storeData);
var storeSt = Ext.getStore('Store1');
storeSt.insert(rowindex + 1, r); // insert a new record into the store (also see add)
pageNo = $('#PageBar').find('input[type="text"]').val();
var rowIndex = App.TestGrid.getSelectionModel().selected.items[0].index;//Get the selected row index
//var pageSize = '@Convert.ToInt32(PriceRight.Settings.PropertyRead er.GetProperty("GRID_PAGE_SIZE"))'
var pageSize = 3;
if (pageNo > 1) {
rowIndex = rowIndex - ((pageNo - 1) * pageSize);
}
addedRecords.push({ "PageNo": pageNo, "rowIndex": rowindex + 1, "record": r });
App.TestGrid.getSelectionModel().select(App.TestGr id.store.getAt(rowIndex+1))
App.TestGrid.editingPlugin.startEditByPosition({ row: rowindex, column: 0 });
return false;
}
};
</script>

Following are my controller action methods

[AllowAnonymous]
public ActionResult Test()
{
return View();
}

[AllowAnonymous]
public ActionResult GetData(StoreRequestParameters parameters)
{
return this.Store(Paging(parameters));
}

private Paging<DummyData> Paging(StoreRequestParameters parameters)
{
return Paging(parameters.Start, parameters.Limit, parameters.SimpleSort, parameters.SimpleSortDirection, null);
}

private Paging<DummyData> Paging(int start, int limit, string sort, SortDirection dir, string filter)
{

List<DummyData> data = new List<DummyData>();
data.Add(new DummyData() { IdCol = 1, NameCol = "First", AgeCol = 25 });
data.Add(new DummyData() { IdCol = 2, NameCol = "Second", AgeCol = 35 });
data.Add(new DummyData() { IdCol = 3, NameCol = "Third", AgeCol = 30 });
data.Add(new DummyData() { IdCol = 4, NameCol = "Fourth", AgeCol = 25 });
data.Add(new DummyData() { IdCol = 5, NameCol = "Fifth", AgeCol = 35 });
data.Add(new DummyData() { IdCol = 6, NameCol = "Sixth", AgeCol = 30 });

if (!string.IsNullOrEmpty(filter) && filter != "*")
{
//data.RemoveAll(plant => !plant.Common.ToLower().StartsWith(filter.ToLower( )));
}

if (!string.IsNullOrEmpty(sort))
{
data.Sort(delegate(DummyData x, DummyData y)
{
object a;
object b;

int direction = dir == SortDirection.DESC ? -1 : 1;

a = x.GetType().GetProperty(sort).GetValue(x, null);
b = y.GetType().GetProperty(sort).GetValue(y, null);

return CaseInsensitiveComparer.Default.Compare(a, b) * direction;
});
}

if ((start + limit) > data.Count)
{
limit = data.Count - start;
}

List<DummyData> rangePlants = (start < 0 || limit < 0) ? data : data.GetRange(start, limit);

return new Paging<DummyData>(rangePlants, data.Count);
}

and Following is my ViewModel


public class DummyData
{
public int IdCol { get; set; }
public string NameCol { get; set; }
public int AgeCol { get; set; }
}

Daniil
Oct 09, 2013, 8:12 AM
Thank you.

Some notes regarding the test case.

1. The first note.

Layout = "~/Views/Shared/_Layout.cshtml";

I don't have _Layout.cshtml. Also I think it is not required at all. Please get rid of such things in test cases.

2. The second note.

.Text(PR.Resources.RP.RP.PEContextAddRow)

I had to remove it to get the code compilable. Please provide us with runnable test cases which we can copy, paste and run without any changes from our side.

3. Finally, running the test case I got "$ is undefined". It is because of JQuery is not loaded. I don't think JQuery is required to reproduce the problem. If it is required for some reason, please provide CDN links like:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

As for the issue.

What are the steps to reproduce the problem?

I tried to put this


alert(e.rowIdx);
into the BeforeEdit listener. It seems to show correct indexes.

PriceRightHTML5team
Oct 09, 2013, 9:07 AM
Hi Daniil,
Following are the steps to reproduce issue.
1) right click on any of the gridpanel rows . You will get context menu with "Add Row" option.
2) Click on "Add Row" - it will insert a copy of current row below.
3) Double click the Name or Age column cell(s).

Expected : added row cell should turn into a editable field.
Actual : the original row cell turning into a editable field.

Daniil
Oct 09, 2013, 12:05 PM
Thank you.

It is an id conflict.

You insert a record with the same IdCol which is the Model's IDProperty. Since you are using it as IDProperty it must be unique.

PriceRightHTML5team
Oct 10, 2013, 5:25 AM
Hi Daniil,
I updated the code to generate a unique value for the IDProperty column

var r = Ext.create('TestGridModel', storeData);
r.data.IdCol = parseInt(Math.floor((Math.random() * (1000 - 100) + 100) + 1));
var storeSt = Ext.getStore('Store1');
storeSt.insert(rowindex + 1, r); // insert a new record into the store (also see add)

My sample data store has IDCol values 1,2,3,4,5,6.

Above script generates a random number between range 100 to 1000, thus unique.

Unfortunately the problem still persists.
7024
I double click the NameCol cell in third row (having IDCol 297) it turn second row corresponding cell into field.

Am I missing some thing

geoffrey.mcgill
Oct 10, 2013, 5:26 AM
Hello PriceRightHTML5team,

For all future posts in these forums, you must provide a runnable sample that accurately demonstrates how to reproduce the problem.

If we cannot reproduce the problem, your thread will not receive a response and will be moved from the Premium Help forum to the general Help forum.

Please do not post again in the forums without first reviewing and agreeing to the following guidelines:

http://forums.ext.net/showthread.php?3440-Forum-Guidelines-For-Posting-New-Topics

Additional tips for posting in the forums are provided at the following location:

http://forums.ext.net/showthread.php?10205-More-Information-Required

Please ensure all members of the PriceRightHTML5team submitting questions (now or in the future) to the Ext.NET forums are aware of and agree to the above guidelines.

If you have any questions regarding the forum guidelines, please feel free to contact me directly (geoff@object.net).

PriceRightHTML5team
Oct 10, 2013, 6:07 AM
Hi,

Following is my cshtml



@{
ViewBag.Title = "Test";
var X = Html.X();
Layout = null;
}
<html>
<head>
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function Save() {
alert(App.TestGrid.getSelectionModel().getCount()) ;
for (var i = 0; i < changedRows.length; i++) {
alert("PKColValue : " + changedRows[i].PKColValue + " Field : " + changedRows[i].Field + " New Value : " + changedRows[i].NewValue);
}
}
var addedRecords = [];
var changedRows = [];
var fieldname = null;
var pageNo = 0;
var cellEdit = function (editor, e) {
for (var i = 0; i < changedRows.length; i++) {
if (changedRows[i].IsEdited == false) {
changedRows.splice(i, 1);
}
}
fieldname = e.field;
pageNo = $('#PageBar').find('input[type="text"]').val();
var rowIndex = e.rowIdx;//App.TestGrid.getSelectionModel().selected.items[0].index;//Get the selected row index
//var pageSize = '@Convert.ToInt32(PriceRight.Settings.PropertyRead er.GetProperty("GRID_PAGE_SIZE"))'
var pageSize = 3;
if (pageNo > 1) {
rowIndex = rowIndex - ((pageNo - 1) * pageSize);
}
changedRows.push({ "IsEdited": false, "Field": e.field, "PageIndex": pageNo - 1, "RowIndex": rowIndex, "PKColValue": e.view.store.data.items[rowIndex].data.IdCol, "NewValue": "" });
return true;
}

var cellBlur = function (object) {
changedRows[changedRows.length - 1].NewValue = object.lastValue;
changedRows[changedRows.length - 1].IsEdited = true;

}

var cellTxtBlur = function (object) {
changedRows[changedRows.length - 1].NewValue = object.lastValue;
changedRows[changedRows.length - 1].IsEdited = true;

}

var storeLoad = function () {
for (var i = 0; i < App.TestGrid.store.getCount() ; i++) {
for (var j = 0; j < changedRows.length; j++) {
if (App.TestGrid.store.getAt(i).get('IdCol') == changedRows[j].PKColValue) {
App.TestGrid.store.getAt(i).set(changedRows[j].Field, changedRows[j].NewValue);
}
}

}
var pageNo = $('#PageBar').find('input[type="text"]').val();
var storeSt = Ext.getStore('Store1');
for (var i = 0; i < addedRecords.length; i++) {
if (addedRecords[i].PageNo == pageNo) {
storeSt.insert(addedRecords[i].rowIndex, addedRecords[i].record);
}
}
}



var rowindex = null;
var paras = new Array();
var storeData = null;
var originalRecord = null;

// opens application specific context menu
var onContextMenu = function (e, currentRecord, index, priceEntryMenu) {
rowindex = index;
e.preventDefault();
var rec = currentRecord;
originalRecord = currentRecord.data;
storeData = JSON.parse(JSON.stringify(currentRecord.data));
priceEntryMenu.dataRecord = rec.data;
priceEntryMenu.showAt(e.getXY());
};

// On Selecting a option from application specific contextmenu Adds a new row to price entry grid , Deletes a row respectively
var onClick = function (grid, text) {
if (text == "Add Row") {
storeData.IsAddedRow = true;
var r = Ext.create('TestGridModel', storeData);
r.data.IdCol = parseInt(Math.floor((Math.random() * (1000 - 100) + 100) + 1));
var storeSt = Ext.getStore('Store1');
storeSt.insert(rowindex + 1, r);
pageNo = $('#PageBar').find('input[type="text"]').val();
@*var rowIndex = App.TestGrid.getSelectionModel().selected.items[0].index; *@
var pageSize = 3;
if (pageNo > 1) {
rowIndex = rowIndex - ((pageNo - 1) * pageSize);
}
addedRecords.push({ "PageNo": pageNo, "rowIndex": rowindex + 1, "record": r });
App.TestGrid.getSelectionModel().select(App.TestGr id.store.getAt(rowindex + 1))
App.TestGrid.editingPlugin.startEditByPosition({ row: rowindex, column: 0 });
return false;
}
};
</script>
</head>
<body>

@(Html.X().ResourceManager(ViewBag.ManagerConfig as MvcResourceManagerConfig))
<h2>Test</h2>



@(
Html.X().FormPanel().ID("FRM").Items(
Html.X().GridPanel().ID("TestGrid")
.Title("Editable GridPanel")
.Width(600)
.Height(350)
.Store(Html.X().Store().PageSize(3).Listeners(ls => ls.Load.Fn = "storeLoad")
.ID("Store1")
.Proxy(Html.X().AjaxProxy()
.Url(Url.Action("GetData"))
.Reader(Html.X().JsonReader().Root("data"))
)
.Model(Html.X().Model().IDProperty("IdCol").Name("TestGridModel")
.IDProperty("IdCol")
.Fields(
new ModelField("IdCol", ModelFieldType.Int),
new ModelField("NameCol", ModelFieldType.String),
new ModelField("AgeCol", ModelFieldType.Int)
)
)

)
.ColumnModel(
Html.X().Column()
.Text("IdCol")
.DataIndex("IdCol")
.Flex(1),
Html.X().Column()
.Text("NameCol")
.DataIndex("NameCol")
.Editor(Html.X().TextField().Listeners(ls => ls.Blur.Fn = "cellTxtBlur")),
Html.X().Column()
.Text("AgeCol")
.DataIndex("AgeCol")
.Editor(Html.X().NumberField().Listeners(ls => ls.Blur.Fn = "cellBlur"))
)
.SelectionModel(Html.X().RowSelectionModel().ID("TestGridRowSelectionModel"))
.Plugins(
Html.X().CellEditing().Listeners(ls => ls.BeforeEdit.Fn = "cellEdit")
)
.BottomBar(Html.X().PagingToolbar().ID("PageBar").HideRefresh(true)
.FirstText("First")
.PrevText("Previous")
.NextText("Next")
.LastText("Last").AfterPageText("of {0}").BeforePageText("Page")

)
.Listeners(l => l.ItemContextMenu.Handler = "onContextMenu(e,this.store.getAt(index),index,#{Gr idPriceEntryContextMenu})")

.Features
(
Html.X().RowWrap())
))
@(
X.Container(
).ID("cntButton").Items(X.Button().ID("btnSave").Text("Save").Type(ButtonType.Submit).Handler("Save")
))
@(X.Menu().ID("GridPriceEntryContextMenu").Width(100).MaxHeight(50)
.Items(X.MenuItem()
.Text("Add Row")
.Listeners(l => l.Click.Handler = "onClick(this,'Add Row')")
))
</body>
</html>



Following are my controller Action methods




public ActionResult Test()
{
return View();
}


public ActionResult GetData(StoreRequestParameters parameters)
{
return this.Store(Paging(parameters));
}

private Paging<DummyData> Paging(StoreRequestParameters parameters)
{
return Paging(parameters.Start, parameters.Limit, parameters.SimpleSort, parameters.SimpleSortDirection, null);
}

private Paging<DummyData> Paging(int start, int limit, string sort, SortDirection dir, string filter)
{

List<DummyData> data = new List<DummyData>();
data.Add(new DummyData() { IdCol = 1, NameCol = "First", AgeCol = 25 });
data.Add(new DummyData() { IdCol = 2, NameCol = "Second", AgeCol = 35 });
data.Add(new DummyData() { IdCol = 3, NameCol = "Third", AgeCol = 30 });
data.Add(new DummyData() { IdCol = 4, NameCol = "Fourth", AgeCol = 25 });
data.Add(new DummyData() { IdCol = 5, NameCol = "Fifth", AgeCol = 35 });
data.Add(new DummyData() { IdCol = 6, NameCol = "Sixth", AgeCol = 30 });

if (!string.IsNullOrEmpty(filter) && filter != "*")
{
//data.RemoveAll(plant => !plant.Common.ToLower().StartsWith(filter.ToLower( )));
}

if (!string.IsNullOrEmpty(sort))
{
data.Sort(delegate(DummyData x, DummyData y)
{
object a;
object b;

int direction = dir == SortDirection.DESC ? -1 : 1;

a = x.GetType().GetProperty(sort).GetValue(x, null);
b = y.GetType().GetProperty(sort).GetValue(y, null);

return CaseInsensitiveComparer.Default.Compare(a, b) * direction;
});
}

if ((start + limit) > data.Count)
{
limit = data.Count - start;
}

List<DummyData> rangePlants = (start < 0 || limit < 0) ? data : data.GetRange(start, limit);

return new Paging<DummyData>(rangePlants, data.Count);
}



Following is my ViewModel class



public class DummyData
{
public int IdCol { get; set; }
public string NameCol { get; set; }
public int AgeCol { get; set; }
}


I am facing an issue;
Following are the steps to reproduce issue.
1) right click on any of the gridpanel rows . You will get context menu with "Add Row" option.
2) Click on "Add Row" - it will insert a copy of current row below.
3) Double click the Name or Age column cell(s).

Expected : added row cell should turn into a editable field.
Actual : the original row cell turning into a editable field.

Am I missing something.

Daniil
Oct 10, 2013, 7:44 AM
You should provide a unique value before creating a record instance.

storeData.IdCol = parseInt(Math.floor((Math.random() * (1000 - 100) + 100) + 1));
var r = Ext.create('TestGridModel', storeData);

Please note that a random call cannot guarantee a unique value.