1 openerp.web.list = function (instance) {
2 var _t = instance.web._t,
3 _lt = instance.web._lt;
4 var QWeb = instance.web.qweb;
5 instance.web.views.add('list', 'instance.web.ListView');
6 instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
8 display_name: _lt('List'),
10 // records can be selected one by one
12 // list rows can be deleted
14 // whether the column headers should be displayed
16 // display addition button, with that label
17 'addable': _lt("Create"),
18 // whether the list view can be sorted, note that once a view has been
19 // sorted it can not be reordered anymore
21 // whether the view rows can be reordered (via vertical drag & drop)
23 'action_buttons': true,
24 // if true, the 'Import', 'Export', etc... buttons will be shown
25 'import_enabled': true,
28 * Core class for list-type displays.
30 * As a view, needs a number of view-related parameters to be correctly
31 * instantiated, provides options and overridable methods for behavioral
34 * See constructor parameters and method documentations for information on
35 * the default behaviors and possible options for the list view.
37 * @constructs instance.web.ListView
38 * @extends instance.web.View
40 * @param parent parent object
41 * @param {instance.web.DataSet} dataset the dataset the view should work with
42 * @param {String} view_id the listview's identifier, if any
43 * @param {Object} options A set of options used to configure the view
44 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
45 * @param {Boolean} [options.header=true] should the list's header be displayed
46 * @param {Boolean} [options.deletable=true] are the list rows deletable
47 * @param {void|String} [options.addable="New"] should the new-record button be displayed, and what should its label be. Use ``null`` to hide the button.
48 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
49 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
51 init: function(parent, dataset, view_id, options) {
54 this.set_default_options(_.extend({}, this.defaults, options || {}));
55 this.dataset = dataset;
56 this.model = dataset.model;
57 this.view_id = view_id;
58 this.previous_colspan = null;
64 this.records = new Collection();
66 this.set_groups(new (this.options.GroupsType)(this));
68 if (this.dataset instanceof instance.web.DataSetStatic) {
69 this.groups.datagroup = new instance.web.StaticDataGroup(this.dataset);
71 this.groups.datagroup = new instance.web.DataGroup(
74 dataset.get_context());
75 this.groups.datagroup.sort = this.dataset._sort;
79 this.records.bind('change', function (event, record, key) {
80 if (!_(self.aggregate_columns).chain()
81 .pluck('name').contains(key).value()) {
84 self.compute_aggregates();
89 set_default_options: function (options) {
91 _.defaults(this.options, {
92 GroupsType: instance.web.ListView.Groups,
93 ListType: instance.web.ListView.List
98 * Retrieves the view's number of records per page (|| section)
100 * options > defaults > parent.action.limit > indefinite
102 * @returns {Number|null}
105 if (this._limit === undefined) {
106 this._limit = (this.options.limit
107 || this.defaults.limit
108 || (this.getParent().action || {}).limit
114 * Set a custom Group construct as the root of the List View.
116 * @param {instance.web.ListView.Groups} groups
118 set_groups: function (groups) {
121 $(this.groups).unbind("selected deleted action row_link");
125 this.groups = groups;
126 $(this.groups).bind({
127 'selected': function (e, ids, records) {
128 self.do_select(ids, records);
130 'deleted': function (e, ids) {
133 'action': function (e, action_name, id, callback) {
134 self.do_button_action(action_name, id, callback);
136 'row_link': function (e, id, dataset, view) {
137 self.do_activate_record(dataset.index, id, dataset, view);
142 * View startup method, the default behavior is to set the ``oe_list``
143 * class on its root element and to perform an RPC load call.
145 * @returns {$.Deferred} loading promise
148 this.$el.addClass('oe_list');
149 return this.reload_view(null, null, true);
152 * Returns the style for the provided record in the current view (from the
153 * ``@colors`` and ``@fonts`` attributes)
155 * @param {Record} record record for the current row
156 * @returns {String} CSS style declaration
158 style_for: function (record) {
161 var context = _.extend({}, record.attributes, {
162 uid: this.session.uid,
163 current_date: new Date().toString('yyyy-MM-dd')
164 // TODO: time, datetime, relativedelta
168 for(var i=0, len=this.fonts.length; i<len; ++i) {
169 var pair = this.fonts[i],
171 expression = pair[1];
172 if (py.evaluate(expression, context).toJSON()) {
175 style += 'font-weight: bold;';
178 style += 'font-style: italic;';
181 style += 'text-decoration: underline;';
188 if (!this.colors) { return style; }
189 for(var i=0, len=this.colors.length; i<len; ++i) {
190 var pair = this.colors[i],
192 expression = pair[1];
193 if (py.evaluate(expression, context).toJSON()) {
194 return style += 'color: ' + color + ';';
196 // TODO: handle evaluation errors
201 * Called after loading the list view's description, sets up such things
202 * as the view table's columns, renders the table itself and hooks up the
203 * various table-level and row-level DOM events (action buttons, deletion
204 * buttons, selection of records, [New] button, selection of a given
207 * Sets up the following:
209 * * Processes arch and fields to generate a complete field descriptor for each field
210 * * Create the table itself and allocate visible columns
211 * * Hook in the top-level (header) [New|Add] and [Delete] button
212 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
213 * * Sets up event handlers for action buttons and per-row deletion button
214 * * Hooks global callback for clicking on a row
215 * * Sets up its sidebar, if any
217 * @param {Object} data wrapped fields_view_get result
218 * @param {Object} data.fields_view fields_view_get result (processed)
219 * @param {Object} data.fields_view.fields mapping of fields for the current model
220 * @param {Object} data.fields_view.arch current list view descriptor
221 * @param {Boolean} grouped Is the list view grouped
223 on_loaded: function(data, grouped) {
225 this.fields_view = data;
226 this.name = "" + this.fields_view.arch.attrs.string;
228 if (this.fields_view.arch.attrs.colors) {
229 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
231 .map(function(color_pair) {
232 var pair = color_pair.split(':'),
235 return [color, py.parse(py.tokenize(expr)), expr];
239 if (this.fields_view.arch.attrs.fonts) {
240 this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
241 .map(function(font_pair) {
242 var pair = font_pair.split(':'),
245 return [font, py.parse(py.tokenize(expr)), expr];
249 this.setup_columns(this.fields_view.fields, grouped);
251 this.$el.html(QWeb.render(this._template, this));
252 this.$el.addClass(this.fields_view.arch.attrs['class']);
255 this.$el.find('.oe_list_record_selector').click(function(){
256 self.$el.find('.oe_list_record_selector input').prop('checked',
257 self.$el.find('.oe_list_record_selector').prop('checked') || false);
258 var selection = self.groups.get_selection();
259 $(self.groups).trigger(
260 'selected', [selection.ids, selection.records]);
264 this.$el.find('thead').delegate('th.oe_sortable[data-id]', 'click', function (e) {
267 self.dataset.sort($this.data('id'));
268 if($this.hasClass("sortdown") || $this.hasClass("sortup")) {
269 $this.toggleClass("sortdown").toggleClass("sortup");
271 $this.toggleClass("sortdown");
273 $this.siblings('.oe_sortable').removeClass("sortup sortdown");
275 self.reload_content();
278 // Add button and Import link
279 if (!this.$buttons) {
280 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
281 if (this.options.$buttons) {
282 this.$buttons.appendTo(this.options.$buttons);
284 this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
286 this.$buttons.find('.oe_list_add')
287 .click(this.proxy('do_add_record'))
288 .prop('disabled', grouped);
289 this.$buttons.on('click', '.oe_list_button_import', function() {
290 self.on_sidebar_import();
297 this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
298 if (this.options.$buttons) {
299 this.$pager.appendTo(this.options.$pager);
301 this.$el.find('.oe_list_pager').replaceWith(this.$pager);
305 .on('click', 'a[data-pager-action]', function () {
307 var max_page = Math.floor(self.dataset.size() / self.limit());
308 switch ($this.data('pager-action')) {
310 self.page = 0; break;
312 self.page = max_page - 1;
315 self.page += 1; break;
317 self.page -= 1; break;
320 self.page = max_page;
321 } else if (self.page > max_page) {
324 self.reload_content();
325 }).find('.oe_list_pager_state')
326 .click(function (e) {
330 var $select = $('<select>')
331 .appendTo($this.empty())
332 .click(function (e) {e.stopPropagation();})
333 .append('<option value="80">80</option>' +
334 '<option value="100">100</option>' +
335 '<option value="200">200</option>' +
336 '<option value="500">500</option>' +
337 '<option value="NaN">' + _t("Unlimited") + '</option>')
338 .change(function () {
339 var val = parseInt($select.val(), 10);
340 self._limit = (isNaN(val) ? null : val);
342 self.reload_content();
344 $(this).trigger('change');
346 .val(self._limit || 'NaN');
351 if (!this.sidebar && this.options.$sidebar) {
352 this.sidebar = new instance.web.Sidebar(this);
353 this.sidebar.appendTo(this.options.$sidebar);
354 this.sidebar.add_items('other', [
355 { label: _t("Import"), callback: this.on_sidebar_import },
356 { label: _t("Export"), callback: this.on_sidebar_export },
357 { label: _t('Delete'), callback: this.do_delete_selected }
359 this.sidebar.add_toolbar(this.fields_view.toolbar);
360 this.sidebar.$el.hide();
364 * Configures the ListView pager based on the provided dataset's information
366 * Horrifying side-effect: sets the dataset's data on this.dataset?
368 * @param {instance.web.DataSet} dataset
370 configure_pager: function (dataset) {
371 this.dataset.ids = dataset.ids;
373 if (dataset._length) {
374 this.dataset._length = dataset._length;
377 var total = dataset.size();
378 var limit = this.limit() || total;
379 this.$pager.toggle(total !== 0);
380 this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
383 var range_start = this.page * limit + 1;
384 var range_stop = range_start - 1 + limit;
385 if (range_stop > total) {
388 spager = _.str.sprintf('%d-%d of %d', range_start, range_stop, total);
391 this.$pager.find('.oe_list_pager_state').text(spager);
394 * Sets up the listview's columns: merges view and fields data, move
395 * grouped-by columns to the front of the columns list and make them all
398 * @param {Object} fields fields_view_get's fields section
399 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
401 setup_columns: function (fields, grouped) {
402 var registry = instance.web.list.columns;
403 this.columns.splice(0, this.columns.length);
404 this.columns.push.apply(this.columns,
405 _(this.fields_view.arch.children).map(function (field) {
406 var id = field.attrs.name;
407 return registry.for_(id, fields[id], field);
410 this.columns.unshift(
411 new instance.web.list.MetaColumn('_group', _t("Group")));
414 this.visible_columns = _.filter(this.columns, function (column) {
415 return column.invisible !== '1';
418 this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
421 * Used to handle a click on a table row, if no other handler caught the
424 * The default implementation asks the list view's view manager to switch
425 * to a different view (by calling
426 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
427 * provided record index (within the current list view's dataset).
429 * If the index is null, ``switch_to_record`` asks for the creation of a
432 * @param {Number|void} index the record index (in the current dataset) to switch to
433 * @param {String} [view="page"] the view type to switch to
435 select_record:function (index, view) {
436 view = view || index == null ? 'form' : 'form';
437 this.dataset.index = index;
438 _.delay(_.bind(function () {
439 this.do_switch_view(view);
442 do_show: function () {
445 this.$buttons.show();
451 do_hide: function () {
453 this.sidebar.$el.hide();
456 this.$buttons.hide();
464 * Reloads the list view based on the current settings (dataset & al)
466 * @param {Boolean} [grouped] Should the list be displayed grouped
467 * @param {Object} [context] context to send the server while loading the view
469 reload_view: function (grouped, context, initial) {
471 var callback = function (field_view_get) {
472 self.on_loaded(field_view_get, grouped);
474 if (this.embedded_view) {
475 return $.Deferred().then(callback).resolve(this.embedded_view);
477 return this.rpc('/web/listview/load', {
479 view_id: this.view_id,
481 context: this.dataset.get_context(context),
482 toolbar: !!this.options.$sidebar
487 * re-renders the content of the list view
489 * @returns {$.Deferred} promise to content reloading
491 reload_content: function () {
493 self.$el.find('.oe_list_record_selector').prop('checked', false);
494 this.records.reset();
495 var reloaded = $.Deferred();
496 this.$el.find('.oe_list_content').append(
497 this.groups.render(function () {
498 if (self.dataset.index == null) {
500 self.records.each(function () { has_one = true; });
502 self.dataset.index = 0;
505 self.compute_aggregates();
512 return reloaded.promise();
514 reload: function () {
515 return this.reload_content();
517 reload_record: function (record) {
518 return this.dataset.read_ids(
520 _.pluck(_(this.columns).filter(function (r) {
521 return r.tag === 'field';
523 ).then(function (records) {
524 _(records[0]).each(function (value, key) {
525 record.set(key, value, {silent: true});
527 record.trigger('change', record);
531 do_load_state: function(state, warm) {
533 if (state.page && this.page !== state.page) {
534 this.page = state.page;
538 if (_.isString(state.limit)) {
541 if (state.limit !== this._limit) {
542 this._limit = state.limit;
547 this.reload_content();
551 * Handler for the result of eval_domain_and_context, actually perform the
554 * @param {Object} results results of evaluating domain and process for a search
556 do_search: function (domain, context, group_by) {
558 this.groups.datagroup = new instance.web.DataGroup(
559 this, this.model, domain, context, group_by);
560 this.groups.datagroup.sort = this.dataset._sort;
562 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
565 this.no_leaf = !!context['group_by_no_leaf'];
567 this.reload_view(!!group_by, context).then(
568 this.proxy('reload_content'));
571 * Handles the signal to delete lines from the records list
573 * @param {Array} ids the ids of the records to delete
575 do_delete: function (ids) {
576 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
580 return $.when(this.dataset.unlink(ids)).then(function () {
581 _(ids).each(function (id) {
582 self.records.remove(self.records.get(id));
584 self.configure_pager(self.dataset);
585 self.compute_aggregates();
589 * Handles the signal indicating that a new record has been selected
591 * @param {Array} ids selected record ids
592 * @param {Array} records selected record values
594 do_select: function (ids, records) {
596 this.dataset.index = 0;
598 this.sidebar.$el.hide();
600 this.compute_aggregates();
604 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
606 this.sidebar.$el.show();
609 this.compute_aggregates(_(records).map(function (record) {
610 return {count: 1, values: record};
614 * Handles action button signals on a record
616 * @param {String} name action name
617 * @param {Object} id id of the record the action should be called on
618 * @param {Function} callback should be called after the action is executed, if non-null
620 do_button_action: function (name, id, callback) {
621 this.handle_button(name, id, callback);
624 * Base handling of buttons, can be called when overriding do_button_action
625 * in order to bypass parent overrides.
627 * The callback will be provided with the ``id`` as its parameter, in case
628 * handle_button's caller had to alter the ``id`` (or even create one)
629 * while not being ``callback``'s creator.
631 * This method should not be overridden.
633 * @param {String} name action name
634 * @param {Object} id id of the record the action should be called on
635 * @param {Function} callback should be called after the action is executed, if non-null
637 handle_button: function (name, id, callback) {
638 var action = _.detect(this.columns, function (field) {
639 return field.name === name;
641 if (!action) { return; }
642 if ('confirm' in action && !window.confirm(action.confirm)) {
646 var c = new instance.web.CompoundContext();
647 c.set_eval_context(_.extend({
650 active_model: this.dataset.model
651 }, this.records.get(id).toContext()));
652 if (action.context) {
653 c.add(action.context);
656 this.do_execute_action(
657 action, this.dataset, id, _.bind(callback, null, id));
660 * Handles the activation of a record (clicking on it)
662 * @param {Number} index index of the record in the dataset
663 * @param {Object} id identifier of the activated record
664 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
666 do_activate_record: function (index, id, dataset, view) {
667 this.dataset.ids = dataset.ids;
668 this.select_record(index, view);
671 * Handles signal for the addition of a new record (can be a creation,
672 * can be the addition from a remote source, ...)
674 * The default implementation is to switch to a new record on the form view
676 do_add_record: function () {
677 this.select_record(null);
680 * Handles deletion of all selected lines
682 do_delete_selected: function () {
683 var ids = this.groups.get_selection().ids;
685 this.do_delete(this.groups.get_selection().ids);
687 this.do_warn(_t("Warning"), _t("You must select at least one record."));
691 * Computes the aggregates for the current list view, either on the
692 * records provided or on the records of the internal
693 * :js:class:`~instance.web.ListView.Group`, by calling
694 * :js:func:`~instance.web.ListView.group.get_records`.
696 * Then displays the aggregates in the table through
697 * :js:method:`~instance.web.ListView.display_aggregates`.
699 * @param {Array} [records]
701 compute_aggregates: function (records) {
702 var columns = _(this.aggregate_columns).filter(function (column) {
703 return column['function']; });
704 if (_.isEmpty(columns)) { return; }
706 if (_.isEmpty(records)) {
707 records = this.groups.get_records();
709 records = _(records).compact();
711 var count = 0, sums = {};
712 _(columns).each(function (column) {
713 switch (column['function']) {
715 sums[column.id] = -Infinity;
718 sums[column.id] = Infinity;
724 _(records).each(function (record) {
725 count += record.count || 1;
726 _(columns).each(function (column) {
727 var field = column.id,
728 value = record.values[field];
729 switch (column['function']) {
731 sums[field] += value;
734 sums[field] += record.count * value;
737 if (sums[field] > value) {
742 if (sums[field] < value) {
751 _(columns).each(function (column) {
752 var field = column.id;
753 switch (column['function']) {
755 aggregates[field] = {value: sums[field] / count};
758 aggregates[field] = {value: sums[field]};
762 this.display_aggregates(aggregates);
764 display_aggregates: function (aggregation) {
766 var $footer_cells = this.$el.find('.oe_list_footer');
767 _(this.aggregate_columns).each(function (column) {
768 if (!column['function']) {
772 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
773 .html(column.format(aggregation, { process_modifiers: false }));
776 get_selected_ids: function() {
777 var ids = this.groups.get_selection().ids;
781 * Adds padding columns at the start or end of all table rows (including
784 * @param {Number} count number of columns to add
785 * @param {Object} options
786 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
787 * @param {Object} [options.except] content row to not pad
789 pad_columns: function (count, options) {
790 options = options || {};
791 // padding for action/pager header
792 var $first_header = this.$el.find('thead tr:first th');
793 var colspan = $first_header.attr('colspan');
795 if (!this.previous_colspan) {
796 this.previous_colspan = colspan;
798 $first_header.attr('colspan', parseInt(colspan, 10) + count);
800 // Padding for column titles, footer and data rows
802 .find('.oe_list_header_columns, tr:not(thead tr)')
803 .not(options['except']);
804 var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
805 if (options.position === 'before') {
806 $rows.prepend(newcols);
808 $rows.append(newcols);
812 * Removes all padding columns of the table
814 unpad_columns: function () {
815 this.$el.find('.oe_list_padding').remove();
816 if (this.previous_colspan) {
818 .find('thead tr:first th')
819 .attr('colspan', this.previous_colspan);
820 this.previous_colspan = null;
823 no_result: function () {
824 this.$el.find('.oe_view_nocontent').remove();
825 if (this.groups.group_by
826 || !this.options.action
827 || !this.options.action.help) {
830 this.$el.find('table:first').hide();
832 $('<div class="oe_view_nocontent">').html(this.options.action.help)
836 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
838 * List display for the ListView, handles basic DOM events and transforms
839 * them in the relevant higher-level events, to which the list view (or
840 * other consumers) can subscribe.
842 * Events on this object are registered via jQuery.
847 * Triggered when a row is selected (using check boxes), provides an
848 * array of ids of all the selected records.
850 * Triggered when deletion buttons are hit, provide an array of ids of
851 * all the records being marked for suppression.
853 * Triggered when an action button is clicked, provides two parameters:
855 * * The name of the action to execute (as a string)
856 * * The id of the record to execute the action on
858 * Triggered when a row of the table is clicked, provides the index (in
859 * the rows array) and id of the selected record to the handle function.
861 * @constructs instance.web.ListView.List
862 * @extends instance.web.Class
864 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
866 init: function (group, opts) {
869 this.view = group.view;
870 this.session = this.view.session;
872 this.options = opts.options;
873 this.columns = opts.columns;
874 this.dataset = opts.dataset;
875 this.records = opts.records;
877 this.record_callbacks = {
878 'remove': function (event, record) {
879 var $row = self.$current.children(
880 '[data-id=' + record.get('id') + ']');
881 var index = $row.data('index');
884 'reset': function () { return self.on_records_reset(); },
885 'change': function (event, record, attribute, value, old_value) {
887 if (attribute === 'id') {
889 throw new Error("Setting 'id' attribute on existing record "
890 + JSON.stringify(record.attributes));
892 if (!_.contains(self.dataset.ids, value)) {
893 // add record to dataset if not already in (added by
895 self.dataset.ids.splice(
896 self.records.indexOf(record), 0, value);
898 // Set id on new record
899 $row = self.$current.children('[data-id=false]');
901 $row = self.$current.children(
902 '[data-id=' + record.get('id') + ']');
904 $row.replaceWith(self.render_record(record));
906 'add': function (ev, records, record, index) {
907 var $new_row = $(self.render_record(record));
910 $new_row.prependTo(self.$current);
912 var previous_record = records.at(index-1),
913 $previous_sibling = self.$current.children(
914 '[data-id=' + previous_record.get('id') + ']');
915 $new_row.insertAfter($previous_sibling);
919 _(this.record_callbacks).each(function (callback, event) {
920 this.records.bind(event, callback);
923 this.$_element = $('<tbody>')
924 .appendTo(document.body)
925 .delegate('th.oe_list_record_selector', 'click', function (e) {
927 var selection = self.get_selection();
929 'selected', [selection.ids, selection.records]);
931 .delegate('td.oe_list_record_delete button', 'click', function (e) {
933 var $row = $(e.target).closest('tr');
934 $(self).trigger('deleted', [[self.row_id($row)]]);
936 .delegate('td.oe_list_field_cell button', 'click', function (e) {
938 var $target = $(e.currentTarget),
939 field = $target.closest('td').data('field'),
940 $row = $target.closest('tr'),
941 record_id = self.row_id($row);
943 // note: $.data converts data to number if it's composed only
944 // of digits, nice when storing actual numbers, not nice when
945 // storing strings composed only of digits. Force the action
946 // name to be a string
947 $(self).trigger('action', [field.toString(), record_id, function (id) {
948 return self.reload_record(self.records.get(id));
951 .delegate('a', 'click', function (e) {
954 .delegate('tr', 'click', function (e) {
955 var row_id = self.row_id(e.currentTarget);
958 if (!self.dataset.select_id(row_id)) {
959 throw new Error("Could not find id in dataset");
965 row_clicked: function (e, view) {
968 [this.dataset.ids[this.dataset.index],
969 this.dataset, view]);
971 render_cell: function (record, column) {
973 if(column.type === 'reference') {
974 value = record.get(column.id);
976 // Ensure that value is in a reference "shape", otherwise we're
977 // going to loop on performing name_get after we've resolved (and
978 // set) a human-readable version. m2o does not have this issue
979 // because the non-human-readable is just a number, where the
980 // human-readable version is a pair
981 if (value && (ref_match = /([\w\.]+),(\d+)/.exec(value))) {
982 // reference values are in the shape "$model,$id" (as a
983 // string), we need to split and name_get this pair in order
984 // to get a correctly displayable value in the field
985 var model = ref_match[1],
986 id = parseInt(ref_match[2], 10);
987 new instance.web.DataSet(this.view, model).name_get([id], function(names) {
988 if (!names.length) { return; }
989 record.set(column.id, names[0][1]);
992 } else if (column.type === 'many2one') {
993 value = record.get(column.id);
994 // m2o values are usually name_get formatted, [Number, String]
995 // pairs, but in some cases only the id is provided. In these
996 // cases, we need to perform a name_get call to fetch the actual
998 if (typeof value === 'number' || value instanceof Number) {
999 // fetch the name, set it on the record (in the right field)
1000 // and let the various registered events handle refreshing the
1002 new instance.web.DataSet(this.view, column.relation)
1003 .name_get([value], function (names) {
1004 if (!names.length) { return; }
1005 record.set(column.id, names[0]);
1009 return column.format(record.toForm().data, {
1010 model: this.dataset.model,
1011 id: record.get('id')
1014 render: function () {
1016 if (this.$current) {
1017 this.$current.remove();
1019 this.$current = this.$_element.clone(true);
1020 this.$current.empty().append(
1021 QWeb.render('ListView.rows', _.extend({
1022 render_cell: function () {
1023 return self.render_cell.apply(self, arguments); }
1025 this.pad_table_to(4);
1027 pad_table_to: function (count) {
1028 if (this.records.length >= count ||
1029 _(this.columns).any(function(column) { return column.meta; })) {
1033 if (this.options.selectable) {
1034 cells.push('<th class="oe_list_record_selector"></td>');
1036 _(this.columns).each(function(column) {
1037 if (column.invisible === '1') {
1040 if (column.tag === 'button') {
1041 cells.push('<td class="oe_button" title="' + column.string + '"> </td>');
1043 cells.push('<td title="' + column.string + '"> </td>');
1046 if (this.options.deletable) {
1047 cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1049 cells.unshift('<tr>');
1050 cells.push('</tr>');
1052 var row = cells.join('');
1054 .children('tr:not([data-id])').remove().end()
1055 .append(new Array(count - this.records.length + 1).join(row));
1058 * Gets the ids of all currently selected records, if any
1059 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1061 get_selection: function () {
1062 var result = {ids: [], records: []};
1063 if (!this.options.selectable) {
1066 var records = this.records;
1067 this.$current.find('th.oe_list_record_selector input:checked')
1068 .closest('tr').each(function () {
1069 var record = records.get($(this).data('id'));
1070 result.ids.push(record.get('id'));
1071 result.records.push(record.attributes);
1076 * Returns the identifier of the object displayed in the provided table
1079 * @param {Object} row the selected table row
1080 * @returns {Number|String} the identifier of the row's object
1082 row_id: function (row) {
1083 return $(row).data('id');
1086 * Death signal, cleans up list display
1088 on_records_reset: function () {
1089 _(this.record_callbacks).each(function (callback, event) {
1090 this.records.unbind(event, callback);
1092 if (!this.$current) { return; }
1093 this.$current.remove();
1094 this.$current = null;
1095 this.$_element.remove();
1097 get_records: function () {
1098 return this.records.map(function (record) {
1099 return {count: 1, values: record.attributes};
1103 * Reloads the provided record by re-reading its content from the server.
1105 * @param {Record} record
1106 * @returns {$.Deferred} promise to the finalization of the reloading
1108 reload_record: function (record) {
1109 return this.view.reload_record(record);
1112 * Renders a list record to HTML
1114 * @param {Record} record index of the record to render in ``this.rows``
1115 * @returns {String} QWeb rendering of the selected record
1117 render_record: function (record) {
1119 var index = this.records.indexOf(record);
1120 return QWeb.render('ListView.row', {
1121 columns: this.columns,
1122 options: this.options,
1124 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1126 render_cell: function () {
1127 return self.render_cell.apply(self, arguments); }
1131 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1132 passtrough_events: 'action deleted row_link',
1134 * Grouped display for the ListView. Handles basic DOM events and interacts
1135 * with the :js:class:`~instance.web.DataGroup` bound to it.
1137 * Provides events similar to those of
1138 * :js:class:`~instance.web.ListView.List`
1140 * @constructs instance.web.ListView.Groups
1141 * @extends instance.web.Class
1143 * @param {instance.web.ListView} view
1144 * @param {Object} [options]
1145 * @param {Collection} [options.records]
1146 * @param {Object} [options.options]
1147 * @param {Array} [options.columns]
1149 init: function (view, options) {
1150 options = options || {};
1152 this.records = options.records || view.records;
1153 this.options = options.options || view.options;
1154 this.columns = options.columns || view.columns;
1155 this.datagroup = null;
1163 this.records.bind('reset', function () {
1164 return self.on_records_reset(); });
1166 make_fragment: function () {
1167 return document.createDocumentFragment();
1170 * Returns a DOM node after which a new tbody can be inserted, so that it
1171 * follows the provided row.
1173 * Necessary to insert the result of a new group or list view within an
1174 * existing groups render, without losing track of the groups's own
1177 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1178 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1180 point_insertion: function (row) {
1182 var red_letter_tboday = $row.closest('tbody')[0];
1184 var $next_siblings = $row.nextAll();
1185 if ($next_siblings.length) {
1186 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1188 $root_kanal.append($next_siblings);
1189 this.elements.splice(
1190 _.indexOf(this.elements, red_letter_tboday),
1194 return red_letter_tboday;
1196 make_paginator: function () {
1198 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1199 .click(function (e) {
1200 e.stopPropagation();
1203 self.$row.closest('tbody').next()
1204 .replaceWith(self.render());
1206 var $next = $('<button type="button" data-pager-action="next">></button>')
1207 .click(function (e) {
1208 e.stopPropagation();
1211 self.$row.closest('tbody').next()
1212 .replaceWith(self.render());
1214 this.$row.children().last()
1216 .append('<span class="oe_list_pager_state"></span>')
1219 open: function (point_insertion) {
1220 this.render().insertAfter(point_insertion);
1222 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1223 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1224 if (no_subgroups && records_terminated) {
1225 this.make_paginator();
1228 close: function () {
1229 this.$row.children().last().empty();
1230 this.records.reset();
1233 * Prefixes ``$node`` with floated spaces in order to indent it relative
1234 * to its own left margin/baseline
1236 * @param {jQuery} $node jQuery object to indent
1237 * @param {Number} level current nesting level, >= 1
1238 * @returns {jQuery} the indentation node created
1240 indent: function ($node, level) {
1242 .css({'float': 'left', 'white-space': 'pre'})
1243 .text(new Array(level).join(' '))
1246 render_groups: function (datagroups) {
1248 var placeholder = this.make_fragment();
1249 _(datagroups).each(function (group) {
1250 if (self.children[group.value]) {
1251 self.records.proxy(group.value).reset();
1252 delete self.children[group.value];
1254 var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1255 records: self.records.proxy(group.value),
1256 options: self.options,
1257 columns: self.columns
1259 self.bind_child_events(child);
1260 child.datagroup = group;
1262 var $row = child.$row = $('<tr>');
1263 if (group.openable && group.length) {
1264 $row.click(function (e) {
1265 if (!$row.data('open')) {
1266 $row.data('open', true)
1267 .find('span.ui-icon')
1268 .removeClass('ui-icon-triangle-1-e')
1269 .addClass('ui-icon-triangle-1-s');
1270 child.open(self.point_insertion(e.currentTarget));
1272 $row.removeData('open')
1273 .find('span.ui-icon')
1274 .removeClass('ui-icon-triangle-1-s')
1275 .addClass('ui-icon-triangle-1-e');
1280 placeholder.appendChild($row[0]);
1282 var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1283 // Don't fill this if group_by_no_leaf but no group_by
1284 if (group.grouped_on) {
1286 row_data[group.grouped_on] = group;
1287 var group_column = _(self.columns).detect(function (column) {
1288 return column.id === group.grouped_on; });
1289 if (! group_column) {
1290 throw new Error(_.str.sprintf(
1291 _t("Grouping on field '%s' is not possible because that field does not appear in the list view."),
1296 group_label = group_column.format(row_data, {
1297 value_if_empty: _t("Undefined"),
1298 process_modifiers: false
1301 group_label = row_data[group_column.id].value;
1303 $group_column.text(_.str.sprintf("%s (%d)",
1304 group_label, group.length));
1306 if (group.length && group.openable) {
1307 // Make openable if not terminal group & group_by_no_leaf
1308 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1310 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1311 // wonky background position to ensure nothing is displayed
1312 // there but the rest of the behavior is ui-icon's
1313 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1316 self.indent($group_column, group.level);
1318 if (self.options.selectable) {
1319 $row.append('<td>');
1321 _(self.columns).chain()
1322 .filter(function (column) { return column.invisible !== '1'; })
1323 .each(function (column) {
1325 // do not do anything
1326 } else if (column.id in group.aggregates) {
1328 r[column.id] = {value: group.aggregates[column.id]};
1329 $('<td class="oe_number">')
1330 .html(column.format(r, {process_modifiers: false}))
1333 $row.append('<td>');
1336 if (self.options.deletable) {
1337 $row.append('<td class="oe_list_group_pagination">');
1342 bind_child_events: function (child) {
1343 var $this = $(this),
1345 $(child).bind('selected', function (e) {
1346 // can have selections spanning multiple links
1347 var selection = self.get_selection();
1348 $this.trigger(e, [selection.ids, selection.records]);
1349 }).bind(this.passtrough_events, function (e) {
1350 // additional positional parameters are provided to trigger as an
1351 // Array, following the event type or event object, but are
1352 // provided to the .bind event handler as *args.
1353 // Convert our *args back into an Array in order to trigger them
1354 // on the group itself, so it can ultimately be forwarded wherever
1355 // it's supposed to go.
1356 var args = Array.prototype.slice.call(arguments, 1);
1357 $this.trigger.call($this, e, args);
1360 render_dataset: function (dataset) {
1362 list = new (this.view.options.ListType)(this, {
1363 options: this.options,
1364 columns: this.columns,
1366 records: this.records
1368 this.bind_child_events(list);
1370 var view = this.view,
1371 limit = view.limit(),
1372 d = new $.Deferred(),
1373 page = this.datagroup.openable ? this.page : view.page;
1375 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1376 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1377 //TODO xmo: investigate why we need to put the setTimeout
1378 $.async_when().then(function() {dataset.read_slice(fields, options).then(function (records) {
1379 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1380 if (self.records.length) {
1381 self.records.reset(null, {silent: true});
1383 if (!self.datagroup.openable) {
1384 view.configure_pager(dataset);
1386 if (dataset.size() == records.length) {
1388 self.$row.find('td.oe_list_group_pagination').empty();
1390 var pages = Math.ceil(dataset.size() / limit);
1392 .find('.oe_list_pager_state')
1393 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1398 .find('button[data-pager-action=previous]')
1399 .attr('disabled', page === 0)
1401 .find('button[data-pager-action=next]')
1402 .attr('disabled', page === pages - 1);
1406 self.records.add(records, {silent: true});
1409 if (_.isEmpty(records)) {
1415 setup_resequence_rows: function (list, dataset) {
1416 // drag and drop enabled if list is not sorted and there is a
1417 // visible column with @widget=handle or "sequence" column in the view.
1418 if ((dataset.sort && dataset.sort())
1419 || !_(this.columns).any(function (column) {
1420 return column.widget === 'handle'
1421 || column.name === 'sequence'; })) {
1424 var sequence_field = _(this.columns).find(function (c) {
1425 return c.widget === 'handle';
1427 var seqname = sequence_field ? sequence_field.name : 'sequence';
1429 // ondrop, move relevant record & fix sequences
1430 list.$current.sortable({
1432 items: '> tr[data-id]',
1435 if (sequence_field) {
1436 list.$current.sortable('option', 'handle', '.oe_list_field_handle');
1438 list.$current.sortable('option', {
1439 start: function (e, ui) {
1440 ui.placeholder.height(ui.item.height());
1442 stop: function (event, ui) {
1443 var to_move = list.records.get(ui.item.data('id')),
1444 target_id = ui.item.prev().data('id'),
1445 from_index = list.records.indexOf(to_move),
1446 target = list.records.get(target_id);
1447 if (list.records.at(from_index - 1) == target) {
1451 list.records.remove(to_move);
1452 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1453 list.records.add(to_move, { at: to });
1455 // resequencing time!
1456 var record, index = to,
1457 // if drag to 1st row (to = 0), start sequencing from 0
1458 // (exclusive lower bound)
1459 seq = to ? list.records.at(to - 1).get(seqname) : 0;
1460 while (++seq, record = list.records.at(index++)) {
1461 // write are independent from one another, so we can just
1462 // launch them all at the same time and we don't really
1463 // give a fig about when they're done
1464 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1465 // Accounting > Taxes > Taxes, child tax accounts)
1466 // when synchronous (without setTimeout)
1467 (function (dataset, id, seq) {
1468 $.async_when().then(function () {
1470 attrs[seqname] = seq;
1471 dataset.write(id, attrs);
1473 }(dataset, record.get('id'), seq));
1474 record.set(seqname, seq);
1479 render: function (post_render) {
1481 var $el = $('<tbody>');
1482 this.elements = [$el[0]];
1484 this.datagroup.list(
1485 _(this.view.visible_columns).chain()
1486 .filter(function (column) { return column.tag === 'field' })
1487 .pluck('name').value(),
1490 self.render_groups(groups));
1491 if (post_render) { post_render(); }
1492 }, function (dataset) {
1493 self.render_dataset(dataset).then(function (list) {
1494 self.children[null] = list;
1496 [list.$current.replaceAll($el)[0]];
1497 self.setup_resequence_rows(list, dataset);
1498 if (post_render) { post_render(); }
1504 * Returns the ids of all selected records for this group, and the records
1507 get_selection: function () {
1508 var ids = [], records = [];
1511 .each(function (child) {
1512 var selection = child.get_selection();
1513 ids.push.apply(ids, selection.ids);
1514 records.push.apply(records, selection.records);
1517 return {ids: ids, records: records};
1519 on_records_reset: function () {
1521 $(this.elements).remove();
1523 get_records: function () {
1524 if (_(this.children).isEmpty()) {
1525 if (!this.datagroup.length) {
1529 count: this.datagroup.length,
1530 values: this.datagroup.aggregates
1533 return _(this.children).chain()
1534 .map(function (child) {
1535 return child.get_records();
1536 }).flatten().value();
1543 var Events = /** @lends Events# */{
1545 * @param {String} event event to listen to on the current object, null for all events
1546 * @param {Function} handler event handler to bind to the relevant event
1549 bind: function (event, handler) {
1550 var calls = this['_callbacks'] || (this._callbacks = {});
1552 if (event in calls) {
1553 calls[event].push(handler);
1555 calls[event] = [handler];
1560 * @param {String} event event to unbind on the current object
1561 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1564 unbind: function (event, handler) {
1565 var calls = this._callbacks || {};
1566 if (!(event in calls)) { return this; }
1568 delete calls[event];
1570 var handlers = calls[event];
1572 _(handlers).indexOf(handler),
1578 * @param {String} event
1581 trigger: function (event) {
1583 if (!(calls = this._callbacks)) { return this; }
1584 var callbacks = (calls[event] || []).concat(calls[null] || []);
1585 for(var i=0, length=callbacks.length; i<length; ++i) {
1586 callbacks[i].apply(this, arguments);
1591 var Record = instance.web.Class.extend(/** @lends Record# */{
1593 * @constructs Record
1594 * @extends instance.web.Class
1597 * @param {Object} [data]
1599 init: function (data) {
1600 this.attributes = data || {};
1603 * @param {String} key
1606 get: function (key) {
1607 return this.attributes[key];
1612 * @param {Object} [options]
1613 * @param {Boolean} [options.silent=false]
1616 set: function (key, value, options) {
1617 options = options || {};
1618 var old_value = this.attributes[key];
1619 if (old_value === value) {
1622 this.attributes[key] = value;
1623 if (!options.silent) {
1624 this.trigger('change:' + key, this, value, old_value);
1625 this.trigger('change', this, key, value, old_value);
1630 * Converts the current record to the format expected by form views:
1632 * .. code-block:: javascript
1641 * @returns {Object} record displayable in a form view
1643 toForm: function () {
1644 var form_data = {}, attrs = this.attributes;
1645 for(var k in attrs) {
1646 form_data[k] = {value: attrs[k]};
1649 return {data: form_data};
1652 * Converts the current record to a format expected by context evaluations
1653 * (identical to record.attributes, except m2o fields are their integer
1654 * value rather than a pair)
1656 toContext: function () {
1657 var output = {}, attrs = this.attributes;
1658 for(var k in attrs) {
1660 if (typeof val !== 'object') {
1662 } else if (val instanceof Array) {
1665 throw new Error("Can't convert value " + val + " to context");
1671 Record.include(Events);
1672 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1674 * Smarter collections, with events, very strongly inspired by Backbone's.
1676 * Using a "dumb" array of records makes synchronization between the
1679 * @constructs Collection
1680 * @extends instance.web.Class
1683 * @param {Array} [records] records to initialize the collection with
1684 * @param {Object} [options]
1686 init: function (records, options) {
1687 options = options || {};
1688 _.bindAll(this, '_onRecordEvent');
1693 this._key = options.key;
1694 this._parent = options.parent;
1701 * @param {Object|Array} record
1702 * @param {Object} [options]
1703 * @param {Number} [options.at]
1704 * @param {Boolean} [options.silent=false]
1707 add: function (record, options) {
1708 options = options || {};
1709 var records = record instanceof Array ? record : [record];
1711 for(var i=0, length=records.length; i<length; ++i) {
1712 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1713 instance_.bind(null, this._onRecordEvent);
1714 this._byId[instance_.get('id')] = instance_;
1715 if (options.at == undefined) {
1716 this.records.push(instance_);
1717 if (!options.silent) {
1718 this.trigger('add', this, instance_, this.records.length-1);
1721 var insertion_index = options.at + i;
1722 this.records.splice(insertion_index, 0, instance_);
1723 if (!options.silent) {
1724 this.trigger('add', this, instance_, insertion_index);
1733 * Get a record by its index in the collection, can also take a group if
1734 * the collection is not degenerate
1736 * @param {Number} index
1737 * @param {String} [group]
1738 * @returns {Record|undefined}
1740 at: function (index, group) {
1742 var groups = group.split('.');
1743 return this._proxies[groups[0]].at(index, groups.join('.'));
1745 return this.records[index];
1748 * Get a record by its database id
1750 * @param {Number} id
1751 * @returns {Record|undefined}
1753 get: function (id) {
1754 if (!_(this._proxies).isEmpty()) {
1756 _(this._proxies).detect(function (proxy) {
1757 return record = proxy.get(id);
1761 return this._byId[id];
1764 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1765 * the subtree's group
1767 * @param {String} section group path section
1768 * @returns {Collection}
1770 proxy: function (section) {
1771 return this._proxies[section] = new Collection(null, {
1774 }).bind(null, this._onRecordEvent);
1777 * @param {Array} [records]
1780 reset: function (records, options) {
1781 options = options || {};
1782 _(this._proxies).each(function (proxy) {
1786 _(this.records).invoke('unbind', null, this._onRecordEvent);
1793 if (!options.silent) {
1794 this.trigger('reset', this);
1799 * Removes the provided record from the collection
1801 * @param {Record} record
1804 remove: function (record) {
1805 var index = this.indexOf(record);
1807 _(this._proxies).each(function (proxy) {
1808 proxy.remove(record);
1813 record.unbind(null, this._onRecordEvent);
1814 this.records.splice(index, 1);
1815 delete this._byId[record.get('id')];
1817 this.trigger('remove', record, this);
1821 _onRecordEvent: function (event) {
1823 // don't propagate reset events
1824 case 'reset': return;
1826 var record = arguments[1];
1827 var new_value = arguments[2];
1828 var old_value = arguments[3];
1829 // [change:id, record, new_value, old_value]
1830 if (this._byId[old_value] === record) {
1831 delete this._byId[old_value];
1832 this._byId[new_value] = record;
1836 this.trigger.apply(this, arguments);
1839 // underscore-type methods
1840 find: function (callback) {
1842 for(var section in this._proxies) {
1843 if (!this._proxies.hasOwnProperty(section)) {
1846 if ((record = this._proxies[section].find(callback))) {
1850 for(var i=0; i<this.length; ++i) {
1851 record = this.records[i];
1852 if (callback(record)) {
1857 each: function (callback) {
1858 for(var section in this._proxies) {
1859 if (this._proxies.hasOwnProperty(section)) {
1860 this._proxies[section].each(callback);
1863 for(var i=0; i<this.length; ++i) {
1864 callback(this.records[i]);
1867 map: function (callback) {
1869 this.each(function (record) {
1870 results.push(callback(record));
1874 pluck: function (fieldname) {
1875 return this.map(function (record) {
1876 return record.get(fieldname);
1879 indexOf: function (record) {
1880 return _(this.records).indexOf(record);
1882 succ: function (record, options) {
1883 options = options || {wraparound: false};
1885 for(var section in this._proxies) {
1886 if (!this._proxies.hasOwnProperty(section)) {
1889 if ((result = this._proxies[section].succ(record, options))) {
1893 var index = this.indexOf(record);
1894 if (index === -1) { return null; }
1895 var next_index = index + 1;
1896 if (options.wraparound && (next_index === this.length)) {
1899 return this.at(next_index);
1901 pred: function (record, options) {
1902 options = options || {wraparound: false};
1905 for (var section in this._proxies) {
1906 if (!this._proxies.hasOwnProperty(section)) {
1909 if ((result = this._proxies[section].pred(record, options))) {
1914 var index = this.indexOf(record);
1915 if (index === -1) { return null; }
1916 var next_index = index - 1;
1917 if (options.wraparound && (next_index === -1)) {
1918 return this.at(this.length - 1);
1920 return this.at(next_index);
1923 Collection.include(Events);
1924 instance.web.list = {
1927 Collection: Collection
1930 * Registry for column objects used to format table cells (and some other tasks
1931 * e.g. aggregation computations).
1933 * Maps a field or button to a Column type via its ``$tag.$widget``,
1934 * ``$tag.$type`` or its ``$tag`` (alone).
1936 * This specific registry has a dedicated utility method ``for_`` taking a
1937 * field (from fields_get/fields_view_get.field) and a node (from a view) and
1938 * returning the right object *already instantiated from the data provided*.
1940 * @type {instance.web.Registry}
1942 instance.web.list.columns = new instance.web.Registry({
1943 'field': 'instance.web.list.Column',
1944 'field.boolean': 'instance.web.list.Boolean',
1945 'field.binary': 'instance.web.list.Binary',
1946 'field.progressbar': 'instance.web.list.ProgressBar',
1947 'field.handle': 'instance.web.list.Handle',
1948 'button': 'instance.web.list.Button',
1950 instance.web.list.columns.for_ = function (id, field, node) {
1951 var description = _.extend({tag: node.tag}, field, node.attrs);
1952 var tag = description.tag;
1953 var Type = this.get_any([
1954 tag + '.' + description.widget,
1955 tag + '.'+ description.type,
1958 return new Type(id, node.tag, description)
1961 instance.web.list.Column = instance.web.Class.extend({
1962 init: function (id, tag, attrs) {
1968 this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
1969 delete attrs.modifiers;
1970 _.extend(this, attrs);
1972 if (this.modifiers['tree_invisible']) {
1973 this.invisible = '1';
1974 } else { delete this.invisible; }
1976 modifiers_for: function (fields) {
1978 var domain_computer = instance.web.form.compute_domain;
1980 for (var attr in this.modifiers) {
1981 if (!this.modifiers.hasOwnProperty(attr)) { continue; }
1982 var modifier = this.modifiers[attr];
1983 out[attr] = _.isBoolean(modifier)
1985 : domain_computer(modifier, fields);
1990 to_aggregate: function () {
1991 if (this.type !== 'integer' && this.type !== 'float') {
1994 var aggregation_func = this['group_operator'] || 'sum';
1995 if (!(aggregation_func in this)) {
1998 var C = function (label, fn) {
1999 this['function'] = fn;
2003 return new C(aggregation_func, this[aggregation_func]);
2007 * @param row_data record whose values should be displayed in the cell
2008 * @param {Object} [options]
2009 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
2010 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
2011 * @param {String} [options.model] current record's model
2012 * @param {Number} [options.id] current record's id
2015 format: function (row_data, options) {
2016 options = options || {};
2018 if (options.process_modifiers !== false) {
2019 attrs = this.modifiers_for(row_data);
2021 if (attrs.invisible) { return ''; }
2023 if (!row_data[this.id]) {
2024 return options.value_if_empty === undefined
2026 : options.value_if_empty;
2028 return this._format(row_data, options);
2031 * Method to override in order to provide alternative HTML content for the
2032 * cell. Column._format will simply call ``instance.web.format_value`` and
2033 * escape the output.
2035 * The output of ``_format`` will *not* be escaped by ``format``, any
2036 * escaping *must be done* by ``format``.
2040 _format: function (row_data, options) {
2041 return _.escape(instance.web.format_value(
2042 row_data[this.id].value, this, options.value_if_empty));
2045 instance.web.list.MetaColumn = instance.web.list.Column.extend({
2047 init: function (id, string) {
2048 this._super(id, '', {string: string});
2051 instance.web.list.Button = instance.web.list.Column.extend({
2053 * Return an actual ``<button>`` tag
2055 format: function (row_data, options) {
2056 return _.template('<button type="button" title="<%-title%>" <%=additional_attributes%> >' +
2057 '<img src="<%-prefix%>/web/static/src/img/icons/<%-icon%>.png" alt="<%-alt%>"/>' +
2059 title: this.string || '',
2060 additional_attributes: isNaN(row_data["id"].value) && instance.web.BufferedDataSet.virtual_id_regex.test(row_data["id"].value) ?
2061 'disabled="disabled" class="oe_list_button_disabled"' : '',
2062 prefix: instance.session.prefix,
2064 alt: this.string || ''
2068 instance.web.list.Boolean = instance.web.list.Column.extend({
2070 * Return a potentially disabled checkbox input
2074 _format: function (row_data, options) {
2075 return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
2076 row_data[this.id].value ? 'checked="checked"' : '');
2079 instance.web.list.Binary = instance.web.list.Column.extend({
2081 * Return a link to the binary data as a file
2085 _format: function (row_data, options) {
2086 var text = _t("Download");
2087 var download_url = _.str.sprintf(
2088 '/web/binary/saveas?session_id=%s&model=%s&field=%s&id=%d',
2089 instance.session.session_id, options.model, this.id, options.id);
2090 if (this.filename) {
2091 download_url += '&filename_field=' + this.filename;
2092 if (row_data[this.filename]) {
2093 text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
2094 row_data[this.filename].value, {type: 'char'}));
2097 return _.template('<a href="<%-href%>"><%-text%></a> (%<-size%>)', {
2100 size: row_data[this.id].value
2104 instance.web.list.ProgressBar = instance.web.list.Column.extend({
2106 * Return a formatted progress bar display
2110 _format: function (row_data, options) {
2112 '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
2113 value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
2117 instance.web.list.Handle = instance.web.list.Column.extend({
2119 * Return styling hooks for a drag handle
2123 _format: function (row_data, options) {
2124 return '<div class="oe_list_handle">';
2128 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: