3 var instance = openerp;
5 var _t = instance.web._t,
6 _lt = instance.web._lt;
7 var QWeb = instance.web.qweb;
8 instance.web.views.add('list', 'instance.web.ListView');
9 instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
10 _template: 'ListView',
11 display_name: _lt('List'),
13 // records can be selected one by one
15 // list rows can be deleted
17 // whether the column headers should be displayed
19 // display addition button, with that label
20 'addable': _lt("Create"),
21 // whether the list view can be sorted, note that once a view has been
22 // sorted it can not be reordered anymore
24 // whether the view rows can be reordered (via vertical drag & drop)
26 'action_buttons': true,
27 //whether the editable property of the view has to be disabled
28 'disable_editable_mode': false,
32 'click thead th.oe_sortable[data-id]': 'sort_by_column'
35 * Core class for list-type displays.
37 * As a view, needs a number of view-related parameters to be correctly
38 * instantiated, provides options and overridable methods for behavioral
41 * See constructor parameters and method documentations for information on
42 * the default behaviors and possible options for the list view.
44 * @constructs instance.web.ListView
45 * @extends instance.web.View
47 * @param parent parent object
48 * @param {instance.web.DataSet} dataset the dataset the view should work with
49 * @param {String} view_id the listview's identifier, if any
50 * @param {Object} options A set of options used to configure the view
51 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
52 * @param {Boolean} [options.header=true] should the list's header be displayed
53 * @param {Boolean} [options.deletable=true] are the list rows deletable
54 * @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.
55 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
56 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
58 init: function(parent, dataset, view_id, options) {
61 this.set_default_options(_.extend({}, this.defaults, options || {}));
62 this.dataset = dataset;
63 this.model = dataset.model;
64 this.view_id = view_id;
65 this.previous_colspan = null;
71 this.records = new Collection();
73 this.set_groups(new (this.options.GroupsType)(this));
75 if (this.dataset instanceof instance.web.DataSetStatic) {
76 this.groups.datagroup = new StaticDataGroup(this.dataset);
78 this.groups.datagroup = new DataGroup(
81 dataset.get_context());
82 this.groups.datagroup.sort = this.dataset._sort;
86 this.records.bind('change', function (event, record, key) {
87 if (!_(self.aggregate_columns).chain()
88 .pluck('name').contains(key).value()) {
91 self.compute_aggregates();
97 view_loading: function(r) {
98 return this.load_list(r);
100 set_default_options: function (options) {
101 this._super(options);
102 _.defaults(this.options, {
103 GroupsType: instance.web.ListView.Groups,
104 ListType: instance.web.ListView.List
109 * Retrieves the view's number of records per page (|| section)
111 * options > defaults > parent.action.limit > indefinite
113 * @returns {Number|null}
116 if (this._limit === undefined) {
117 this._limit = (this.options.limit
118 || this.defaults.limit
119 || (this.getParent().action || {}).limit
125 * Set a custom Group construct as the root of the List View.
127 * @param {instance.web.ListView.Groups} groups
129 set_groups: function (groups) {
132 $(this.groups).unbind("selected deleted action row_link");
136 this.groups = groups;
137 $(this.groups).bind({
138 'selected': function (e, ids, records, deselected) {
139 self.do_select(ids, records, deselected);
141 'deleted': function (e, ids) {
144 'action': function (e, action_name, id, callback) {
145 self.do_button_action(action_name, id, callback);
147 'row_link': function (e, id, dataset, view) {
148 self.do_activate_record(dataset.index, id, dataset, view);
153 * View startup method, the default behavior is to set the ``oe_list``
154 * class on its root element and to perform an RPC load call.
156 * @returns {$.Deferred} loading promise
159 this.$el.addClass('oe_list');
160 return this._super();
163 * Returns the style for the provided record in the current view (from the
164 * ``@colors`` and ``@fonts`` attributes)
166 * @param {Record} record record for the current row
167 * @returns {String} CSS style declaration
169 style_for: function (record) {
172 var context = _.extend({}, record.attributes, {
173 uid: this.session.uid,
174 current_date: moment().format('YYYY-MM-DD')
175 // TODO: time, datetime, relativedelta
181 for(i=0, len=this.fonts.length; i<len; ++i) {
182 pair = this.fonts[i];
184 expression = pair[1];
185 if (py.evaluate(expression, context).toJSON()) {
188 style += 'font-weight: bold;';
191 style += 'font-style: italic;';
194 style += 'text-decoration: underline;';
201 if (!this.colors) { return style; }
202 for(i=0, len=this.colors.length; i<len; ++i) {
203 pair = this.colors[i];
205 expression = pair[1];
206 if (py.evaluate(expression, context).toJSON()) {
207 return style += 'color: ' + color + ';';
209 // TODO: handle evaluation errors
214 * Called after loading the list view's description, sets up such things
215 * as the view table's columns, renders the table itself and hooks up the
216 * various table-level and row-level DOM events (action buttons, deletion
217 * buttons, selection of records, [New] button, selection of a given
220 * Sets up the following:
222 * * Processes arch and fields to generate a complete field descriptor for each field
223 * * Create the table itself and allocate visible columns
224 * * Hook in the top-level (header) [New|Add] and [Delete] button
225 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
226 * * Sets up event handlers for action buttons and per-row deletion button
227 * * Hooks global callback for clicking on a row
228 * * Sets up its sidebar, if any
230 * @param {Object} data wrapped fields_view_get result
231 * @param {Object} data.fields_view fields_view_get result (processed)
232 * @param {Object} data.fields_view.fields mapping of fields for the current model
233 * @param {Object} data.fields_view.arch current list view descriptor
234 * @param {Boolean} grouped Is the list view grouped
236 load_list: function(data) {
238 this.fields_view = data;
239 this.name = "" + this.fields_view.arch.attrs.string;
241 if (this.fields_view.arch.attrs.colors) {
242 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
244 .map(function(color_pair) {
245 var pair = color_pair.split(':'),
248 return [color, py.parse(py.tokenize(expr)), expr];
252 if (this.fields_view.arch.attrs.fonts) {
253 this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
254 .map(function(font_pair) {
255 var pair = font_pair.split(':'),
258 return [font, py.parse(py.tokenize(expr)), expr];
262 this.setup_columns(this.fields_view.fields, this.grouped);
264 this.$el.html(QWeb.render(this._template, this));
265 this.$el.addClass(this.fields_view.arch.attrs['class']);
269 this.$el.find('.oe_list_record_selector').click(function(){
270 self.$el.find('.oe_list_record_selector input').prop('checked',
271 self.$el.find('.oe_list_record_selector').prop('checked') || false);
272 var selection = self.groups.get_selection();
273 $(self.groups).trigger(
274 'selected', [selection.ids, selection.records]);
278 if (!this.$buttons) {
279 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
280 if (this.options.$buttons) {
281 this.$buttons.appendTo(this.options.$buttons);
283 this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
285 this.$buttons.find('.oe_list_add')
286 .click(this.proxy('do_add_record'))
287 .prop('disabled', this.grouped);
292 this.$pager = $(QWeb.render("ListView.pager", {'widget':self})).hide();
293 if (this.options.$buttons) {
294 this.$pager.appendTo(this.options.$pager);
296 this.$el.find('.oe_list_pager').replaceWith(this.$pager);
300 .on('click', 'a[data-pager-action]', function () {
302 var max_page = Math.floor(self.dataset.size() / self.limit());
303 switch ($this.data('pager-action')) {
305 self.page = 0; break;
307 self.page = max_page - 1;
310 self.page += 1; break;
312 self.page -= 1; break;
315 self.page = max_page;
316 } else if (self.page > max_page) {
319 self.reload_content();
320 }).find('.oe_list_pager_state')
321 .click(function (e) {
325 var $select = $('<select>')
326 .appendTo($this.empty())
327 .click(function (e) {e.stopPropagation();})
328 .append('<option value="80">80</option>' +
329 '<option value="200">200</option>' +
330 '<option value="500">500</option>' +
331 '<option value="2000">2000</option>' +
332 '<option value="NaN">' + _t("Unlimited") + '</option>')
333 .change(function () {
334 var val = parseInt($select.val(), 10);
335 self._limit = (isNaN(val) ? null : val);
337 self.reload_content();
339 $(this).trigger('change');
341 .val(self._limit || 'NaN');
346 if (!this.sidebar && this.options.$sidebar) {
347 this.sidebar = new instance.web.Sidebar(this);
348 this.sidebar.appendTo(this.options.$sidebar);
349 this.sidebar.add_items('other', _.compact([
350 { label: _t("Export"), callback: this.on_sidebar_export },
351 self.is_action_enabled('delete') && { label: _t('Delete'), callback: this.do_delete_selected }
353 this.sidebar.add_toolbar(this.fields_view.toolbar);
354 this.sidebar.$el.hide();
357 var default_order = this.fields_view.arch.attrs.default_order,
358 unsorted = !this.dataset._sort.length;
359 if (unsorted && default_order) {
360 this.dataset.set_sort(default_order.split(','));
363 if(this.dataset._sort.length){
364 if(this.dataset._sort[0].indexOf('-') == -1){
365 this.$el.find('th[data-id=' + this.dataset._sort[0] + ']').addClass("sortdown");
367 this.$el.find('th[data-id=' + this.dataset._sort[0].split('-')[1] + ']').addClass("sortup");
370 this.trigger('list_view_loaded', data, this.grouped);
372 sort_by_column: function (e) {
374 var $column = $(e.currentTarget);
375 var col_name = $column.data('id');
376 var field = this.fields_view.fields[col_name];
377 // test whether the field is sortable
378 if (field && !field.sortable) {
381 this.dataset.sort(col_name);
382 if($column.hasClass("sortdown") || $column.hasClass("sortup")) {
383 $column.toggleClass("sortup sortdown");
385 $column.addClass("sortdown");
387 $column.siblings('.oe_sortable').removeClass("sortup sortdown");
389 this.reload_content();
392 * Configures the ListView pager based on the provided dataset's information
394 * Horrifying side-effect: sets the dataset's data on this.dataset?
396 * @param {instance.web.DataSet} dataset
398 configure_pager: function (dataset) {
399 this.dataset.ids = dataset.ids;
401 if (dataset._length) {
402 this.dataset._length = dataset._length;
405 var total = dataset.size();
406 var limit = this.limit() || total;
407 this.$pager.find('.oe-pager-button').toggle(total > limit);
408 this.$pager.find('.oe_pager_value').toggle(total !== 0);
411 var range_start = this.page * limit + 1;
412 var range_stop = range_start - 1 + limit;
413 if (this.records.length) {
414 range_stop = range_start - 1 + this.records.length;
416 if (range_stop > total) {
419 spager = _.str.sprintf(_t("%d-%d of %d"), range_start, range_stop, total);
422 this.$pager.find('.oe_list_pager_state').text(spager);
425 * Sets up the listview's columns: merges view and fields data, move
426 * grouped-by columns to the front of the columns list and make them all
429 * @param {Object} fields fields_view_get's fields section
430 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
432 setup_columns: function (fields, grouped) {
433 var registry = instance.web.list.columns;
434 this.columns.splice(0, this.columns.length);
435 this.columns.push.apply(this.columns,
436 _(this.fields_view.arch.children).map(function (field) {
437 var id = field.attrs.name;
438 return registry.for_(id, fields[id], field);
441 this.columns.unshift(
442 new instance.web.list.MetaColumn('_group', _t("Group")));
445 this.visible_columns = _.filter(this.columns, function (column) {
446 return column.invisible !== '1';
449 this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
452 * Used to handle a click on a table row, if no other handler caught the
455 * The default implementation asks the list view's view manager to switch
456 * to a different view (by calling
457 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
458 * provided record index (within the current list view's dataset).
460 * If the index is null, ``switch_to_record`` asks for the creation of a
463 * @param {Number|void} index the record index (in the current dataset) to switch to
464 * @param {String} [view="page"] the view type to switch to
466 select_record:function (index, view) {
467 view = view || index === null || index === undefined ? 'form' : 'form';
468 this.dataset.index = index;
469 _.delay(_.bind(function () {
470 this.do_switch_view(view);
473 do_show: function () {
476 this.$buttons.show();
482 do_hide: function () {
484 this.sidebar.$el.hide();
487 this.$buttons.hide();
495 * Reloads the list view based on the current settings (dataset & al)
498 * @param {Boolean} [grouped] Should the list be displayed grouped
499 * @param {Object} [context] context to send the server while loading the view
501 reload_view: function (grouped, context, initial) {
502 return this.load_view(context);
505 * re-renders the content of the list view
507 * @returns {$.Deferred} promise to content reloading
509 reload_content: synchronized(function () {
511 self.$el.find('.oe_list_record_selector').prop('checked', false);
512 this.records.reset();
513 var reloaded = $.Deferred();
514 reloaded.then(function () {
515 if (!self.grouped) self.$pager.show();
517 this.$el.find('.oe_list_content').append(
518 this.groups.render(function () {
519 if (self.dataset.index == null) {
520 if (self.records.length) {
521 self.dataset.index = 0;
523 } else if (self.dataset.index >= self.records.length) {
524 self.dataset.index = self.records.length ? 0 : null;
527 self.compute_aggregates();
534 return reloaded.promise();
536 reload: function () {
537 return this.reload_content();
539 reload_record: function (record) {
541 var fields = this.fields_view.fields;
542 return this.dataset.read_ids(
544 _.pluck(_(this.columns).filter(function (r) {
545 return r.tag === 'field';
547 {check_access_rule: true}
548 ).done(function (records) {
549 var values = records[0];
551 self.records.remove(record);
554 _.each(values, function (value, key) {
555 if (fields[key] && fields[key].type === 'many2many')
556 record.set(key + '__display', false, {silent: true});
557 record.set(key, value, {silent: true});
559 record.trigger('change', record);
563 do_load_state: function(state, warm) {
565 if (state.page && this.page !== state.page) {
566 this.page = state.page;
570 if (_.isString(state.limit)) {
573 if (state.limit !== this._limit) {
574 this._limit = state.limit;
579 this.reload_content();
583 * Handler for the result of eval_domain_and_context, actually perform the
586 * @param {Object} results results of evaluating domain and process for a search
588 do_search: function (domain, context, group_by) {
590 this.groups.datagroup = new DataGroup(
591 this, this.model, domain, context, group_by);
592 this.groups.datagroup.sort = this.dataset._sort;
594 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
597 this.no_leaf = !!context['group_by_no_leaf'];
598 this.grouped = !!group_by;
600 return this.alive(this.load_view(context)).then(
601 this.proxy('reload_content'));
604 * Handles the signal to delete lines from the records list
606 * @param {Array} ids the ids of the records to delete
608 do_delete: function (ids) {
609 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
613 return $.when(this.dataset.unlink(ids)).done(function () {
614 _(ids).each(function (id) {
615 self.records.remove(self.records.get(id));
617 if (self.records.length === 0 && self.dataset.size() > 0) {
618 //Trigger previous manually to navigate to previous page,
619 //If all records are deleted on current page.
620 self.$pager.find('ul li:first a').trigger('click');
621 } else if (self.dataset.size() == self.limit()) {
622 //Reload listview to update current page with next page records
623 //because pager going to be hidden if dataset.size == limit
626 self.configure_pager(self.dataset);
628 self.compute_aggregates();
632 * Handles the signal indicating that a new record has been selected
634 * @param {Array} ids selected record ids
635 * @param {Array} records selected record values
637 do_select: function (ids, records, deselected) {
638 // uncheck header hook if at least one row has been deselected
640 this.$('.oe_list_record_selector').prop('checked', false);
644 this.dataset.index = 0;
646 this.sidebar.$el.hide();
648 this.compute_aggregates();
652 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
654 this.options.$sidebar.show();
655 this.sidebar.$el.show();
658 this.compute_aggregates(_(records).map(function (record) {
659 return {count: 1, values: record};
663 * Handles action button signals on a record
665 * @param {String} name action name
666 * @param {Object} id id of the record the action should be called on
667 * @param {Function} callback should be called after the action is executed, if non-null
669 do_button_action: function (name, id, callback) {
670 this.handle_button(name, id, callback);
673 * Base handling of buttons, can be called when overriding do_button_action
674 * in order to bypass parent overrides.
676 * The callback will be provided with the ``id`` as its parameter, in case
677 * handle_button's caller had to alter the ``id`` (or even create one)
678 * while not being ``callback``'s creator.
680 * This method should not be overridden.
682 * @param {String} name action name
683 * @param {Object} id id of the record the action should be called on
684 * @param {Function} callback should be called after the action is executed, if non-null
686 handle_button: function (name, id, callback) {
687 var action = _.detect(this.columns, function (field) {
688 return field.name === name;
690 if (!action) { return; }
691 if ('confirm' in action && !window.confirm(action.confirm)) {
695 var c = new instance.web.CompoundContext();
696 c.set_eval_context(_.extend({
699 active_model: this.dataset.model
700 }, this.records.get(id).toContext()));
701 if (action.context) {
702 c.add(action.context);
705 this.do_execute_action(
706 action, this.dataset, id, _.bind(callback, null, id));
709 * Handles the activation of a record (clicking on it)
711 * @param {Number} index index of the record in the dataset
712 * @param {Object} id identifier of the activated record
713 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
715 do_activate_record: function (index, id, dataset, view) {
716 this.dataset.ids = dataset.ids;
717 this.select_record(index, view);
720 * Handles signal for the addition of a new record (can be a creation,
721 * can be the addition from a remote source, ...)
723 * The default implementation is to switch to a new record on the form view
725 do_add_record: function () {
726 this.select_record(null);
729 * Handles deletion of all selected lines
731 do_delete_selected: function () {
732 var ids = this.groups.get_selection().ids;
734 this.do_delete(this.groups.get_selection().ids);
736 this.do_warn(_t("Warning"), _t("You must select at least one record."));
740 * Computes the aggregates for the current list view, either on the
741 * records provided or on the records of the internal
742 * :js:class:`~instance.web.ListView.Group`, by calling
743 * :js:func:`~instance.web.ListView.group.get_records`.
745 * Then displays the aggregates in the table through
746 * :js:method:`~instance.web.ListView.display_aggregates`.
748 * @param {Array} [records]
750 compute_aggregates: function (records) {
751 var columns = _(this.aggregate_columns).filter(function (column) {
752 return column['function']; });
753 if (_.isEmpty(columns)) { return; }
755 if (_.isEmpty(records)) {
756 records = this.groups.get_records();
758 records = _(records).compact();
760 var count = 0, sums = {};
761 _(columns).each(function (column) {
762 switch (column['function']) {
764 sums[column.id] = -Infinity;
767 sums[column.id] = Infinity;
773 _(records).each(function (record) {
774 count += record.count || 1;
775 _(columns).each(function (column) {
776 var field = column.id,
777 value = record.values[field];
778 switch (column['function']) {
780 sums[field] += value;
783 sums[field] += record.count * value;
786 if (sums[field] > value) {
791 if (sums[field] < value) {
800 _(columns).each(function (column) {
801 var field = column.id;
802 switch (column['function']) {
804 aggregates[field] = {value: sums[field] / count};
807 aggregates[field] = {value: sums[field]};
811 this.display_aggregates(aggregates);
813 display_aggregates: function (aggregation) {
815 var $footer_cells = this.$el.find('.oe_list_footer');
816 _(this.aggregate_columns).each(function (column) {
817 if (!column['function']) {
821 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
822 .html(column.format(aggregation, { process_modifiers: false }));
825 get_selected_ids: function() {
826 var ids = this.groups.get_selection().ids;
830 * Calculate the active domain of the list view. This should be done only
831 * if the header checkbox has been checked. This is done by evaluating the
832 * search results, and then adding the dataset domain (i.e. action domain).
834 get_active_domain: function () {
836 if (this.$('.oe_list_record_selector').prop('checked')) {
837 var search_view = this.getParent().searchview;
838 var search_data = search_view.build_search_data();
839 return instance.web.pyeval.eval_domains_and_contexts({
840 domains: search_data.domains,
841 contexts: search_data.contexts,
842 group_by_seq: search_data.groupbys || []
843 }).then(function (results) {
844 var domain = self.dataset.domain.concat(results.domain || []);
849 return $.Deferred().resolve();
853 * Adds padding columns at the start or end of all table rows (including
856 * @param {Number} count number of columns to add
857 * @param {Object} options
858 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
859 * @param {Object} [options.except] content row to not pad
861 pad_columns: function (count, options) {
862 options = options || {};
863 // padding for action/pager header
864 var $first_header = this.$el.find('thead tr:first th');
865 var colspan = $first_header.attr('colspan');
867 if (!this.previous_colspan) {
868 this.previous_colspan = colspan;
870 $first_header.attr('colspan', parseInt(colspan, 10) + count);
872 // Padding for column titles, footer and data rows
874 .find('.oe_list_header_columns, tr:not(thead tr)')
875 .not(options['except']);
876 var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
877 if (options.position === 'before') {
878 $rows.prepend(newcols);
880 $rows.append(newcols);
884 * Removes all padding columns of the table
886 unpad_columns: function () {
887 this.$el.find('.oe_list_padding').remove();
888 if (this.previous_colspan) {
890 .find('thead tr:first th')
891 .attr('colspan', this.previous_colspan);
892 this.previous_colspan = null;
895 no_result: function () {
896 this.$el.find('.oe_view_nocontent').remove();
897 if (this.groups.group_by
898 || !this.options.action
899 || !this.options.action.help) {
902 this.$el.find('table:first').hide();
904 $('<div class="oe_view_nocontent">').html(this.options.action.help)
906 var $buttons = this.$buttons;
907 this.$el.find('.oe_view_nocontent').click(function() {
908 $buttons.width($buttons.width() + 1).openerpBounce();
912 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
914 * List display for the ListView, handles basic DOM events and transforms
915 * them in the relevant higher-level events, to which the list view (or
916 * other consumers) can subscribe.
918 * Events on this object are registered via jQuery.
923 * Triggered when a row is selected (using check boxes), provides an
924 * array of ids of all the selected records.
926 * Triggered when deletion buttons are hit, provide an array of ids of
927 * all the records being marked for suppression.
929 * Triggered when an action button is clicked, provides two parameters:
931 * * The name of the action to execute (as a string)
932 * * The id of the record to execute the action on
934 * Triggered when a row of the table is clicked, provides the index (in
935 * the rows array) and id of the selected record to the handle function.
937 * @constructs instance.web.ListView.List
938 * @extends instance.web.Class
940 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
942 init: function (group, opts) {
945 this.view = group.view;
946 this.session = this.view.session;
948 this.options = opts.options;
949 this.columns = opts.columns;
950 this.dataset = opts.dataset;
951 this.records = opts.records;
953 this.record_callbacks = {
954 'remove': function (event, record) {
955 var id = record.get('id');
956 self.dataset.remove_ids([id]);
957 var $row = self.$current.children('[data-id=' + id + ']');
958 var index = $row.data('index');
961 'reset': function () { return self.on_records_reset(); },
962 'change': function (event, record, attribute, value, old_value) {
964 if (attribute === 'id') {
966 throw new Error(_.str.sprintf( _t("Setting 'id' attribute on existing record %s"),
967 JSON.stringify(record.attributes) ));
969 self.dataset.add_ids([value], self.records.indexOf(record));
970 // Set id on new record
971 $row = self.$current.children('[data-id=false]');
973 $row = self.$current.children(
974 '[data-id=' + record.get('id') + ']');
976 $row.replaceWith(self.render_record(record));
978 'add': function (ev, records, record, index) {
979 var $new_row = $(self.render_record(record));
980 var id = record.get('id');
981 if (id) { self.dataset.add_ids([id], index); }
984 $new_row.prependTo(self.$current);
986 var previous_record = records.at(index-1),
987 $previous_sibling = self.$current.children(
988 '[data-id=' + previous_record.get('id') + ']');
989 $new_row.insertAfter($previous_sibling);
993 _(this.record_callbacks).each(function (callback, event) {
994 this.records.bind(event, callback);
997 this.$current = $('<tbody>')
998 .delegate('input[readonly=readonly]', 'click', function (e) {
1000 Against all logic and sense, as of right now @readonly
1001 apparently does nothing on checkbox and radio inputs, so
1002 the trick of using @readonly to have, well, readonly
1003 checkboxes (which still let clicks go through) does not
1004 work out of the box. We *still* need to preventDefault()
1005 on the event, otherwise the checkbox's state *will* toggle
1010 .delegate('th.oe_list_record_selector', 'click', function (e) {
1011 e.stopPropagation();
1012 var selection = self.get_selection();
1013 var checked = $(e.currentTarget).find('input').prop('checked');
1015 'selected', [selection.ids, selection.records, ! checked]);
1017 .delegate('td.oe_list_record_delete button', 'click', function (e) {
1018 e.stopPropagation();
1019 var $row = $(e.target).closest('tr');
1020 $(self).trigger('deleted', [[self.row_id($row)]]);
1022 .delegate('td.oe_list_field_cell button', 'click', function (e) {
1023 e.stopPropagation();
1024 var $target = $(e.currentTarget),
1025 field = $target.closest('td').data('field'),
1026 $row = $target.closest('tr'),
1027 record_id = self.row_id($row);
1029 if ($target.attr('disabled')) {
1032 $target.attr('disabled', 'disabled');
1034 // note: $.data converts data to number if it's composed only
1035 // of digits, nice when storing actual numbers, not nice when
1036 // storing strings composed only of digits. Force the action
1037 // name to be a string
1038 $(self).trigger('action', [field.toString(), record_id, function (id) {
1039 $target.removeAttr('disabled');
1040 return self.reload_record(self.records.get(id));
1043 .delegate('a', 'click', function (e) {
1044 e.stopPropagation();
1046 .delegate('tr', 'click', function (e) {
1047 var row_id = self.row_id(e.currentTarget);
1049 e.stopPropagation();
1050 if (!self.dataset.select_id(row_id)) {
1051 throw new Error(_t("Could not find id in dataset"));
1053 self.row_clicked(e);
1057 row_clicked: function (e, view) {
1060 [this.dataset.ids[this.dataset.index],
1061 this.dataset, view]);
1063 render_cell: function (record, column) {
1065 if(column.type === 'reference') {
1066 value = record.get(column.id);
1068 // Ensure that value is in a reference "shape", otherwise we're
1069 // going to loop on performing name_get after we've resolved (and
1070 // set) a human-readable version. m2o does not have this issue
1071 // because the non-human-readable is just a number, where the
1072 // human-readable version is a pair
1073 if (value && (ref_match = /^([\w\.]+),(\d+)$/.exec(value))) {
1074 // reference values are in the shape "$model,$id" (as a
1075 // string), we need to split and name_get this pair in order
1076 // to get a correctly displayable value in the field
1077 var model = ref_match[1],
1078 id = parseInt(ref_match[2], 10);
1079 new instance.web.DataSet(this.view, model).name_get([id]).done(function(names) {
1080 if (!names.length) { return; }
1081 record.set(column.id + '__display', names[0][1]);
1084 } else if (column.type === 'many2one') {
1085 value = record.get(column.id);
1086 // m2o values are usually name_get formatted, [Number, String]
1087 // pairs, but in some cases only the id is provided. In these
1088 // cases, we need to perform a name_get call to fetch the actual
1089 // displayable value
1090 if (typeof value === 'number' || value instanceof Number) {
1091 // fetch the name, set it on the record (in the right field)
1092 // and let the various registered events handle refreshing the
1094 new instance.web.DataSet(this.view, column.relation)
1095 .name_get([value]).done(function (names) {
1096 if (!names.length) { return; }
1097 record.set(column.id, names[0]);
1100 } else if (column.type === 'many2many') {
1101 value = record.get(column.id);
1102 // non-resolved (string) m2m values are arrays
1103 if (value instanceof Array && !_.isEmpty(value)
1104 && !record.get(column.id + '__display')) {
1106 // they come in two shapes:
1107 if (value[0] instanceof Array) {
1108 var command = value[0];
1109 // 1. an array of m2m commands (usually (6, false, ids))
1110 if (command[0] !== 6) {
1111 throw new Error(_.str.sprintf( _t("Unknown m2m command %s"), command[0]));
1115 // 2. an array of ids
1118 new instance.web.Model(column.relation)
1119 .call('name_get', [ids, this.dataset.context]).done(function (names) {
1120 // FIXME: nth horrible hack in this poor listview
1121 record.set(column.id + '__display',
1122 _(names).pluck(1).join(', '));
1123 record.set(column.id, ids);
1126 record.set(column.id, false);
1129 return column.format(record.toForm().data, {
1130 model: this.dataset.model,
1131 id: record.get('id')
1134 render: function () {
1135 this.$current.empty().append(
1136 QWeb.render('ListView.rows', _.extend({
1137 render_cell: function () {
1138 return self.render_cell.apply(self, arguments); }
1140 this.pad_table_to(4);
1142 pad_table_to: function (count) {
1143 if (this.records.length >= count ||
1144 _(this.columns).any(function(column) { return column.meta; })) {
1148 if (this.options.selectable) {
1149 cells.push('<th class="oe_list_record_selector"></td>');
1151 _(this.columns).each(function(column) {
1152 if (column.invisible === '1') {
1155 cells.push('<td title="' + column.string + '"> </td>');
1157 if (this.options.deletable) {
1158 cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1160 cells.unshift('<tr>');
1161 cells.push('</tr>');
1163 var row = cells.join('');
1165 .children('tr:not([data-id])').remove().end()
1166 .append(new Array(count - this.records.length + 1).join(row));
1169 * Gets the ids of all currently selected records, if any
1170 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1172 get_selection: function () {
1173 var result = {ids: [], records: []};
1174 if (!this.options.selectable) {
1177 var records = this.records;
1178 this.$current.find('th.oe_list_record_selector input:checked')
1179 .closest('tr').each(function () {
1180 var record = records.get($(this).data('id'));
1181 result.ids.push(record.get('id'));
1182 result.records.push(record.attributes);
1187 * Returns the identifier of the object displayed in the provided table
1190 * @param {Object} row the selected table row
1191 * @returns {Number|String} the identifier of the row's object
1193 row_id: function (row) {
1194 return $(row).data('id');
1197 * Death signal, cleans up list display
1199 on_records_reset: function () {
1200 _(this.record_callbacks).each(function (callback, event) {
1201 this.records.unbind(event, callback);
1203 if (!this.$current) { return; }
1204 this.$current.remove();
1206 get_records: function () {
1207 return this.records.map(function (record) {
1208 return {count: 1, values: record.attributes};
1212 * Reloads the provided record by re-reading its content from the server.
1214 * @param {Record} record
1215 * @returns {$.Deferred} promise to the finalization of the reloading
1217 reload_record: function (record) {
1218 return this.view.reload_record(record);
1221 * Renders a list record to HTML
1223 * @param {Record} record index of the record to render in ``this.rows``
1224 * @returns {String} QWeb rendering of the selected record
1226 render_record: function (record) {
1228 var index = this.records.indexOf(record);
1229 return QWeb.render('ListView.row', {
1230 columns: this.columns,
1231 options: this.options,
1233 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1235 render_cell: function () {
1236 return self.render_cell.apply(self, arguments); }
1240 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1241 passthrough_events: 'action deleted row_link',
1243 * Grouped display for the ListView. Handles basic DOM events and interacts
1244 * with the :js:class:`~DataGroup` bound to it.
1246 * Provides events similar to those of
1247 * :js:class:`~instance.web.ListView.List`
1249 * @constructs instance.web.ListView.Groups
1250 * @extends instance.web.Class
1252 * @param {instance.web.ListView} view
1253 * @param {Object} [options]
1254 * @param {Collection} [options.records]
1255 * @param {Object} [options.options]
1256 * @param {Array} [options.columns]
1258 init: function (view, options) {
1259 options = options || {};
1261 this.records = options.records || view.records;
1262 this.options = options.options || view.options;
1263 this.columns = options.columns || view.columns;
1264 this.datagroup = null;
1272 this.records.bind('reset', function () {
1273 return self.on_records_reset(); });
1275 make_fragment: function () {
1276 return document.createDocumentFragment();
1279 * Returns a DOM node after which a new tbody can be inserted, so that it
1280 * follows the provided row.
1282 * Necessary to insert the result of a new group or list view within an
1283 * existing groups render, without losing track of the groups's own
1286 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1287 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1289 point_insertion: function (row) {
1291 var red_letter_tboday = $row.closest('tbody')[0];
1293 var $next_siblings = $row.nextAll();
1294 if ($next_siblings.length) {
1295 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1297 $root_kanal.append($next_siblings);
1298 this.elements.splice(
1299 _.indexOf(this.elements, red_letter_tboday),
1303 return red_letter_tboday;
1305 make_paginator: function () {
1307 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1308 .click(function (e) {
1309 e.stopPropagation();
1312 self.$row.closest('tbody').next()
1313 .replaceWith(self.render());
1315 var $next = $('<button type="button" data-pager-action="next">></button>')
1316 .click(function (e) {
1317 e.stopPropagation();
1320 self.$row.closest('tbody').next()
1321 .replaceWith(self.render());
1323 this.$row.children().last()
1324 .addClass('oe_list_group_pagination')
1326 .append('<span class="oe_list_pager_state"></span>')
1329 open: function (point_insertion) {
1330 this.render().insertAfter(point_insertion);
1332 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1333 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1334 if (no_subgroups && records_terminated) {
1335 this.make_paginator();
1338 close: function () {
1339 this.$row.children().last().find('button').remove();
1340 this.$row.children().last().find('span').remove();
1341 this.records.reset();
1344 * Prefixes ``$node`` with floated spaces in order to indent it relative
1345 * to its own left margin/baseline
1347 * @param {jQuery} $node jQuery object to indent
1348 * @param {Number} level current nesting level, >= 1
1349 * @returns {jQuery} the indentation node created
1351 indent: function ($node, level) {
1353 .css({'float': 'left', 'white-space': 'pre'})
1354 .text(new Array(level).join(' '))
1357 render_groups: function (datagroups) {
1359 var placeholder = this.make_fragment();
1360 _(datagroups).each(function (group) {
1361 if (self.children[group.value]) {
1362 self.records.proxy(group.value).reset();
1363 delete self.children[group.value];
1365 var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1366 records: self.records.proxy(group.value),
1367 options: self.options,
1368 columns: self.columns
1370 self.bind_child_events(child);
1371 child.datagroup = group;
1373 var $row = child.$row = $('<tr class="oe_group_header">');
1374 if (group.openable && group.length) {
1375 $row.click(function (e) {
1376 if (!$row.data('open')) {
1377 $row.data('open', true)
1378 .find('span.ui-icon')
1379 .removeClass('ui-icon-triangle-1-e')
1380 .addClass('ui-icon-triangle-1-s');
1381 child.open(self.point_insertion(e.currentTarget));
1383 $row.removeData('open')
1384 .find('span.ui-icon')
1385 .removeClass('ui-icon-triangle-1-s')
1386 .addClass('ui-icon-triangle-1-e');
1388 // force recompute the selection as closing group reset properties
1389 var selection = self.get_selection();
1390 $(self).trigger('selected', [selection.ids, this.records]);
1394 placeholder.appendChild($row[0]);
1396 var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1397 // Don't fill this if group_by_no_leaf but no group_by
1398 if (group.grouped_on) {
1400 row_data[group.grouped_on] = group;
1401 var group_label = _t("Undefined");
1402 var group_column = _(self.columns).detect(function (column) {
1403 return column.id === group.grouped_on; });
1406 group_label = group_column.format(row_data, {
1407 value_if_empty: _t("Undefined"),
1408 process_modifiers: false
1411 group_label = _.str.escapeHTML(row_data[group_column.id].value);
1414 group_label = group.value;
1415 if (group_label instanceof Array) {
1416 group_label = group_label[1];
1418 if (group_label === false) {
1419 group_label = _t('Undefined');
1421 group_label = _.str.escapeHTML(group_label);
1424 // group_label is html-clean (through format or explicit
1425 // escaping if format failed), can inject straight into HTML
1426 $group_column.html(_.str.sprintf(_t("%s (%d)"),
1427 group_label, group.length));
1429 if (group.length && group.openable) {
1430 // Make openable if not terminal group & group_by_no_leaf
1431 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1433 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1434 // wonky background position to ensure nothing is displayed
1435 // there but the rest of the behavior is ui-icon's
1436 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1439 self.indent($group_column, group.level);
1441 if (self.options.selectable) {
1442 $row.append('<td>');
1444 _(self.columns).chain()
1445 .filter(function (column) { return column.invisible !== '1'; })
1446 .each(function (column) {
1448 // do not do anything
1449 } else if (column.id in group.aggregates) {
1451 r[column.id] = {value: group.aggregates[column.id]};
1452 $('<td class="oe_number">')
1453 .html(column.format(r, {process_modifiers: false}))
1456 $row.append('<td>');
1459 if (self.options.deletable) {
1460 $row.append('<td class="oe_list_group_pagination">');
1465 bind_child_events: function (child) {
1466 var $this = $(this),
1468 $(child).bind('selected', function (e, _0, _1, deselected) {
1469 // can have selections spanning multiple links
1470 var selection = self.get_selection();
1471 $this.trigger(e, [selection.ids, selection.records, deselected]);
1472 }).bind(this.passthrough_events, function (e) {
1473 // additional positional parameters are provided to trigger as an
1474 // Array, following the event type or event object, but are
1475 // provided to the .bind event handler as *args.
1476 // Convert our *args back into an Array in order to trigger them
1477 // on the group itself, so it can ultimately be forwarded wherever
1478 // it's supposed to go.
1479 var args = Array.prototype.slice.call(arguments, 1);
1480 $this.trigger.call($this, e, args);
1483 render_dataset: function (dataset) {
1485 list = new (this.view.options.ListType)(this, {
1486 options: this.options,
1487 columns: this.columns,
1489 records: this.records
1491 this.bind_child_events(list);
1493 var view = this.view,
1494 limit = view.limit(),
1495 page = this.datagroup.openable ? this.page : view.page;
1497 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field";}), 'name');
1498 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1499 //TODO xmo: investigate why we need to put the setTimeout
1500 return $.async_when().then(function() {
1501 return dataset.read_slice(fields, options).then(function (records) {
1502 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1503 if (self.records.length) {
1504 self.records.reset(null, {silent: true});
1506 if (!self.datagroup.openable) {
1507 view.configure_pager(dataset);
1509 if (dataset.size() == records.length) {
1511 self.$row.find('td.oe_list_group_pagination').find('button').remove();
1512 self.$row.find('td.oe_list_group_pagination').find('span').remove();
1514 var pages = Math.ceil(dataset.size() / limit);
1516 .find('.oe_list_pager_state')
1517 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1522 .find('button[data-pager-action=previous]')
1523 .toggleClass('disabled', page === 0)
1525 .find('button[data-pager-action=next]')
1526 .toggleClass('disabled', page === pages - 1);
1530 self.records.add(records, {silent: true});
1532 if (_.isEmpty(records)) {
1539 setup_resequence_rows: function (list, dataset) {
1540 // drag and drop enabled if list is not sorted and there is a
1541 // visible column with @widget=handle or "sequence" column in the view.
1542 if ((dataset.sort && dataset.sort())
1543 || !_(this.columns).any(function (column) {
1544 return column.widget === 'handle'
1545 || column.name === 'sequence'; })) {
1548 var sequence_field = _(this.columns).find(function (c) {
1549 return c.widget === 'handle';
1551 var seqname = sequence_field ? sequence_field.name : 'sequence';
1553 // ondrop, move relevant record & fix sequences
1554 list.$current.sortable({
1556 items: '> tr[data-id]',
1559 if (sequence_field) {
1560 list.$current.sortable('option', 'handle', '.oe_list_field_handle');
1562 list.$current.sortable('option', {
1563 start: function (e, ui) {
1564 ui.placeholder.height(ui.item.height());
1566 stop: function (event, ui) {
1567 var to_move = list.records.get(ui.item.data('id')),
1568 target_id = ui.item.prev().data('id'),
1569 from_index = list.records.indexOf(to_move),
1570 target = list.records.get(target_id);
1571 if (list.records.at(from_index - 1) == target) {
1575 list.records.remove(to_move);
1576 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1577 list.records.add(to_move, { at: to });
1579 // resequencing time!
1580 var record, index = to,
1581 // if drag to 1st row (to = 0), start sequencing from 0
1582 // (exclusive lower bound)
1583 seq = to ? list.records.at(to - 1).get(seqname) : 0;
1584 var fct = function (dataset, id, seq) {
1585 $.async_when().done(function () {
1587 attrs[seqname] = seq;
1588 dataset.write(id, attrs);
1591 while (++seq, (record = list.records.at(index++))) {
1592 // write are independent from one another, so we can just
1593 // launch them all at the same time and we don't really
1594 // give a fig about when they're done
1595 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1596 // Accounting > Taxes > Taxes, child tax accounts)
1597 // when synchronous (without setTimeout)
1598 fct(dataset, record.get('id'), seq);
1599 record.set(seqname, seq);
1604 render: function (post_render) {
1606 var $el = $('<tbody>');
1607 this.elements = [$el[0]];
1609 this.datagroup.list(
1610 _(this.view.visible_columns).chain()
1611 .filter(function (column) { return column.tag === 'field';})
1612 .pluck('name').value(),
1614 self.view.$pager.hide();
1616 self.render_groups(groups));
1617 if (post_render) { post_render(); }
1618 }, function (dataset) {
1619 self.render_dataset(dataset).then(function (list) {
1620 self.children[null] = list;
1622 [list.$current.replaceAll($el)[0]];
1623 self.setup_resequence_rows(list, dataset);
1624 }).always(function() {
1625 if (post_render) { post_render(); }
1626 self.view.trigger('view_list_rendered');
1632 * Returns the ids of all selected records for this group, and the records
1635 get_selection: function () {
1636 var ids = [], records = [];
1639 .each(function (child) {
1640 var selection = child.get_selection();
1641 ids.push.apply(ids, selection.ids);
1642 records.push.apply(records, selection.records);
1645 return {ids: ids, records: records};
1647 on_records_reset: function () {
1649 $(this.elements).remove();
1651 get_records: function () {
1652 if (_(this.children).isEmpty()) {
1653 if (!this.datagroup.length) {
1657 count: this.datagroup.length,
1658 values: this.datagroup.aggregates
1661 return _(this.children).chain()
1662 .map(function (child) {
1663 return child.get_records();
1664 }).flatten().value();
1669 * Serializes concurrent calls to this asynchronous method. The method must
1670 * return a deferred or promise.
1672 * Current-implementation is class-serialized (the mutex is common to all
1673 * instances of the list view). Can be switched to instance-serialized if
1674 * having concurrent list views becomes possible and common.
1676 function synchronized(fn) {
1677 var fn_mutex = new $.Mutex();
1678 return function () {
1680 var args = _.toArray(arguments);
1681 return fn_mutex.exec(function () {
1682 if (obj.isDestroyed()) { return $.when(); }
1683 return fn.apply(obj, args)
1687 var DataGroup = instance.web.Class.extend({
1688 init: function(parent, model, domain, context, group_by, level) {
1689 this.model = new instance.web.Model(model, context, domain);
1690 this.group_by = group_by;
1691 this.context = context;
1692 this.domain = domain;
1694 this.level = level || 0;
1696 list: function (fields, ifGroups, ifRecords) {
1698 if (!_.isEmpty(this.group_by)) {
1699 // ensure group_by fields are read.
1700 fields = _.unique((fields || []).concat(this.group_by));
1702 var query = this.model.query(fields).order_by(this.sort).group_by(this.group_by);
1703 $.when(query).done(function (querygroups) {
1706 var ds = new instance.web.DataSetSearch(self, self.model.name, self.model.context(), self.model.domain());
1707 ds._sort = self.sort;
1712 var child_datagroups = _(querygroups).map(function (group) {
1713 var child_context = _.extend(
1714 {}, self.model.context(), group.model.context());
1715 var child_dg = new DataGroup(
1716 self, self.model.name, group.model.domain(),
1717 child_context, group.model._context.group_by,
1719 child_dg.sort = self.sort;
1720 // copy querygroup properties
1721 child_dg.__context = child_context;
1722 child_dg.__domain = group.model.domain();
1723 child_dg.folded = group.get('folded');
1724 child_dg.grouped_on = group.get('grouped_on');
1725 child_dg.length = group.get('length');
1726 child_dg.value = group.get('value');
1727 child_dg.openable = group.get('has_children');
1728 child_dg.aggregates = group.get('aggregates');
1731 ifGroups(child_datagroups);
1735 var StaticDataGroup = DataGroup.extend({
1736 init: function (dataset) {
1737 this.dataset = dataset;
1739 list: function (fields, ifGroups, ifRecords) {
1740 ifRecords(this.dataset);
1747 var Events = /** @lends Events# */{
1749 * @param {String} event event to listen to on the current object, null for all events
1750 * @param {Function} handler event handler to bind to the relevant event
1753 bind: function (event, handler) {
1754 var calls = this['_callbacks'] || (this._callbacks = {});
1756 if (event in calls) {
1757 calls[event].push(handler);
1759 calls[event] = [handler];
1764 * @param {String} event event to unbind on the current object
1765 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1768 unbind: function (event, handler) {
1769 var calls = this._callbacks || {};
1770 if (!(event in calls)) { return this; }
1772 delete calls[event];
1774 var handlers = calls[event];
1776 _(handlers).indexOf(handler),
1782 * @param {String} event
1785 trigger: function (event) {
1787 if (!(calls = this._callbacks)) { return this; }
1788 var callbacks = (calls[event] || []).concat(calls[null] || []);
1789 for(var i=0, length=callbacks.length; i<length; ++i) {
1790 callbacks[i].apply(this, arguments);
1795 var Record = instance.web.Class.extend(/** @lends Record# */{
1797 * @constructs Record
1798 * @extends instance.web.Class
1801 * @param {Object} [data]
1803 init: function (data) {
1804 this.attributes = data || {};
1807 * @param {String} key
1810 get: function (key) {
1811 return this.attributes[key];
1816 * @param {Object} [options]
1817 * @param {Boolean} [options.silent=false]
1820 set: function (key, value, options) {
1821 options = options || {};
1822 var old_value = this.attributes[key];
1823 if (old_value === value) {
1826 this.attributes[key] = value;
1827 if (!options.silent) {
1828 this.trigger('change:' + key, this, value, old_value);
1829 this.trigger('change', this, key, value, old_value);
1834 * Converts the current record to the format expected by form views:
1836 * .. code-block:: javascript
1845 * @returns {Object} record displayable in a form view
1847 toForm: function () {
1848 var form_data = {}, attrs = this.attributes;
1849 for(var k in attrs) {
1850 form_data[k] = {value: attrs[k]};
1853 return {data: form_data};
1856 * Converts the current record to a format expected by context evaluations
1857 * (identical to record.attributes, except m2o fields are their integer
1858 * value rather than a pair)
1860 toContext: function () {
1861 var output = {}, attrs = this.attributes;
1862 for(var k in attrs) {
1864 if (typeof val !== 'object') {
1866 } else if (val instanceof Array) {
1869 throw new Error(_.str.sprintf(_t("Can't convert value %s to context"), val));
1875 Record.include(Events);
1876 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1878 * Smarter collections, with events, very strongly inspired by Backbone's.
1880 * Using a "dumb" array of records makes synchronization between the
1883 * @constructs Collection
1884 * @extends instance.web.Class
1887 * @param {Array} [records] records to initialize the collection with
1888 * @param {Object} [options]
1890 init: function (records, options) {
1891 options = options || {};
1892 _.bindAll(this, '_onRecordEvent');
1897 this._key = options.key;
1898 this._parent = options.parent;
1905 * @param {Object|Array} record
1906 * @param {Object} [options]
1907 * @param {Number} [options.at]
1908 * @param {Boolean} [options.silent=false]
1911 add: function (record, options) {
1912 options = options || {};
1913 var records = record instanceof Array ? record : [record];
1915 for(var i=0, length=records.length; i<length; ++i) {
1916 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1917 instance_.bind(null, this._onRecordEvent);
1918 this._byId[instance_.get('id')] = instance_;
1919 if (options.at === undefined || options.at === null) {
1920 this.records.push(instance_);
1921 if (!options.silent) {
1922 this.trigger('add', this, instance_, this.records.length-1);
1925 var insertion_index = options.at + i;
1926 this.records.splice(insertion_index, 0, instance_);
1927 if (!options.silent) {
1928 this.trigger('add', this, instance_, insertion_index);
1937 * Get a record by its index in the collection, can also take a group if
1938 * the collection is not degenerate
1940 * @param {Number} index
1941 * @param {String} [group]
1942 * @returns {Record|undefined}
1944 at: function (index, group) {
1946 var groups = group.split('.');
1947 return this._proxies[groups[0]].at(index, groups.join('.'));
1949 return this.records[index];
1952 * Get a record by its database id
1954 * @param {Number} id
1955 * @returns {Record|undefined}
1957 get: function (id) {
1958 if (!_(this._proxies).isEmpty()) {
1960 _(this._proxies).detect(function (proxy) {
1961 record = proxy.get(id);
1966 return this._byId[id];
1969 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1970 * the subtree's group
1972 * @param {String} section group path section
1973 * @returns {Collection}
1975 proxy: function (section) {
1976 this._proxies[section] = new Collection(null, {
1979 }).bind(null, this._onRecordEvent);
1980 return this._proxies[section];
1983 * @param {Array} [records]
1986 reset: function (records, options) {
1987 options = options || {};
1988 _(this._proxies).each(function (proxy) {
1992 _(this.records).invoke('unbind', null, this._onRecordEvent);
1999 if (!options.silent) {
2000 this.trigger('reset', this);
2005 * Removes the provided record from the collection
2007 * @param {Record} record
2010 remove: function (record) {
2011 var index = this.indexOf(record);
2013 _(this._proxies).each(function (proxy) {
2014 proxy.remove(record);
2019 record.unbind(null, this._onRecordEvent);
2020 this.records.splice(index, 1);
2021 delete this._byId[record.get('id')];
2023 this.trigger('remove', record, this);
2027 _onRecordEvent: function (event) {
2029 // don't propagate reset events
2030 case 'reset': return;
2032 var record = arguments[1];
2033 var new_value = arguments[2];
2034 var old_value = arguments[3];
2035 // [change:id, record, new_value, old_value]
2036 if (this._byId[old_value] === record) {
2037 delete this._byId[old_value];
2038 this._byId[new_value] = record;
2042 this.trigger.apply(this, arguments);
2045 // underscore-type methods
2046 find: function (callback) {
2048 for(var section in this._proxies) {
2049 if (!this._proxies.hasOwnProperty(section)) {
2052 if ((record = this._proxies[section].find(callback))) {
2056 for(var i=0; i<this.length; ++i) {
2057 record = this.records[i];
2058 if (callback(record)) {
2063 each: function (callback) {
2064 for(var section in this._proxies) {
2065 if (this._proxies.hasOwnProperty(section)) {
2066 this._proxies[section].each(callback);
2069 for(var i=0; i<this.length; ++i) {
2070 callback(this.records[i]);
2073 map: function (callback) {
2075 this.each(function (record) {
2076 results.push(callback(record));
2080 pluck: function (fieldname) {
2081 return this.map(function (record) {
2082 return record.get(fieldname);
2085 indexOf: function (record) {
2086 return _(this.records).indexOf(record);
2088 succ: function (record, options) {
2089 options = options || {wraparound: false};
2091 for(var section in this._proxies) {
2092 if (!this._proxies.hasOwnProperty(section)) {
2095 if ((result = this._proxies[section].succ(record, options))) {
2099 var index = this.indexOf(record);
2100 if (index === -1) { return null; }
2101 var next_index = index + 1;
2102 if (options.wraparound && (next_index === this.length)) {
2105 return this.at(next_index);
2107 pred: function (record, options) {
2108 options = options || {wraparound: false};
2111 for (var section in this._proxies) {
2112 if (!this._proxies.hasOwnProperty(section)) {
2115 if ((result = this._proxies[section].pred(record, options))) {
2120 var index = this.indexOf(record);
2121 if (index === -1) { return null; }
2122 var next_index = index - 1;
2123 if (options.wraparound && (next_index === -1)) {
2124 return this.at(this.length - 1);
2126 return this.at(next_index);
2129 Collection.include(Events);
2130 instance.web.list = {
2133 Collection: Collection
2136 * Registry for column objects used to format table cells (and some other tasks
2137 * e.g. aggregation computations).
2139 * Maps a field or button to a Column type via its ``$tag.$widget``,
2140 * ``$tag.$type`` or its ``$tag`` (alone).
2142 * This specific registry has a dedicated utility method ``for_`` taking a
2143 * field (from fields_get/fields_view_get.field) and a node (from a view) and
2144 * returning the right object *already instantiated from the data provided*.
2146 * @type {instance.web.Registry}
2148 instance.web.list.columns = new instance.web.Registry({
2149 'field': 'instance.web.list.Column',
2150 'field.boolean': 'instance.web.list.Boolean',
2151 'field.binary': 'instance.web.list.Binary',
2152 'field.char': 'instance.web.list.Char',
2153 'field.progressbar': 'instance.web.list.ProgressBar',
2154 'field.handle': 'instance.web.list.Handle',
2155 'button': 'instance.web.list.Button',
2156 'field.many2onebutton': 'instance.web.list.Many2OneButton',
2157 'field.reference': 'instance.web.list.Reference',
2158 'field.many2many': 'instance.web.list.Many2Many',
2159 'button.toggle_button': 'instance.web.list.toggle_button',
2161 instance.web.list.columns.for_ = function (id, field, node) {
2162 var description = _.extend({tag: node.tag}, field, node.attrs);
2163 var tag = description.tag;
2164 var Type = this.get_any([
2165 tag + '.' + description.widget,
2166 tag + '.'+ description.type,
2169 return new Type(id, node.tag, description);
2172 instance.web.list.Column = instance.web.Class.extend({
2173 init: function (id, tag, attrs) {
2179 this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
2180 delete attrs.modifiers;
2181 _.extend(this, attrs);
2183 if (this.modifiers['tree_invisible']) {
2184 this.invisible = '1';
2185 } else { delete this.invisible; }
2187 modifiers_for: function (fields) {
2189 var domain_computer = instance.web.form.compute_domain;
2191 for (var attr in this.modifiers) {
2192 if (!this.modifiers.hasOwnProperty(attr)) { continue; }
2193 var modifier = this.modifiers[attr];
2194 out[attr] = _.isBoolean(modifier)
2196 : domain_computer(modifier, fields);
2201 to_aggregate: function () {
2202 if (this.type !== 'integer' && this.type !== 'float') {
2205 var aggregation_func = this['group_operator'] || 'sum';
2206 if (!(aggregation_func in this)) {
2209 var C = function (fn, label) {
2210 this['function'] = fn;
2214 return new C(aggregation_func, this[aggregation_func]);
2218 * @param row_data record whose values should be displayed in the cell
2219 * @param {Object} [options]
2220 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
2221 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
2222 * @param {String} [options.model] current record's model
2223 * @param {Number} [options.id] current record's id
2226 format: function (row_data, options) {
2227 options = options || {};
2229 if (options.process_modifiers !== false) {
2230 attrs = this.modifiers_for(row_data);
2232 if (attrs.invisible) { return ''; }
2234 if (!row_data[this.id]) {
2235 return options.value_if_empty === undefined
2237 : options.value_if_empty;
2239 return this._format(row_data, options);
2242 * Method to override in order to provide alternative HTML content for the
2243 * cell. Column._format will simply call ``instance.web.format_value`` and
2244 * escape the output.
2246 * The output of ``_format`` will *not* be escaped by ``format``, any
2247 * escaping *must be done* by ``format``.
2251 _format: function (row_data, options) {
2252 return _.escape(instance.web.format_value(
2253 row_data[this.id].value, this, options.value_if_empty));
2256 instance.web.list.MetaColumn = instance.web.list.Column.extend({
2258 init: function (id, string) {
2259 this._super(id, '', {string: string});
2262 instance.web.list.Button = instance.web.list.Column.extend({
2264 * Return an actual ``<button>`` tag
2266 format: function (row_data, options) {
2267 options = options || {};
2269 if (options.process_modifiers !== false) {
2270 attrs = this.modifiers_for(row_data);
2272 if (attrs.invisible) { return ''; }
2273 var template = this.icon && 'ListView.row.button' || 'ListView.row.text_button';
2274 return QWeb.render(template, {
2276 prefix: instance.session.prefix,
2277 disabled: attrs.readonly
2278 || isNaN(row_data.id.value)
2279 || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
2283 instance.web.list.Boolean = instance.web.list.Column.extend({
2285 * Return a potentially disabled checkbox input
2289 _format: function (row_data, options) {
2290 return _.str.sprintf('<input type="checkbox" %s readonly="readonly"/>',
2291 row_data[this.id].value ? 'checked="checked"' : '');
2294 instance.web.list.Binary = instance.web.list.Column.extend({
2296 * Return a link to the binary data as a file
2300 _format: function (row_data, options) {
2301 var text = _t("Download");
2302 var value = row_data[this.id].value;
2304 if (value && value.substr(0, 10).indexOf(' ') == -1) {
2305 download_url = "data:application/octet-stream;base64," + value;
2307 download_url = instance.session.url('/web/binary/saveas', {model: options.model, field: this.id, id: options.id});
2308 if (this.filename) {
2309 download_url += '&filename_field=' + this.filename;
2312 if (this.filename && row_data[this.filename]) {
2313 text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
2314 row_data[this.filename].value, {type: 'char'}));
2316 return _.template('<a href="<%-href%>"><%-text%></a> (<%-size%>)', {
2319 size: instance.web.binary_to_binsize(value),
2323 instance.web.list.Char = instance.web.list.Column.extend({
2326 * If password field, only display replacement characters (if value is
2329 _format: function (row_data, options) {
2330 var value = row_data[this.id].value;
2331 if (value && this.password === 'True') {
2332 return value.replace(/[\s\S]/g, _.escape(this.replacement));
2334 return this._super(row_data, options);
2337 instance.web.list.ProgressBar = instance.web.list.Column.extend({
2339 * Return a formatted progress bar display
2343 _format: function (row_data, options) {
2345 '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
2346 value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
2350 instance.web.list.Handle = instance.web.list.Column.extend({
2352 this._super.apply(this, arguments);
2353 // Handle overrides the field to not be form-editable.
2354 this.modifiers.readonly = true;
2357 * Return styling hooks for a drag handle
2361 _format: function (row_data, options) {
2362 return '<div class="oe_list_handle">';
2365 instance.web.list.Many2OneButton = instance.web.list.Column.extend({
2366 _format: function (row_data, options) {
2367 this.has_value = !!row_data[this.id].value;
2368 this.icon = this.has_value ? 'gtk-yes' : 'gtk-no';
2369 this.string = this.has_value ? _t('View') : _t('Create');
2370 return QWeb.render('Many2OneButton.cell', {
2372 'prefix': instance.session.prefix,
2376 instance.web.list.Many2Many = instance.web.list.Column.extend({
2377 _format: function (row_data, options) {
2378 if (!_.isEmpty(row_data[this.id].value)) {
2379 // If value, use __display version for printing
2380 row_data[this.id] = row_data[this.id + '__display'];
2382 return this._super(row_data, options);
2385 instance.web.list.Reference = instance.web.list.Column.extend({
2386 _format: function (row_data, options) {
2387 if (!_.isEmpty(row_data[this.id].value)) {
2388 // If value, use __display version for printing
2389 if (!!row_data[this.id + '__display']) {
2390 row_data[this.id] = row_data[this.id + '__display'];
2392 row_data[this.id] = {'value': ''};
2395 return this._super(row_data, options);
2398 instance.web.list.toggle_button = instance.web.list.Column.extend({
2399 format: function (row_data, options) {
2400 this._super(row_data, options);
2401 var button_tips = JSON.parse(this.options);
2402 var fieldname = this.field_name;
2403 var has_value = row_data[fieldname] && !!row_data[fieldname].value;
2404 this.icon = has_value ? 'gtk-yes' : 'gtk-normal';
2405 this.string = has_value ? _t(button_tips ? button_tips['active']: ''): _t(button_tips ? button_tips['inactive']: '');
2406 return QWeb.render('toggle_button', {
2408 prefix: instance.session.prefix,