ui-grid icon indicating copy to clipboard operation
ui-grid copied to clipboard

Displaying editDropdownValueLabel in dropdown instead of editDropdownIdLabel

Open trouttdev opened this issue 11 years ago • 19 comments

Similar to this issue: https://github.com/angular-ui/ng-grid/issues/2676

Is there a simple way to make the grid show editDropdownValueLabel rather than the editDropdownIdLabel? Currently the way it seems to work is if you have editDropdownOptionsArray : {'id': 1, 'value': 'Test'} and 1 was selected, the grid would show 1 rather than Test as I would expect it to, but the dropdown editor shows Test selected, as I would expect.

From the tutorial it looks like you can accomplish this with a filter and map, but in my case there are many different fields which generate dropdowns dynamically, meaning that I would have to hard code all the different field filters and then use a service or something to fill them in, which is less than ideal.

trouttdev avatar Feb 18 '15 23:02 trouttdev

If the field can generate the dropdown dynamically, can it not generate the filter dynamically? Alternatively, are all your ids unique (even across all the different dropdowns) in which case you could create a single filter with every value in it - since you never pick from the filter the user would never know it was a superset. Finally, the filter can be a function, so it in turn could call whatever logic you are using to dynamically generate the dropdowns?

PaulL1 avatar Feb 19 '15 04:02 PaulL1

Unfortunately the ID's are not unique across columns. As for building the filter dynamically, I'm not sure how I would go about doing that efficiently. I'm currently using a service to pull data from my server which builds out the column definitions. In the case of the dropdowns in question, the dropdown is populated with key/value pairs from another table which is stored as a reference ID in the table being viewed (i.e. some_useful_id in the table would reference the id field in the something_useful table). So, ideally, the row would reference the ID but display the value as it does when you click open the dropdown menu.

Would there be some way to create a filter that would essentially use the dropdowns key/value pairs to display the correct value rather than having to create a dynamic filter that (I would assume) would have to hit the server for each time the value changed?

trouttdev avatar Feb 19 '15 14:02 trouttdev

There may be, I'm not great with filters. But if you take a look in the debugger, you may find that the filter has available to it row.entity.xxxx, and perhaps something like row.entity[col.field].xxxx, so it can maybe get at the dropdownOptions. I can't recall whether the dropdownOptions might be living in dropdownOptions or something like that directly in the cell - you could look in the edit feature code to see whether it gets added to the cell scope. I'm assuming here that the filter would run with the cell $scope, which I'm not certain is true, but might be.

PaulL1 avatar Feb 19 '15 19:02 PaulL1

With this filter/cellFilter combination I was able to get close, but the initial state is now blank instead of showing the ID. If I put the cell in edit mode and click off it, the correct value then shows up.

.filter('griddropdown', function () {
    return function (input, map) {
      return map[input-1].name;
    };
  });
cellFilter: "griddropdown:editDropdownOptionsArray"

Any ideas on what I could do differently to get the initial value to show up? It's probably worth noting that map in the filter is undefined on the initial grid load.

EDIT: more flexible but still shows nothing on initial load:

.filter('griddropdown', function () {
    return function (input, map, idField, valueField) {
      for (var i = 0; i < map.length; i++) {
        if(map[i][idField] == input)
        {
          return map[i][valueField];
        }
      }
      return '';
    };
  });
cellFilter: "griddropdown:editDropdownOptionsArray:editDropdownIdLabel:editDropdownValueLabel"

trouttdev avatar Feb 19 '15 22:02 trouttdev

I've managed to create a filter which seems to accomplish what I'm wanting:

  .filter('griddropdown', function () {
    return function (input, map, idField, valueField, initial) {
      if(typeof map !== "undefined") {
        for (var i = 0; i < map.length; i++) {
          if(map[i][idField] == input)
          {
            return map[i][valueField];
          }
        }
      } else if(initial) {
        return initial;
      }
      return input;
    };
  });

With the cell filter:

cellFilter: "griddropdown:editDropdownOptionsArray:editDropdownIdLabel:editDropdownValueLabel:row.entity.relatedobject.name"

I pass to the filter the options array, the ID label, the value label so that I can retrieve the value when it changes, and the initial value via the row.entity (which doesn't update when the value is changed in my case, since it's a child object). The initial value setting is probably specific to my use-case, but the other part may help someone. Suggestions for improvement are more than welcome.

trouttdev avatar Feb 19 '15 23:02 trouttdev

Looks excellent, sounds like there is no remaining issue so I'll close.

PaulL1 avatar Feb 26 '15 07:02 PaulL1

Michael, I did not retrieve the row values when the grid was loaded at first time. So, I changed a little bit your code. I would like ui-grid to manage this issue automatically. Here is my approach:

  1. I defined an uiGridFactory.js as this one:
angularFactories.factory('uiGridFactory', function ($http, $rootScope) {

var factory = {};

/* It returns a dropdown filter to help you show editDropdownValueLabel
 *
 * Parameters:
 *
 * - input: selected input value, it always comes when you select a dropdown value
 * - map: Dictionary containing the catalog info. For example:
 *    $scope.languageCatalog = [ {'id': 'EN', 'description': 'English'}, {'id': 'ES', 'description': 'Español'} ]
 * - idLabel: ID label. For this example: 'id'.
 * - valueLabel: Value label. For this example: 'description'.
 *
 * 1) Configure cellFilter this way at the ui-grid colDef:
 *
 * { field: 'languageId', name: 'Language'), editableCellTemplate: 'ui-grid/dropdownEditor',
 *   editDropdownIdLabel: 'id', editDropdownValueLabel: 'description', 
 *   editDropdownOptionsArray: $scope.languageCatalog,
 *   cellFilter: 'mapDropdown:row:row.grid.appScope.languageCatalog:"id":"description":languageCatalog' },
 *
 * 2) Append this snippet to the controller:
 * 
 * .filter('mapDropdown', function(uiGridFactory) { 
 *    return uiGridFactory.getMapDrowdownFilter()
 * });
 *
 */
factory.getMapDrowdownFilter = function() {

    return function(input, map, idLabel, valueLabel) {

        if (map != null)
        {
            for (var i = 0; i < map.length; i ++) {
                if (map[i][idLabel] == input)
                {
                    return map[i][valueLabel];
                }
            }
        }
        return "";
    }
}

return factory;

});
  1. Then I added the filter mapDropdown at the end of the controller that requires dropdown logic
.filter('mapDropdown', function(uiGridFactory) { 
    return uiGridFactory.getMapDrowdownFilter()
});
  1. I added this cellFilter to the column definition that contains the dropdown:
 columnDefs: [
     { field: 'id', 'ID')},
     { field: 'languageId', name: 'Language',
           editableCellTemplate: 'ui-grid/dropdownEditor', 
           editDropdownIdLabel: 'id', editDropdownValueLabel: 'description', 
           editDropdownOptionsArray: $scope.languageCatalog,
           cellFilter: 'mapDropdown:row.grid.appScope.languageCatalog:"id":"description"' },
     { field: 'comments', 'Comments' }
 ]

where the mapDropdown() parameters are: a) the catalog map (row.grid.appScope.languageCatalog), b) the ID label c) the VALUE label.

ComeOutToPlay avatar Mar 08 '15 23:03 ComeOutToPlay

More generic:

Core.Modules.FeaturesAdAiringsDocument.filter('griddropdown', function() {
        return function (input, context) {
            var map = context.col.colDef.editDropdownOptionsArray;
            var idField = context.col.colDef.editDropdownIdLabel;
            var valueField = context.col.colDef.editDropdownValueLabel;
            var initial = context.row.entity[context.col.field];
            if (typeof map !== "undefined") {
                for (var i = 0; i < map.length; i++) {
                    if (map[i][idField] == input) {
                        return map[i][valueField];
                    }
                }
            } else if (initial) {
                return initial;
            }
            return input;
        };
    });

cellFilter: "griddropdown:this",

jonborchardt avatar Jul 06 '15 18:07 jonborchardt

I don't believe this issue should be closed. The standard functionality of a dropdown should be to display the display label and have that displayed in the grid. I don't think we need to go off building filters for everyday functionality.

tdekoekkoek avatar Jul 28 '15 22:07 tdekoekkoek

If I am right you are looking for the this

http://embed.plnkr.co/0iY5Qn/

prasannapethe avatar Dec 18 '15 09:12 prasannapethe

@mltroutt , @jonborchardt thanks for your contributions-- I used your filter.

Does anyone know how to allow the user to sort by the filtered values? I would have guessed that sortCellFiltered would work, but it doesn't. When using this griddropdown filter, the values reported to the sort function are undefined.

Please see my Codepen example, here (link to source code). You can see that if you un-check "Sort Filtered", it sorts by the underlying ID values.

Any ideas?

transistor1 avatar Feb 23 '16 19:02 transistor1

This appears to be due to a bug in ui-grid in which the grid is passing the row entity to the filter function when sorting, rather than the context. Below is the workaround that I used.

Note, however, that this will only allow the user to sort on 1 drop-down column. If there's a secondary/tertiary dropdown sort in place, it simply won't work. The reason for this is that it doesn't know how to determine which dropdown column is being sorted. It does work if the other column(s) being sorted are not drop-downs.

Please see my forked Codepen, here for an example.

Make sure you have sortCellFiltered: true in your column definition.

myModule.filter('griddropdown', function() {
    return function (input, context) {
        //For some reason the text "this" is occasionally directly being
        //passed here
        if (typeof context === 'undefined' || context === 'this')
            return 0;

        //Workaround for bug in ui-grid
        if (typeof context.col === 'undefined') {
            var sortCols = context.grid.getColumnSorting();
            if (sortCols.length <= 0)
                return 0;

            context = { col: sortCols[0], row: context };
        }

        var map = context.col.colDef.editDropdownOptionsArray;
        var idField = context.col.colDef.editDropdownIdLabel;
        var valueField = context.col.colDef.editDropdownValueLabel;
        var initial = context.row.entity[context.col.field];
        if (typeof map !== "undefined") {
            for (var i = 0; i < map.length; i++) {
                if (map[i][idField] == input) {
                    return map[i][valueField];
                }
            }
        } else if (initial) {
            return initial;
        }
        return input;
    };
});

transistor1 avatar Feb 26 '16 21:02 transistor1

@jonborchardt, thank you so much! Excellent solution! 5 stars! 30 seconds, done!

PS: it works, but, after trying to edit this cell, I get this error: angular.js:13424 TypeError: Cannot read property 'colDef' of undefined at main.js:3098 at GridRowColumnFactory.GridRowColumn.getIntersectionValueFiltered (ui-grid.js:9053) at ui-grid.js:15256 at m.$broadcast (angular.js:17348) at Object.compile.pre.uiGridCtrl.cellNav.broadcastCellNav.grid.cellNav.broadcastCellNav as broadcastCellNav at HTMLDivElement. (ui-grid.js:15480) at Pf (angular.js:3417) at HTMLDivElement.Of.d (angular.js:3405)

main.js:3098 is 3rd line of yr code: var map = context.col.colDef.editDropdownOptionsArray;

any idea?

rsilva1959 avatar Apr 11 '16 17:04 rsilva1959

Saying that this issue is closed is genius /s

brendon-colburn avatar Apr 20 '16 14:04 brendon-colburn

I've made an adjustment to the @jonborchardt solution so that you can filter on dynamically loaded editDropdownRowEntityOptionsArrayPath as well. See below, I check on context before using col.colDef. @transistor1 we had a brief exchange on Stack Overflow in regards to this and I noticed that you made your own change to the @jonborchardt solution. Maybe we could roll your check condition in with mine or vice versa for a more comprehensive solution.

.filter('griddropdown', function () {
            return function (input, context) {
                var fieldLevel = (context.editDropdownOptionsArray == undefined) ? context.col.colDef : context;
                var map = fieldLevel.editDropdownOptionsArray;
                var idField = fieldLevel.editDropdownIdLabel;
                var valueField = fieldLevel.editDropdownValueLabel;
                var initial = context.row.entity[context.col.field];
                if (typeof map !== "undefined") {
                    for (var i = 0; i < map.length; i++) {
                        if (map[i][idField] == input) {
                            return map[i][valueField];
                        }
                    }
                } else if (initial) {
                    return initial;
                }
                return input;
            };
        });

brendon-colburn avatar Apr 20 '16 15:04 brendon-colburn

@mltroutt I am struggling in setting up dynamically generated dropdowns in ui-grid. Can you please look at my question at http://stackoverflow.com/questions/37110591/angular-ui-grid-unable-to-load-dynamic-data-into-ui-grid-dropdown ?

My table gets updated with server response but dropdown remains empty.

I'm sorry if this the question is out of topic but I didn't found any other way to contact you.

harman052 avatar May 09 '16 12:05 harman052

@mltroutt I am having problems while implementing your solution on Feb 20, The problem is that map is coming as undefined on the first load because of which the values of dropdown is nt binding. Please help me with the solution.

ShradhaShaw avatar May 09 '16 13:05 ShradhaShaw

for the initial blank value issue, i think it is the map were undefined when first iterate, so i try not pass the array via ui-grid, i pass a constant array and it work

app.constant('Constant', {
    optionItems:[
        {id:"A", value: "App"},
        {id:"B", value: "Boy"},
        {id:"C", value: "Cat"}
    ],
     getById : function (arr, id) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id === id) {
                return arr[i].value;
            }
        }
    }
}

$scope.gridOptions = {
 {
    field : 'something',
    displayName : 'Some thing',
    editableCellTemplate : 'ui-grid/dropdownEditor',
    cellFilter: 'optionGridDropdownFilter:"optionItems"',
    editDropdownOptionsArray : Constant.optionItems,
    editDropdownIdLabel : 'id',
    editDropdownValueLabel : 'value'
}

mainApp.filter('optionGridDropdownFilter', function (Constant) {
    return function (input, objName) {
        var map = Constant[objName];
        return Constant.getById(map, input);
      };
});

paulyiu avatar Jul 12 '16 16:07 paulyiu

http://codepen.io/transistor1/pen/XXvgKO?editors=0010#0

poloaha avatar Jan 28 '17 20:01 poloaha