1 if(!dojo._hasResource['openils.widget.AutoFieldWidget']) {
2 dojo.provide('openils.widget.AutoFieldWidget');
3 dojo.require('openils.Util');
4 dojo.require('openils.User');
5 dojo.require('fieldmapper.IDL');
6 dojo.require('openils.PermaCrud');
7 dojo.requireLocalization("openils.widget", "AutoFieldWidget");
9 dojo.declare('openils.widget.AutoFieldWidget', null, {
15 * idlField -- Field description object from fieldmapper.IDL.fmclasses
16 * fmObject -- If available, the object being edited. This will be used
17 * to set the value of the widget.
18 * fmClass -- Class name (not required if idlField or fmObject is set)
19 * fmField -- Field name (not required if idlField)
20 * parentNode -- If defined, the widget will be appended to this DOM node
21 * dijitArgs -- Optional parameters object, passed directly to the dojo widget
22 * orgLimitPerms -- If this field defines a set of org units and an orgLimitPerms
23 * is defined, the code will limit the org units in the set to those
24 * allowed by the permission
25 * orgDefaultsToWs -- If this is an org unit field and the widget has no value,
26 * set the value equal to the users's workstation org unit. Othwerwise, leave it null
27 * selfReference -- The primary purpose of an AutoFieldWidget is to render the value
28 * or widget for a field on an object (that may or may not link to another object).
29 * selfReference allows you to sidestep the indirection and create a selector widget
30 * based purely on an fmClass. To get a dropdown of all of the 'abc'
31 * objects, pass in {selfReference : true, fmClass : 'abc'}.
32 * labelFormat -- For widgets that are displayed as remote object filtering selects,
33 * this provides a mechanism for overriding the label format in the filtering select.
34 * It must be an array, whose first value is a format string, compliant with
35 * dojo.string.substitute. The remaining array items are the arguments to the format
36 * represented as field names on the remote linked object.
38 * labelFormat : [ '${0} (${1})', 'obj_field_1', 'obj_field_2' ]
39 * Note: this does not control the final display value. Only values in the drop-down.
40 * See searchFormat for controlling the display value
41 * searchFormat -- This format controls the structure of the search attribute which
42 * controls the text used during type-ahead searching and the displayed value in
43 * the filtering select. See labelFormat for the structure.
44 * dataLoader : Bypass the default PermaCrud linked data fetcher and use this function instead.
45 * Function arguments are (link class name, search filter, callback)
46 * The fetched objects should be passed to the callback as an array
47 * disableQuery : dojo.data query passed to FilteringTreeSelect-based widgets to disable
48 * (but leave visible) certain options.
49 * useWriteStore : tells AFW to use a dojo.data.ItemFileWriteStore instead of a ReadStore for
50 * data stores created with dynamic data. This allows the caller to add/remove items from
53 constructor : function(args) {
57 if (!this.dijitArgs) {
60 this.dijitArgs['scrollOnFocus'] = false;
63 // find the field description in the IDL if not provided
65 this.fmClass = this.fmObject.classname;
66 this.fmIDL = fieldmapper.IDL.fmclasses[this.fmClass];
68 if(this.fmClass && !this.fmIDL) {
69 fieldmapper.IDL.load([this.fmClass]);
70 this.fmIDL = fieldmapper.IDL.fmclasses[this.fmClass];
73 this.suppressLinkedFields = args.suppressLinkedFields || [];
75 if(this.selfReference) {
76 this.fmField = fieldmapper.IDL.fmclasses[this.fmClass].pkey;
78 // create a mock-up of the idlField object.
81 'class' : this.fmClass,
90 this.fmIDL = fieldmapper.IDL.fmclasses[this.fmClass];
91 var fields = this.fmIDL.fields;
93 if(fields[f].name == this.fmField)
94 this.idlField = fields[f];
99 throw new Error("AutoFieldWidget could not determine which " +
100 "field to render. We need more information. fmClass=" +
101 this.fmClass + ' fmField=' + this.fmField + ' fmObject=' + js2JSON(this.fmObject));
103 this.auth = openils.User.authtoken;
104 this.cache = openils.widget.AutoFieldWidget.cache;
105 this.cache[this.auth] = this.cache[this.auth] || {};
106 this.cache[this.auth].single = this.cache[this.auth].single || {};
107 this.cache[this.auth].list = this.cache[this.auth].list || {};
109 if (this.useWriteStore) {
110 dojo.require('dojo.data.ItemFileWriteStore');
111 this.storeConstructor = dojo.data.ItemFileWriteStore;
113 this.storeConstructor = dojo.data.ItemFileReadStore;
118 * Turn the widget-stored value into a value oils understands
120 getFormattedValue : function() {
121 var value = this.baseWidgetValue();
122 switch(this.idlField.datatype) {
125 case 'true': return 't';
126 case 'on': return 't';
127 case 'false' : return 'f';
128 case 'unset' : return null;
129 case true : return 't';
133 if(!value) return null;
134 return dojo.date.stamp.toISOString(value);
138 if(isNaN(value)) value = null;
140 return (value === '') ? null : value;
144 baseWidgetValue : function(value) {
145 var attr = (this.readOnly) ? 'content' : 'value';
146 if(arguments.length) this.widget.attr(attr, value);
147 return this.widget.attr(attr);
151 * Turn the widget-stored value into something visually suitable
153 getDisplayString : function() {
154 var value = this.widgetValue;
160 return openils.widget.AutoFieldWidget.localeStrings.INHERITED;
163 switch(this.idlField.datatype) {
168 return openils.widget.AutoFieldWidget.localeStrings.TRUE;
171 return openils.widget.AutoFieldWidget.localeStrings.FALSE;
173 case 'unset' : return openils.widget.AutoFieldWidget.localeStrings.UNSET;
174 case true : return openils.widget.AutoFieldWidget.localeStrings.TRUE;
175 default: return openils.widget.AutoFieldWidget.localeStrings.FALSE;
178 if (!value) return '';
179 return openils.Util.timeStamp(
180 value, {"formatLength": "short"}
183 if(value === null || value === undefined) return '';
184 return fieldmapper.aou.findOrgUnit(value).shortname();
187 if(isNaN(value)) value = 0;
189 if(value === undefined || value === null)
195 isRequired : function() {
198 this.idlField.required || (
200 this.dijitArgs.required || this.dijitArgs.regExp
207 build : function(onload) {
209 if(this.widgetValue == null)
210 this.widgetValue = (this.fmObject) ? this.fmObject[this.idlField.name]() : null;
213 // core widget provided for us, attach and move on
214 if(this.parentNode) // may already be in the "right" place
215 this.parentNode.appendChild(this.widget.domNode);
217 if (this.shove.mode == "update") {
218 if (this.idlField.datatype == "timestamp")
219 this.widgetValue = openils.Util.timeStampAsDateObj(
223 this.widgetValue = this.shove.create;
225 this._widgetLoaded();
226 } else if (this.widget.attr("value") == null) {
227 this._widgetLoaded();
232 if(!this.parentNode) // give it somewhere to live so that dojo won't complain
233 this.parentNode = dojo.create('div');
235 this.onload = onload;
238 dojo.require('dijit.layout.ContentPane');
239 this.widget = new dijit.layout.ContentPane(this.dijitArgs, this.parentNode);
240 if(this.widgetValue !== null)
241 this._tryLinkedDisplayField();
243 } else if(this.widgetClass) {
244 dojo.require(this.widgetClass);
245 eval('this.widget = new ' + this.widgetClass + '(this.dijitArgs, this.parentNode);');
249 switch(this.idlField.datatype) {
252 dojo.require('dijit.form.TextBox');
253 this.widget = new dijit.form.TextBox(this.dijitArgs, this.parentNode);
257 this._buildOrgSelector();
261 // dojo.require('dijit.form.CurrencyTextBox');
262 // the CurrencyTextBox dijit is broken in Dojo 1.3; upon upgrading
263 // to Dojo 1.5 or later, should re-evaluate work-around use of dijit.form.NumberTextBox.
264 // See https://bugs.launchpad.net/evergreen/+bug/702117
265 dojo.require('dijit.form.NumberTextBox');
266 this.dijitArgs = dojo.mixin({constraints:{places:'0,2'}}, this.dijitArgs || {});
267 this.widget = new dijit.form.NumberTextBox(this.dijitArgs, this.parentNode);
271 dojo.require('dijit.form.NumberTextBox');
272 this.dijitArgs = dojo.mixin({constraints:{places:0}}, this.dijitArgs || {});
273 this.widget = new dijit.form.NumberTextBox(this.dijitArgs, this.parentNode);
277 dojo.require('dijit.form.NumberTextBox');
278 this.widget = new dijit.form.NumberTextBox(this.dijitArgs, this.parentNode);
282 dojo.require('dijit.form.DateTextBox');
283 dojo.require('dojo.date.stamp');
284 if(!this.dijitArgs.constraints) {
285 this.dijitArgs.constraints = {};
287 if(!this.dijitArgs.constraints.datePattern) {
288 var user = new openils.User().user;
290 var datePattern = fieldmapper.aou.fetchOrgSettingDefault(user.ws_ou(), 'format.date');
291 if(datePattern) this.dijitArgs.constraints.datePattern = datePattern.value;
294 this.widget = new dijit.form.DateTextBox(this.dijitArgs, this.parentNode);
295 if (this.widgetValue != null) {
296 this.widgetValue = openils.Util.timeStampAsDateObj(
303 if(this.ternary || this.inherits) {
304 dojo.require('dijit.form.FilteringSelect');
305 var store = new dojo.data.ItemFileReadStore({
307 identifier : 'value',
309 {label : (this.inherits ? openils.widget.AutoFieldWidget.localeStrings.INHERITED : openils.widget.AutoFieldWidget.localeStrings.UNSET), value : 'unset'},
310 {label : openils.widget.AutoFieldWidget.localeStrings.TRUE, value : 'true'},
311 {label : openils.widget.AutoFieldWidget.localeStrings.FALSE, value : 'false'}
315 this.widget = new dijit.form.FilteringSelect(this.dijitArgs, this.parentNode);
316 this.widget.searchAttr = this.widget.labelAttr = 'label';
317 this.widget.valueAttr = 'value';
318 this.widget.store = store;
319 this.widget.startup();
320 this.widgetValue = (this.widgetValue === null) ? 'unset' :
321 (openils.Util.isTrue(this.widgetValue)) ? 'true' : 'false';
323 dojo.require('dijit.form.CheckBox');
324 this.widget = new dijit.form.CheckBox(this.dijitArgs, this.parentNode);
325 this.widgetValue = openils.Util.isTrue(this.widgetValue);
330 if(this._buildLinkSelector()) break;
333 if(this.dijitArgs && (this.dijitArgs.required || this.dijitArgs.regExp)) {
334 dojo.require('dijit.form.ValidationTextBox');
335 this.widget = new dijit.form.ValidationTextBox(this.dijitArgs, this.parentNode);
337 dojo.require('dijit.form.TextBox');
338 this.widget = new dijit.form.TextBox(this.dijitArgs, this.parentNode);
343 if(!this.async) this._widgetLoaded();
347 // we want to display the value for our widget. However, instead of displaying
348 // an ID, for exmaple, display the value for the 'selector' field on the object
350 _tryLinkedDisplayField : function(noAsync) {
352 if(this.idlField.datatype == 'org_unit')
353 return false; // we already handle org_units, no need to re-fetch
355 // user opted to bypass fetching this linked data
356 if(this.suppressLinkedFields.indexOf(this.idlField.name) > -1)
359 var linkInfo = this._getLinkSelector();
360 if(!(linkInfo && linkInfo.vfield && linkInfo.vfield.selector))
362 var lclass = linkInfo.linkClass;
367 // first try the store cache
369 if(this.cache[this.auth].list[lclass]) {
370 var store = this.cache[this.auth].list[lclass];
372 query[linkInfo.vfield.name] = ''+this.widgetValue;
374 store.fetch({query:query, onComplete:
378 if(self.labelFormat) {
379 self.widgetValue = self._applyLabelFormat(item, self.labelFormat);
381 self.widgetValue = store.getValue(item, linkInfo.vfield.selector);
391 // then try the single object cache
393 if(this.cache[this.auth].single[lclass] && (
394 item = this.cache[this.auth].single[lclass][this.widgetValue]) ) {
396 this.widgetValue = (this.labelFormat) ?
397 this._applyLabelFormat(item.toStoreItem(), this.labelFormat) :
398 item[linkInfo.vfield.selector]();
403 console.log("Fetching linked object " + lclass + " : " + this.widgetValue);
405 // if those fail, fetch the linked object
408 new openils.PermaCrud().retrieve(lclass, this.widgetValue, {
409 async : !this.forceSync,
410 oncomplete : function(r) {
411 var item = openils.Util.readResponse(r);
413 // cache the true object under its real value
414 if(!self.cache[self.auth].single[lclass])
415 self.cache[self.auth].single[lclass] = {};
416 self.cache[self.auth].single[lclass][self.widgetValue] = item;
418 self.widgetValue = (self.labelFormat) ?
419 self._applyLabelFormat(item.toStoreItem(), self.labelFormat) :
420 item[linkInfo.vfield.selector]();
422 self.widget.startup();
423 self._widgetLoaded();
428 _getLinkSelector : function() {
429 var linkClass = this.idlField['class'];
430 if(this.idlField.reltype != 'has_a') return false;
431 if(!fieldmapper.IDL.fmclasses[linkClass]) // class neglected by AutoIDL
432 fieldmapper.IDL.load([linkClass]);
433 if(!fieldmapper.IDL.fmclasses[linkClass].permacrud) return false;
434 if(!fieldmapper.IDL.fmclasses[linkClass].permacrud.retrieve) return false;
437 var rclassIdl = fieldmapper.IDL.fmclasses[linkClass];
439 for(var f in rclassIdl.fields) {
440 if(this.idlField.key == rclassIdl.fields[f].name) {
441 vfield = rclassIdl.fields[f];
447 throw new Error("'" + linkClass + "' has no '" + this.idlField.key + "' field!");
450 linkClass : linkClass,
455 _applyLabelFormat : function (item, formatList) {
459 // formatList[1..*] are names of fields. Pull the field
460 // values from each object to determine the values for string substitution
462 var format = formatList[0];
463 for(var i = 1; i< formatList.length; i++)
464 values.push(item[formatList[i]]);
466 return dojo.string.substitute(format, values);
470 "openils.widget.AutoFieldWidget: Invalid formatList ["+formatList+"] : "+E);
474 _buildLinkSelector : function() {
476 var selectorInfo = this._getLinkSelector();
477 if(!selectorInfo) return false;
479 var linkClass = selectorInfo.linkClass;
480 var vfield = selectorInfo.vfield;
484 if(linkClass == 'pgt')
485 return this._buildPermGrpSelector();
486 if(linkClass == 'aou')
487 return this._buildOrgSelector();
488 if(linkClass == 'acpl')
489 return this._buildCopyLocSelector();
490 if(linkClass == 'acqpro')
491 return this._buildAutoCompleteSelector(linkClass, vfield.selector);
494 dojo.require('dojo.data.ItemFileReadStore');
495 dojo.require('dijit.form.FilteringSelect');
497 this.widget = new dijit.form.FilteringSelect(this.dijitArgs, this.parentNode);
498 this.widget.searchAttr = this.widget.labelAttr = vfield.selector || vfield.name;
499 this.widget.valueAttr = vfield.name;
500 this.widget.attr('disabled', true);
502 var oncomplete = function(list) {
503 self.widget.attr('disabled', false);
506 self.widget.labelAttr = '_label';
508 if(self.searchFormat)
509 self.widget.searchAttr = '_search';
512 var storeData = {data:fieldmapper[linkClass].toStoreData(list)};
514 if(self.labelFormat) {
515 dojo.forEach(storeData.data.items,
517 item._label = self._applyLabelFormat(item, self.labelFormat);
522 if(self.searchFormat) {
523 dojo.forEach(storeData.data.items,
525 item._search = self._applyLabelFormat(item, self.searchFormat);
530 self.widget.store = new self.storeConstructor(storeData);
531 self.cache[self.auth].list[linkClass] = self.widget.store;
534 self.widget.store = self.cache[self.auth].list[linkClass];
537 self.widget.startup();
538 self._widgetLoaded();
541 if(!this.noCache && this.cache[self.auth].list[linkClass]) {
546 if(!this.dataLoader && openils.widget.AutoFieldWidget.defaultLinkedDataLoader[linkClass])
547 this.dataLoader = openils.widget.AutoFieldWidget.defaultLinkedDataLoader[linkClass];
549 if(this.dataLoader) {
551 // caller provided an external function for retrieving the data
552 this.dataLoader(linkClass, this.searchFilter, oncomplete);
556 var _cb = function(r) {
557 oncomplete(openils.Util.readResponse(r, false, true));
560 /* XXX LFW: I want to uncomment the following three lines that refer to ob, but haven't had the time to properly test. */
563 //ob[linkClass] = vfield.selector || vfield.name;
565 this.searchOptions = dojo.mixin(
567 async : !this.forceSync,
570 }, this.searchOptions
573 if (this.searchFilter) {
574 new openils.PermaCrud().search(linkClass, this.searchFilter, this.searchOptions);
576 new openils.PermaCrud().retrieveAll(linkClass, this.searchOptions);
585 * For widgets that run asynchronously, provide a callback for finishing up
587 _widgetLoaded : function(value) {
591 /* -------------------------------------------------------------
592 when using widgets in a grid, the cell may dissapear, which
593 kills the underlying DOM node, which causes this to fail.
594 For now, back out gracefully and let grid getters use
595 getDisplayString() instead
596 -------------------------------------------------------------*/
598 this.baseWidgetValue(this.getDisplayString());
603 this.baseWidgetValue(this.widgetValue);
604 if(this.idlField.name == this.fmIDL.pkey && this.fmIDL.pkey_sequence && (!this.selfReference && !this.noDisablePkey))
605 this.widget.attr('disabled', true);
606 if(this.disableWidgetTest && this.disableWidgetTest(this.idlField.name, this.fmObject))
607 this.widget.attr('disabled', true);
610 this.onload(this.widget, this);
612 if(!this.readOnly && (this.idlField.required || (this.dijitArgs && this.dijitArgs.required))) {
613 // a required dijit is not given any styling to indicate the value
614 // is invalid until the user has focused the widget then left it with
615 // invalid data. This change tells dojo to pretend this focusing has
616 // already happened so we can style required widgets during page render.
617 this.widget._hasBeenBlurred = true;
618 if(this.widget.validate)
619 this.widget.validate();
623 _buildOrgSelector : function() {
624 dojo.require('fieldmapper.OrgUtils');
625 dojo.require('openils.widget.FilteringTreeSelect');
626 this.widget = new openils.widget.FilteringTreeSelect(this.dijitArgs, this.parentNode);
627 this.widget.searchAttr = this.searchAttr || 'shortname';
628 this.widget.labelAttr = this.searchAttr || 'shortname';
629 this.widget.parentField = 'parent_ou';
630 var user = new openils.User();
632 if(this.widgetValue == null && this.orgDefaultsToWs)
633 this.widgetValue = user.user.ws_ou();
635 // if we have a limit perm, find the relevent orgs (async)
636 if(this.orgLimitPerms && this.orgLimitPerms.length > 0) {
639 user.getPermOrgList(this.orgLimitPerms,
641 self.widget.tree = orgList;
642 self.widget.startup();
643 self._widgetLoaded();
648 this.widget.tree = fieldmapper.aou.globalOrgTree;
649 this.widget.startup();
655 _buildPermGrpSelector : function() {
656 dojo.require('openils.widget.FilteringTreeSelect');
657 this.widget = new openils.widget.FilteringTreeSelect(this.dijitArgs, this.parentNode);
658 this.widget.disableQuery = this.disableQuery;
659 this.widget.searchAttr = 'name';
661 if(this.cache.permGrpTree) {
662 this.widget.tree = this.cache.permGrpTree;
663 this.widget.startup();
664 this._widgetLoaded();
670 new openils.PermaCrud().retrieveAll('pgt', {
671 async : !this.forceSync,
672 oncomplete : function(r) {
673 var list = openils.Util.readResponse(r, false, true);
678 map[list[l].id()] = list[l];
681 var pnode = map[node.parent()];
682 if(!pnode) {root = node; continue;}
683 if(!pnode.children()) pnode.children([]);
684 pnode.children().push(node);
686 self.widget.tree = self.cache.permGrpTree = root;
687 self.widget.startup();
688 self._widgetLoaded();
695 _buildCopyLocSelector : function() {
696 dojo.require('dijit.form.FilteringSelect');
697 this.widget = new dijit.form.FilteringSelect(this.dijitArgs, this.parentNode);
698 this.widget.searchAttr = this.widget.labalAttr = 'name';
699 this.widget.valueAttr = 'id';
701 if(this.cache.copyLocStore) {
702 this.widget.store = this.cache.copyLocStore;
703 this.widget.startup();
709 var ws_ou = openils.User.user.ws_ou();
710 var orgs = fieldmapper.aou.findOrgUnit(ws_ou).orgNodeTrail().map(function (i) { return i.id() });
711 orgs = orgs.concat(fieldmapper.aou.descendantNodeList(ws_ou).map(function (i) { return i.id() }));
714 new openils.PermaCrud().search('acpl', {owning_lib : orgs}, {
715 async : !this.forceSync,
716 order_by : {"acpl": "name"},
717 oncomplete : function(r) {
718 var list = openils.Util.readResponse(r, false, true);
721 new self.storeConstructor({data:fieldmapper.acpl.toStoreData(list)});
722 self.cache.copyLocStore = self.widget.store;
723 self.widget.startup();
724 self._widgetLoaded();
731 _buildAutoCompleteSelector : function(linkClass, searchAttr) {
732 dojo.require("openils.widget.PCrudAutocompleteBox");
733 dojo.mixin(this.dijitArgs, {
735 searchAttr : searchAttr,
737 this.widget = new openils.widget.PCrudAutocompleteBox(this.dijitArgs, this.parentNode);
738 this._widgetLoaded();
743 openils.widget.AutoFieldWidget.localeStrings = dojo.i18n.getLocalization("openils.widget", "AutoFieldWidget");
744 openils.widget.AutoFieldWidget.cache = {};
745 openils.widget.AutoFieldWidget.defaultLinkedDataLoader = {};