terça-feira, 25 de setembro de 2012

The Ilusive jsGrid (V)

And now something long due: how to display comboboxes/dropdowlists on the jsGrid.

So at a given point in your code you'll have - i hope - something similar to this:

GridSerializer gds = new GridSerializer(SerializeMode.Full,
dataTable,
"key",
new FieldOrderCollection(),
GetGridFields(),
GetGridColumns());

Your GetGridFields() function should resemble this:

protected IList GetGridFields()
{
   List row = new List();
   foreach (DataColumn iterator in dataTable.Columns)
   {
      GridField field = new GridField();
      field = FormatGridField(field, iterator);
      row.Add(field);
   }
   return row;
}

Now let's focus on FormatGridField(gridField, dataColumn). Let's say the column that should display the comboboxes is named "brands". This is what should be included in your FormatGridFields(...) function:
(...)
if (dc.ColumnName == "brands") //our combobox column
{
   gf.PropertyTypeId = "myLookupTable"; //Use whatever name you want here; just be aware that it will be used on the js file where the GridManager is instatiated
   gf.Localizer = (ValueLocalizer)delegate(DataRow row, object toConvert)
   {
      string brandName = (string)row["brandName"];
      return toConvert == null ? "" : brandName;
   };
   gf.SerializeDataValue = true;
   gf.SerializeLocalizedValue = true;
}
(...)

That's all on the server side.

As for the js file where the GridManager is instatiated, you'll have something similar to this:
GridManager = function () {
   this._jsGridControl = null;
   this.Init = function (jsGridControl, initialData, props) {
(...)

Add this inside that same function:
SP.JsGrid.PropertyType.RegisterNewLookupPropType('myLookupTable', brandsArray, SP.JsGrid.DisplayControl.Type.Text, false); //Remember "myLookupTable" from before; it's up to you to get the brandsArray filled with the possible values; i use an hiddenfield, then move the contents into the array.

(a couple of lines below)

jsGridParams.tableViewParams.columns.GetColumnByKey('brands').fnGetEditControlName = function () { return SP.JsGrid.EditControl.Type.ComboBox; } //"brands" is the name of the column
jsGridControl.Init(jsGridParams);

That's all there is to it - (from top to bottom) tell the grid that the EditControl for the column is a ComboBox; also, register the lookup table that contains all the possible values; change the server side code so that the combobox displays previously saved values.

I hope this is useful.

Soundtrack for this finding:
Haven't heard much music lately, but "Bandoliers" by Them Crooked Vultures certainly played a part.