recordselect 3.1.2 → 3.1.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -404,7 +404,8 @@ RecordSelect.Dialog = RecordSelect.Abstract.extend({
404
404
  /**
405
405
  * Used by record_select_field helper
406
406
  * The options hash may contain id: and label: keys, designating the current value
407
- * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine.
407
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine
408
+ * and field_name: key, where value will be set as name of the input field.
408
409
  */
409
410
  RecordSelect.Single = RecordSelect.Abstract.extend({
410
411
  onload: function() {
@@ -418,7 +419,7 @@ RecordSelect.Single = RecordSelect.Abstract.extend({
418
419
 
419
420
  // transfer the input name from the text input to the hidden input
420
421
  this.hidden_input.attr('name', this.obj.attr('name'));
421
- this.obj.attr('name', '');
422
+ this.obj.attr('name', this.options.field_name || '');
422
423
 
423
424
  // initialize the values
424
425
  this.set(this.options.id, this.options.label);
@@ -450,6 +451,46 @@ RecordSelect.Single = RecordSelect.Abstract.extend({
450
451
  }
451
452
  });
452
453
 
454
+ /**
455
+ * Used by record_select_autocomplete helper
456
+ * The options hash may contain label: key, designating the current value
457
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine.
458
+ */
459
+ RecordSelect.Autocomplete = RecordSelect.Abstract.extend({
460
+ onload: function() {
461
+ // initialize the container
462
+ this.container = this.create_container();
463
+ this.container.addClass('record-select-autocomplete');
464
+
465
+ // initialize the values
466
+ this.set(this.options.label);
467
+
468
+ this._respond_to_text_field(this.obj);
469
+ if (this.obj.focused) this.open(); // if it was focused before we could attach observers
470
+ },
471
+
472
+ close: function() {
473
+ // if they close the dialog with the text field empty, then delete the id value
474
+ if (this.obj.val() == '') this.set('');
475
+
476
+ RecordSelect.Abstract.prototype.close.call(this);
477
+ },
478
+
479
+ onselect: function(id, value) {
480
+ this.set(value);
481
+ if (this.options.onchange) this.options.onchange.call(this, id, value);
482
+ this.close();
483
+ },
484
+
485
+ /**
486
+ * sets the id/label
487
+ */
488
+ set: function(label) {
489
+ // unescaped html missing for label
490
+ this.obj.val(label);
491
+ }
492
+ });
493
+
453
494
  /**
454
495
  * Used by record_multi_select_field helper.
455
496
  * Options:
@@ -240,7 +240,7 @@ RecordSelect.Abstract = Class.extend({
240
240
  this.container.show();
241
241
  this.container.css('left', offset.left);
242
242
  if (top + this.container.height() > $(document).height())
243
- this.container.css('bottom', offset.top);
243
+ this.container.css('top', offset.top - this.container.height());
244
244
  else this.container.css('top', top);
245
245
 
246
246
  if (this._use_iframe_mask()) {
@@ -404,7 +404,8 @@ RecordSelect.Dialog = RecordSelect.Abstract.extend({
404
404
  /**
405
405
  * Used by record_select_field helper
406
406
  * The options hash may contain id: and label: keys, designating the current value
407
- * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine.
407
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine
408
+ * and field_name: key, where value will be set as name of the input field.
408
409
  */
409
410
  RecordSelect.Single = RecordSelect.Abstract.extend({
410
411
  onload: function() {
@@ -418,7 +419,7 @@ RecordSelect.Single = RecordSelect.Abstract.extend({
418
419
 
419
420
  // transfer the input name from the text input to the hidden input
420
421
  this.hidden_input.attr('name', this.obj.attr('name'));
421
- this.obj.attr('name', '');
422
+ this.obj.attr('name', this.options.field_name || '');
422
423
 
423
424
  // initialize the values
424
425
  this.set(this.options.id, this.options.label);
@@ -450,6 +451,46 @@ RecordSelect.Single = RecordSelect.Abstract.extend({
450
451
  }
451
452
  });
452
453
 
454
+ /**
455
+ * Used by record_select_autocomplete helper
456
+ * The options hash may contain label: key, designating the current value
457
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine.
458
+ */
459
+ RecordSelect.Autocomplete = RecordSelect.Abstract.extend({
460
+ onload: function() {
461
+ // initialize the container
462
+ this.container = this.create_container();
463
+ this.container.addClass('record-select-autocomplete');
464
+
465
+ // initialize the values
466
+ this.set(this.options.label);
467
+
468
+ this._respond_to_text_field(this.obj);
469
+ if (this.obj.focused) this.open(); // if it was focused before we could attach observers
470
+ },
471
+
472
+ close: function() {
473
+ // if they close the dialog with the text field empty, then delete the id value
474
+ if (this.obj.val() == '') this.set('', '');
475
+
476
+ RecordSelect.Abstract.prototype.close.call(this);
477
+ },
478
+
479
+ onselect: function(id, value) {
480
+ this.set(value);
481
+ if (this.options.onchange) this.options.onchange.call(this, id, value);
482
+ this.close();
483
+ },
484
+
485
+ /**
486
+ * sets the id/label
487
+ */
488
+ set: function(label) {
489
+ // unescaped html missing for label
490
+ this.obj.val(label);
491
+ }
492
+ });
493
+
453
494
  /**
454
495
  * Used by record_multi_select_field helper.
455
496
  * Options:
@@ -269,7 +269,8 @@ RecordSelect.Dialog.prototype = Object.extend(new RecordSelect.Abstract(), {
269
269
  /**
270
270
  * Used by record_select_field helper
271
271
  * The options hash may contain id: and label: keys, designating the current value
272
- * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine.
272
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine
273
+ * and field_name: key, where value will be set as name of the input field.
273
274
  */
274
275
  RecordSelect.Single = Class.create();
275
276
  RecordSelect.Single.prototype = Object.extend(new RecordSelect.Abstract(), {
@@ -284,7 +285,7 @@ RecordSelect.Single.prototype = Object.extend(new RecordSelect.Abstract(), {
284
285
 
285
286
  // transfer the input name from the text input to the hidden input
286
287
  this.hidden_input.name = this.obj.name;
287
- this.obj.name = '';
288
+ this.obj.name = this.options.field_name || '';
288
289
 
289
290
  // initialize the values
290
291
  this.set(this.options.id, this.options.label);
@@ -315,6 +316,46 @@ RecordSelect.Single.prototype = Object.extend(new RecordSelect.Abstract(), {
315
316
  }
316
317
  });
317
318
 
319
+ /**
320
+ * Used by record_select_autocomplete helper
321
+ * The options hash may contain label: key, designating the current value
322
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine.
323
+ */
324
+ RecordSelect.Autocomplete = Class.create();
325
+ RecordSelect.Autocomplete.prototype = Object.extend(new RecordSelect.Abstract(), {
326
+ onload: function() {
327
+ // initialize the container
328
+ this.container = this.create_container();
329
+ this.container.addClassName('record-select-autocomplete');
330
+
331
+ // initialize the values
332
+ this.set(this.options.label);
333
+
334
+ this._respond_to_text_field(this.obj);
335
+ if (this.obj.focused) this.open(); // if it was focused before we could attach observers
336
+ },
337
+
338
+ close: function() {
339
+ // if they close the dialog with the text field empty, then delete the id value
340
+ if (this.obj.value == '') this.set('', '');
341
+
342
+ RecordSelect.Abstract.prototype.close.call(this);
343
+ },
344
+
345
+ onselect: function(id, value) {
346
+ this.set(value);
347
+ if (this.options.onchange) this.options.onchange.call(this, id, value);
348
+ this.close();
349
+ },
350
+
351
+ /**
352
+ * sets the id/label
353
+ */
354
+ set: function(label) {
355
+ this.obj.value = label.unescapeHTML();
356
+ }
357
+ });
358
+
318
359
  /**
319
360
  * Used by record_multi_select_field helper.
320
361
  * Options:
@@ -0,0 +1,411 @@
1
+ document.observe("dom:loaded", function() {
2
+ RecordSelect.document_loaded = true;
3
+ document.on('ajax:before', 'div.record-select * li.record a', function(event) {
4
+ var link = event.findElement();
5
+ if (link) {
6
+ if (RecordSelect.notify(link) == false) {
7
+ event.stop();
8
+ } else {
9
+ link.toggleClassName("selected");
10
+ }
11
+ }
12
+ return true;
13
+ });
14
+ });
15
+
16
+ Form.Element.AfterActivity = function(element, callback, delay) {
17
+ element = $(element);
18
+ if (!delay) delay = 0.25;
19
+ new Form.Element.Observer(element, delay, function(element, value) {
20
+ // TODO: display loading indicator
21
+ if (element.activity_timer) clearTimeout(element.activity_timer);
22
+ element.activity_timer = setTimeout(function() {
23
+ callback(element.value);
24
+ }, delay * 1000 + 50);
25
+ });
26
+ }
27
+
28
+ var RecordSelect = new Object();
29
+ RecordSelect.document_loaded = false;
30
+
31
+ RecordSelect.notify = function(item) {
32
+ var e = Element.up(item, '.record-select-handler');
33
+ var onselect = e.onselect || e.getAttribute('onselect');
34
+ if (typeof onselect != 'function') onselect = eval(onselect);
35
+ if (onselect)
36
+ {
37
+ try {
38
+ onselect(item.parentNode.id.substr(2), (item.down('label') || item).innerHTML.unescapeHTML(), e);
39
+ } catch(e) {
40
+ alert(e);
41
+ }
42
+ return false;
43
+ }
44
+ else return true;
45
+ };
46
+
47
+ RecordSelect.render_page = function(record_select_id, page) {
48
+ var page_element = $$('#' + record_select_id + ' ol')[0];
49
+ if (page_element) Element.replace(page_element, page);
50
+ };
51
+
52
+ RecordSelect.Abstract = Class.create();
53
+ Object.extend(RecordSelect.Abstract.prototype, {
54
+ /**
55
+ * obj - the id or element that will anchor the recordselect to the page
56
+ * url - the url to run the recordselect
57
+ * options - ??? (check concrete classes)
58
+ */
59
+ initialize: function(obj, url, options) {
60
+ this.obj = $(obj);
61
+ this.url = url;
62
+ this.options = options;
63
+ this.container;
64
+
65
+ if (RecordSelect.document_loaded) this.onload();
66
+ else Event.observe(window, 'load', this.onload.bind(this));
67
+ },
68
+
69
+ /**
70
+ * Finish the setup - IE doesn't like doing certain things before the page loads
71
+ * --override--
72
+ */
73
+ onload: function() {},
74
+
75
+ /**
76
+ * the onselect event handler - when someone clicks on a record
77
+ * --override--
78
+ */
79
+ onselect: function(id, value) {
80
+ alert(id + ': ' + value);
81
+ },
82
+
83
+ /**
84
+ * opens the recordselect
85
+ */
86
+ open: function() {
87
+ if (this.is_open()) return;
88
+
89
+ new Ajax.Updater(this.container, this.url, {
90
+ method: 'get',
91
+ evalScripts: true,
92
+ asynchronous: true,
93
+ onComplete: function() {
94
+ this.show();
95
+ // needs to be mousedown so the event doesn't get canceled by other code (see issue #26)
96
+ Element.observe(document.body, 'mousedown', this.onbodyclick.bindAsEventListener(this));
97
+ }.bind(this)
98
+ });
99
+ },
100
+
101
+ /**
102
+ * positions and reveals the recordselect
103
+ */
104
+ show: function() {
105
+ var offset = Position.cumulativeOffset(this.obj);
106
+ this.container.style.left = offset[0] + 'px';
107
+ this.container.style.top = (Element.getHeight(this.obj) + offset[1]) + 'px';
108
+
109
+ if (this._use_iframe_mask()) {
110
+ this.container.insertAdjacentHTML('afterEnd', '<iframe src="javascript:false;" class="record-select-mask" />');
111
+ var mask = this.container.next('iframe');
112
+ mask.style.left = this.container.style.left;
113
+ mask.style.top = this.container.style.top;
114
+ }
115
+
116
+ this.container.show();
117
+
118
+ if (this._use_iframe_mask()) {
119
+ var dimensions = this.container.immediateDescendants().first().getDimensions();
120
+ mask.style.width = dimensions.width + 'px';
121
+ mask.style.height = dimensions.height + 'px';
122
+ }
123
+ },
124
+
125
+ /**
126
+ * closes the recordselect by emptying the container
127
+ */
128
+ close: function() {
129
+ if (this._use_iframe_mask()) {
130
+ this.container.next('iframe').remove();
131
+ }
132
+
133
+ this.container.hide();
134
+ // hopefully by using remove() instead of innerHTML we won't leak memory
135
+ this.container.immediateDescendants().invoke('remove');
136
+ },
137
+
138
+ /**
139
+ * returns true/false for whether the recordselect is open
140
+ */
141
+ is_open: function() {
142
+ return (!this.container.innerHTML.blank())
143
+ },
144
+
145
+ /**
146
+ * when the user clicks outside the dropdown
147
+ */
148
+ onbodyclick: function(ev) {
149
+ if (!this.is_open()) return;
150
+ var elem = $(Event.element(ev));
151
+ var ancestors = elem.ancestors();
152
+ ancestors.push(elem);
153
+ if (ancestors.include(this.container) || ancestors.include(this.obj)) return;
154
+ this.close();
155
+ },
156
+
157
+ /**
158
+ * creates and initializes (and returns) the recordselect container
159
+ */
160
+ create_container: function() {
161
+ new Insertion.Bottom(document.body, '<div class="record-select-container record-select-handler"></div>');
162
+ e = document.body.childNodes[document.body.childNodes.length - 1];
163
+ e.onselect = this.onselect.bind(this);
164
+ e.style.display = 'none';
165
+
166
+ return $(e);
167
+ },
168
+
169
+ /**
170
+ * all the behavior to respond to a text field as a search box
171
+ */
172
+ _respond_to_text_field: function(text_field) {
173
+ // attach the events to start this party
174
+ text_field.observe('focus', this.open.bind(this));
175
+
176
+ // the autosearch event - needs to happen slightly late (keyup is later than keypress)
177
+ text_field.observe('keyup', function() {
178
+ if (!this.is_open()) return;
179
+ this.container.down('.text-input').value = text_field.value;
180
+ }.bind(this));
181
+
182
+ // keyboard navigation, if available
183
+ if (this.onkeypress) {
184
+ text_field.observe('keypress', this.onkeypress.bind(this));
185
+ }
186
+ },
187
+
188
+ _use_iframe_mask: function() {
189
+ return this.container.insertAdjacentHTML ? true : false;
190
+ }
191
+ });
192
+
193
+ /**
194
+ * Adds keyboard navigation to RecordSelect objects
195
+ */
196
+ Object.extend(RecordSelect.Abstract.prototype, {
197
+ current: null,
198
+
199
+ /**
200
+ * keyboard navigation - where to intercept the keys is up to the concrete class
201
+ */
202
+ onkeypress: function(ev) {
203
+ var elem;
204
+ switch (ev.keyCode) {
205
+ case Event.KEY_UP:
206
+ if (this.current && this.current.up('.record-select')) elem = this.current.previous();
207
+ if (!elem) elem = this.container.getElementsBySelector('ol li.record').last();
208
+ this.highlight(elem);
209
+ break;
210
+ case Event.KEY_DOWN:
211
+ if (this.current && this.current.up('.record-select')) elem = this.current.next();
212
+ if (!elem) elem = this.container.getElementsBySelector('ol li.record').first();
213
+ this.highlight(elem);
214
+ break;
215
+ case Event.KEY_SPACE:
216
+ case Event.KEY_RETURN:
217
+ if (this.current) this.current.down('a').onclick();
218
+ break;
219
+ case Event.KEY_RIGHT:
220
+ elem = this.container.down('li.pagination.next');
221
+ if (elem) elem.down('a').onclick();
222
+ break;
223
+ case Event.KEY_LEFT:
224
+ elem = this.container.down('li.pagination.previous');
225
+ if (elem) elem.down('a').onclick();
226
+ break;
227
+ case Event.KEY_ESC:
228
+ this.close();
229
+ break;
230
+ default:
231
+ return;
232
+ }
233
+ Event.stop(ev); // so "enter" doesn't submit the form, among other things(?)
234
+ },
235
+
236
+ /**
237
+ * moves the highlight to a new object
238
+ */
239
+ highlight: function(obj) {
240
+ if (this.current) this.current.removeClassName('current');
241
+ this.current = $(obj);
242
+ obj.addClassName('current');
243
+ }
244
+ });
245
+
246
+ /**
247
+ * Used by link_to_record_select
248
+ * The options hash should contain a onselect: key, with a javascript function as value
249
+ */
250
+ RecordSelect.Dialog = Class.create();
251
+ RecordSelect.Dialog.prototype = Object.extend(new RecordSelect.Abstract(), {
252
+ onload: function() {
253
+ this.container = this.create_container();
254
+ this.obj.observe('click', this.toggle.bind(this));
255
+
256
+ if (this.onkeypress) this.obj.observe('keypress', this.onkeypress.bind(this));
257
+ },
258
+
259
+ onselect: function(id, value) {
260
+ if (this.options.onselect(id, value) != false) this.close();
261
+ },
262
+
263
+ toggle: function() {
264
+ if (this.is_open()) this.close();
265
+ else this.open();
266
+ }
267
+ });
268
+
269
+ /**
270
+ * Used by record_select_field helper
271
+ * The options hash may contain id: and label: keys, designating the current value
272
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine
273
+ * and field_name: key, where value will be set as name of the input field.
274
+ */
275
+ RecordSelect.Single = Class.create();
276
+ RecordSelect.Single.prototype = Object.extend(new RecordSelect.Abstract(), {
277
+ onload: function() {
278
+ // initialize the container
279
+ this.container = this.create_container();
280
+ this.container.addClassName('record-select-autocomplete');
281
+
282
+ // create the hidden input
283
+ new Insertion.After(this.obj, '<input type="hidden" name="" value="" />')
284
+ this.hidden_input = this.obj.next();
285
+
286
+ // transfer the input name from the text input to the hidden input
287
+ this.hidden_input.name = this.obj.name;
288
+ this.obj.name = this.options.field_name || '';
289
+
290
+ // initialize the values
291
+ this.set(this.options.id, this.options.label);
292
+
293
+ this._respond_to_text_field(this.obj);
294
+ if (this.obj.focused) this.open(); // if it was focused before we could attach observers
295
+ },
296
+
297
+ close: function() {
298
+ // if they close the dialog with the text field empty, then delete the id value
299
+ if (this.obj.value == '') this.set('', '');
300
+
301
+ RecordSelect.Abstract.prototype.close.call(this);
302
+ },
303
+
304
+ onselect: function(id, value) {
305
+ this.set(id, value);
306
+ if (this.options.onchange) this.options.onchange.call(this, id, value);
307
+ this.close();
308
+ },
309
+
310
+ /**
311
+ * sets the id/label
312
+ */
313
+ set: function(id, label) {
314
+ this.obj.value = label.unescapeHTML();
315
+ this.hidden_input.value = id;
316
+ }
317
+ });
318
+
319
+ /**
320
+ * Used by record_select_autocomplete helper
321
+ * The options hash may contain label: key, designating the current value
322
+ * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine.
323
+ */
324
+ RecordSelect.Autocomplete = Class.create();
325
+ RecordSelect.Autocomplete.prototype = Object.extend(new RecordSelect.Abstract(), {
326
+ onload: function() {
327
+ // initialize the container
328
+ this.container = this.create_container();
329
+ this.container.addClassName('record-select-autocomplete');
330
+
331
+ // initialize the values
332
+ this.set(this.options.label);
333
+
334
+ this._respond_to_text_field(this.obj);
335
+ if (this.obj.focused) this.open(); // if it was focused before we could attach observers
336
+ },
337
+
338
+ close: function() {
339
+ // if they close the dialog with the text field empty, then delete the id value
340
+ if (this.obj.value == '') this.set('', '');
341
+
342
+ RecordSelect.Abstract.prototype.close.call(this);
343
+ },
344
+
345
+ onselect: function(id, value) {
346
+ this.set(id, value);
347
+ if (this.options.onchange) this.options.onchange.call(this, id, value);
348
+ this.close();
349
+ },
350
+
351
+ /**
352
+ * sets the id/label
353
+ */
354
+ set: function(id, label) {
355
+ this.obj.value = label.unescapeHTML();
356
+ this.hidden_input.value = id;
357
+ }
358
+ });
359
+
360
+ /**
361
+ * Used by record_multi_select_field helper.
362
+ * Options:
363
+ * list - the id (or object) of the <ul> to contain the <li>s of selected entries
364
+ * current - an array of id:/label: keys designating the currently selected entries
365
+ */
366
+ RecordSelect.Multiple = Class.create();
367
+ RecordSelect.Multiple.prototype = Object.extend(new RecordSelect.Abstract(), {
368
+ onload: function() {
369
+ // initialize the container
370
+ this.container = this.create_container();
371
+ this.container.addClassName('record-select-autocomplete');
372
+
373
+ // decide where the <li> entries should be placed
374
+ if (this.options.list) this.list_container = $(this.options.list);
375
+ else this.list_container = this.obj.next('ul');
376
+
377
+ // take the input name from the text input, and store it for this.add()
378
+ this.input_name = this.obj.name;
379
+ this.obj.name = '';
380
+
381
+ // initialize the list
382
+ $A(this.options.current).each(function(c) {
383
+ this.add(c.id, c.label);
384
+ }.bind(this));
385
+
386
+ this._respond_to_text_field(this.obj);
387
+ if (this.obj.focused) this.open(); // if it was focused before we could attach observers
388
+ },
389
+
390
+ onselect: function(id, value) {
391
+ this.add(id, value);
392
+ },
393
+
394
+ /**
395
+ * Adds a record to the selected list
396
+ */
397
+ add: function(id, label) {
398
+ // return silently if this value has already been selected
399
+ var already_selected = this.list_container.getElementsBySelector('input').any(function(i) {
400
+ return i.value == id
401
+ });
402
+ if (already_selected) return;
403
+
404
+ var entry = '<li>'
405
+ + '<a href="#" onclick="$(this.parentNode).remove(); return false;" class="remove">remove</a>'
406
+ + '<input type="hidden" name="' + this.input_name + '" value="' + id + '" />'
407
+ + '<label>' + label + '</label>'
408
+ + '</li>';
409
+ new Insertion.Top(this.list_container, entry);
410
+ }
411
+ });
@@ -29,24 +29,58 @@ module RecordSelectHelper
29
29
  # +controller+:: The controller configured to provide the result set. Optional if you have standard resource controllers (e.g. UsersController for the User model), in which case the controller will be inferred from the class of +current+ (the second argument)
30
30
  # +params+:: A hash of extra URL parameters
31
31
  # +id+:: The id to use for the input. Defaults based on the input's name.
32
+ # +field_name+:: The name to use for the text input. Defaults to '', so field is not submitted.
32
33
  # +onchange+:: A JavaScript function that will be called whenever something new is selected. It should accept the new id as the first argument, and the new label as the second argument. For example, you could set onchange to be "function(id, label) {alert(id);}", or you could create a JavaScript function somewhere else and set onchange to be "my_function" (without the parantheses!).
33
34
  def record_select_field(name, current, options = {})
34
35
  options[:controller] ||= current.class.to_s.pluralize.underscore
35
36
  options[:params] ||= {}
36
37
  options[:id] ||= name.gsub(/[\[\]]/, '_')
37
38
 
39
+ id = options.delete(:id)
40
+ html = text_field_tag(name, nil, :autocomplete => 'off', :id => id, :class => options.delete(:class), :onfocus => "this.focused=true", :onblur => "this.focused=false")
41
+
38
42
  controller = assert_controller_responds(options[:controller])
39
43
 
40
- id = label = ''
44
+ options[:id] = options[:label] = ''
41
45
  if current and not current.new_record?
42
- id = current.id
43
- label = label_for_field(current, controller)
46
+ options[:id] = current.id
47
+ options[:label] = label_for_field(current, controller)
44
48
  end
45
49
 
46
- url = url_for({:action => :browse, :controller => options[:controller], :escape => false}.merge(options[:params]))
50
+ url = url_for({:action => :browse, :controller => options.delete(:controller), :escape => false}.merge(options.delete(:params)))
51
+ html << javascript_tag("new RecordSelect.Single(#{id.to_json}, #{url.to_json}, #{options.to_json});")
52
+
53
+ return html
54
+ end
55
+
56
+ # Adds a RecordSelect-based form field. The field is autocompleted.
57
+ #
58
+ # *Arguments*
59
+ # +name+:: the input name that will be used to submit the selected value.
60
+ # +current+:: the current object. provide a new record if there're none currently selected and you have not passed the optional :controller argument.
61
+ #
62
+ # *Options*
63
+ # +controller+:: The controller configured to provide the result set. Optional if you have standard resource controllers (e.g. UsersController for the User model), in which case the controller will be inferred from the class of +current+ (the second argument)
64
+ # +params+:: A hash of extra URL parameters
65
+ # +id+:: The id to use for the input. Defaults based on the input's name.
66
+ # +onchange+:: A JavaScript function that will be called whenever something new is selected. It should accept the new id as the first argument, and the new label as the second argument. For example, you could set onchange to be "function(id, label) {alert(id);}", or you could create a JavaScript function somewhere else and set onchange to be "my_function" (without the parantheses!).
67
+ def record_select_autocomplete(name, current, options = {})
68
+ options[:controller] ||= current.class.to_s.pluralize.underscore
69
+ options[:params] ||= {}
70
+ options[:id] ||= name.gsub(/[\[\]]/, '_')
71
+
72
+ id = options.delete(:id)
73
+ html = text_field_tag(name, nil, :autocomplete => 'off', :id => id, :class => options.delete(:class), :onfocus => "this.focused=true", :onblur => "this.focused=false")
74
+
75
+ controller = assert_controller_responds(options[:controller])
76
+
77
+ options[:label] = ''
78
+ if current and not current.new_record?
79
+ options[:label] = label_for_field(current, controller)
80
+ end
47
81
 
48
- html = text_field_tag(name, nil, :autocomplete => 'off', :id => options[:id], :class => options[:class], :onfocus => "this.focused=true", :onblur => "this.focused=false")
49
- html << javascript_tag("new RecordSelect.Single(#{options[:id].to_json}, #{url.to_json}, {id: #{id.to_json}, label: #{label.to_json}, onchange: #{options[:onchange] || ''.to_json}});")
82
+ url = url_for({:action => :browse, :controller => options.delete(:controller), :escape => false}.merge(options.delete(:params)))
83
+ html << javascript_tag("new RecordSelect.Autocomplete(#{id.to_json}, #{url.to_json}, #{options.to_json});")
50
84
 
51
85
  return html
52
86
  end
@@ -0,0 +1,209 @@
1
+ module RecordSelectHelper
2
+ # Adds a link on the page that toggles a RecordSelect widget from the given controller.
3
+ #
4
+ # *Options*
5
+ # +onselect+:: JavaScript code to handle selections client-side. This code has access to two variables: id, label. If the code returns false, the dialog will *not* close automatically.
6
+ # +params+:: Extra URL parameters. If any parameter is a column name, the parameter will be used as a search term to filter the result set.
7
+ def link_to_record_select(name, controller, options = {})
8
+ options[:params] ||= {}
9
+ options[:params].merge!(:controller => controller, :action => :browse)
10
+ options[:onselect] = "function(id, label) {#{options[:onselect]}}" if options[:onselect]
11
+ options[:html] ||= {}
12
+ options[:html][:id] ||= "rs_#{rand(9999)}"
13
+
14
+ assert_controller_responds(options[:params][:controller])
15
+
16
+ html = link_to_function(name, '', options[:html])
17
+ html << javascript_tag("new RecordSelect.Dialog(#{options[:html][:id].to_json}, #{url_for(options[:params].merge(:escape => false)).to_json}, {onselect: #{options[:onselect] || ''}})")
18
+
19
+ return html
20
+ end
21
+
22
+ # Adds a RecordSelect-based form field. The field submits the record's id using a hidden input.
23
+ #
24
+ # *Arguments*
25
+ # +name+:: the input name that will be used to submit the selected record's id.
26
+ # +current+:: the currently selected object. provide a new record if there're none currently selected and you have not passed the optional :controller argument.
27
+ #
28
+ # *Options*
29
+ # +controller+:: The controller configured to provide the result set. Optional if you have standard resource controllers (e.g. UsersController for the User model), in which case the controller will be inferred from the class of +current+ (the second argument)
30
+ # +params+:: A hash of extra URL parameters
31
+ # +id+:: The id to use for the input. Defaults based on the input's name.
32
+ # +field_name+:: The name to use for the text input. Defaults to '', so field is not submitted.
33
+ # +onchange+:: A JavaScript function that will be called whenever something new is selected. It should accept the new id as the first argument, and the new label as the second argument. For example, you could set onchange to be "function(id, label) {alert(id);}", or you could create a JavaScript function somewhere else and set onchange to be "my_function" (without the parantheses!).
34
+ def record_select_field(name, current, options = {})
35
+ options[:controller] ||= current.class.to_s.pluralize.underscore
36
+ options[:params] ||= {}
37
+ options[:id] ||= name.gsub(/[\[\]]/, '_')
38
+
39
+ id = options.delete(:id)
40
+ html = text_field_tag(name, nil, :autocomplete => 'off', :id => id, :class => options.delete(:class), :onfocus => "this.focused=true", :onblur => "this.focused=false")
41
+
42
+ controller = assert_controller_responds(options[:controller])
43
+
44
+ options[:id] = options[:label] = ''
45
+ if current and not current.new_record?
46
+ options[:id] = current.id
47
+ options[:label] = label_for_field(current, controller)
48
+ end
49
+
50
+ url = url_for({:action => :browse, :controller => options.delete(:controller), :escape => false}.merge(options.delete(:params)))
51
+ html << javascript_tag("new RecordSelect.Single(#{id.to_json}, #{url.to_json}, #{options.to_json});")
52
+
53
+ return html
54
+ end
55
+
56
+ # Adds a RecordSelect-based form field. The field is autocompleted.
57
+ #
58
+ # *Arguments*
59
+ # +name+:: the input name that will be used to submit the selected value.
60
+ # +current+:: the current object. provide a new record if there're none currently selected and you have not passed the optional :controller argument.
61
+ #
62
+ # *Options*
63
+ # +controller+:: The controller configured to provide the result set. Optional if you have standard resource controllers (e.g. UsersController for the User model), in which case the controller will be inferred from the class of +current+ (the second argument)
64
+ # +params+:: A hash of extra URL parameters
65
+ # +id+:: The id to use for the input. Defaults based on the input's name.
66
+ # +onchange+:: A JavaScript function that will be called whenever something new is selected. It should accept the new id as the first argument, and the new label as the second argument. For example, you could set onchange to be "function(id, label) {alert(id);}", or you could create a JavaScript function somewhere else and set onchange to be "my_function" (without the parantheses!).
67
+ def record_select_autocomplete(name, current, options = {})
68
+ options[:controller] ||= current.class.to_s.pluralize.underscore
69
+ options[:params] ||= {}
70
+ options[:id] ||= name.gsub(/[\[\]]/, '_')
71
+
72
+ html = text_field_tag(name, nil, :autocomplete => 'off', :id => options.delete(:id), :class => options.delete(:class), :onfocus => "this.focused=true", :onblur => "this.focused=false")
73
+
74
+ controller = assert_controller_responds(options[:controller])
75
+
76
+ options[:label] = ''
77
+ if current and not current.new_record?
78
+ options[:label] = label_for_field(current, controller)
79
+ end
80
+
81
+ url = url_for({:action => :browse, :controller => options.delete(:controller), :escape => false}.merge(options.delete(:params)))
82
+ html << javascript_tag("new RecordSelect.Autocomplete(#{options[:id].to_json}, #{url.to_json}, #{options.to_json});")
83
+
84
+ return html
85
+ end
86
+
87
+ # Assists with the creation of an observer for the :onchange option of the record_select_field method.
88
+ # Currently only supports building an Ajax.Request based on the id of the selected record.
89
+ #
90
+ # options[:url] should be a hash with all the necessary options *except* :id. that parameter
91
+ # will be provided based on the selected record.
92
+ #
93
+ # Question: if selecting users, what's more likely?
94
+ # /users/5/categories
95
+ # /categories?user_id=5
96
+ def record_select_observer(options = {})
97
+ fn = ""
98
+ fn << "function(id, value) {"
99
+ fn << "var url = #{url_for(options[:url].merge(:id => ":id:")).to_json}.replace(/:id:/, id);"
100
+ fn << "new Ajax.Request(url);"
101
+ fn << "}"
102
+ end
103
+
104
+ # Adds a RecordSelect-based form field for multiple selections. The values submit using a list of hidden inputs.
105
+ #
106
+ # *Arguments*
107
+ # +name+:: the input name that will be used to submit the selected records' ids. empty brackets will be appended to the name.
108
+ # +current+:: pass a collection of existing associated records
109
+ #
110
+ # *Options*
111
+ # +controller+:: The controller configured to provide the result set.
112
+ # +params+:: A hash of extra URL parameters
113
+ # +id+:: The id to use for the input. Defaults based on the input's name.
114
+ def record_multi_select_field(name, current, options = {})
115
+ options[:controller] ||= current.first.class.to_s.pluralize.underscore
116
+ options[:params] ||= {}
117
+ options[:id] ||= name.gsub(/[\[\]]/, '_')
118
+
119
+ controller = assert_controller_responds(options[:controller])
120
+
121
+ # js identifier so we can talk to it.
122
+ widget = "rs_%s" % name.gsub(/[\[\]]/, '_').chomp('_')
123
+
124
+ current = current.inject([]) { |memo, record| memo.push({:id => record.id, :label => label_for_field(record, controller)}) }
125
+
126
+ url = url_for({:action => :browse, :controller => options[:controller], :escape => false}.merge(options[:params]))
127
+
128
+ html = text_field_tag("#{name}[]", nil, :autocomplete => 'off', :id => options[:id], :class => options[:class], :onfocus => "this.focused=true", :onblur => "this.focused=false")
129
+ html << content_tag('ul', '', :class => 'record-select-list');
130
+ html << javascript_tag("#{widget} = new RecordSelect.Multiple(#{options[:id].to_json}, #{url.to_json}, {current: #{current.to_json}});")
131
+
132
+ return html
133
+ end
134
+
135
+ # A helper to render RecordSelect partials
136
+ def render_record_select(options = {}) #:nodoc:
137
+ controller.send(:render_record_select, options) do |options|
138
+ render options
139
+ end
140
+ end
141
+
142
+ # Provides view access to the RecordSelect configuration
143
+ def record_select_config #:nodoc:
144
+ controller.send :record_select_config
145
+ end
146
+
147
+ # The id of the RecordSelect widget for the given controller.
148
+ def record_select_id(controller = nil) #:nodoc:
149
+ controller ||= params[:controller]
150
+ "record-select-#{controller.gsub('/', '_')}"
151
+ end
152
+
153
+ def record_select_search_id(controller = nil) #:nodoc:
154
+ "#{record_select_id(controller)}-search"
155
+ end
156
+
157
+ private
158
+ # render the record using the renderer and add a link to select the record
159
+ def render_record_in_list(record, controller_path)
160
+ text = render_record_from_config(record)
161
+ if record_select_config.link?
162
+ url_options = {:controller => controller_path, :action => :select, :id => record.id, :escape => false}
163
+ link_to text, url_options, :method => :post, :remote => true, :class => ''
164
+ else
165
+ text
166
+ end
167
+ end
168
+
169
+
170
+ # uses renderer (defaults to record_select_config.label) to determine how the given record renders.
171
+ def render_record_from_config(record, renderer = record_select_config.label)
172
+ case renderer
173
+ when Symbol, String
174
+ # return full-html from the named partial
175
+ render :partial => renderer.to_s, :locals => {:record => record}
176
+
177
+ when Proc
178
+ # return an html-cleaned descriptive string
179
+ h renderer.call(record)
180
+ end
181
+ end
182
+
183
+ # uses the result of render_record_from_config to snag an appropriate record label
184
+ # to display in a field.
185
+ #
186
+ # if given a controller, searches for a partial in its views path
187
+ def label_for_field(record, controller = self.controller)
188
+ renderer = controller.record_select_config.label
189
+ case renderer
190
+ when Symbol, String
191
+ # find the <label> element and grab its innerHTML
192
+ description = render_record_from_config(record, File.join(controller.controller_path, renderer.to_s))
193
+ description.match(/<label[^>]*>(.*)<\/label>/)[1]
194
+
195
+ when Proc
196
+ # just return the string
197
+ render_record_from_config(record, renderer)
198
+ end
199
+ end
200
+
201
+ def assert_controller_responds(controller_name)
202
+ controller_name = "#{controller_name.camelize}Controller"
203
+ controller = controller_name.constantize
204
+ unless controller.uses_record_select?
205
+ raise "#{controller_name} has not been configured to use RecordSelect."
206
+ end
207
+ controller
208
+ end
209
+ end
@@ -2,7 +2,7 @@ module RecordSelect
2
2
  module Version
3
3
  MAJOR = 3
4
4
  MINOR = 1
5
- PATCH = 2
5
+ PATCH = 3
6
6
 
7
7
  STRING = [MAJOR, MINOR, PATCH].compact.join('.')
8
8
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: recordselect
3
3
  version: !ruby/object:Gem::Version
4
- hash: 7
4
+ hash: 5
5
5
  prerelease:
6
6
  segments:
7
7
  - 3
8
8
  - 1
9
- - 2
10
- version: 3.1.2
9
+ - 3
10
+ version: 3.1.3
11
11
  platform: ruby
12
12
  authors:
13
13
  - Sergio Cambra
@@ -17,7 +17,7 @@ autorequire:
17
17
  bindir: bin
18
18
  cert_chain: []
19
19
 
20
- date: 2011-10-21 00:00:00 Z
20
+ date: 2011-11-09 00:00:00 Z
21
21
  dependencies:
22
22
  - !ruby/object:Gem::Dependency
23
23
  requirement: &id001 !ruby/object:Gem::Requirement
@@ -98,6 +98,7 @@ files:
98
98
  - app/assets/javascripts/jquery/record_select.js
99
99
  - app/assets/javascripts/jquery/record_select.js~
100
100
  - app/assets/javascripts/prototype/record_select.js
101
+ - app/assets/javascripts/prototype/record_select.js~
101
102
  - app/assets/javascripts/record_select.js.erb
102
103
  - app/assets/stylesheets/record_select.css.erb
103
104
  - lib/record_select.rb
@@ -110,6 +111,7 @@ files:
110
111
  - lib/record_select/extensions/localization.rb
111
112
  - lib/record_select/extensions/routing_mapper.rb
112
113
  - lib/record_select/helpers/record_select_helper.rb
114
+ - lib/record_select/helpers/record_select_helper.rb~
113
115
  - lib/record_select/version.rb
114
116
  - lib/record_select/engine.rb
115
117
  - MIT-LICENSE