CRM-13783 - ProfileBuilder - Auto-add new custom field to canvas
[civicrm-core.git] / js / view / crm.designer.js
CommitLineData
6a488035
TO
1(function($) {
2 if (!CRM.Designer) CRM.Designer = {};
3
4 /**
5 * When rendering a template with Marionette.ItemView, the list of variables is determined by
6 * serializeData(). The normal behavior is to map each property of this.model to a template
7 * variable.
8 *
9 * This function extends that practice by exporting variables "_view", "_model", "_collection",
10 * and "_options". This makes it easier for the template to, e.g., access computed properties of
11 * a model (by calling "_model.getComputedProperty"), or to access constructor options (by
12 * calling "_options.myoption").
13 *
14 * @return {*}
15 */
16 var extendedSerializeData = function() {
17 var result = Marionette.ItemView.prototype.serializeData.apply(this);
18 result._view = this;
19 result._model = this.model;
20 result._collection = this.collection;
21 result._options = this.options;
22 return result;
abc8b55b 23 };
6a488035
TO
24
25 /**
26 * Display a dialog window with an editable form for a UFGroupModel
27 *
28 * The implementation here is very "jQuery-style" and not "Backbone-style";
29 * it's been extracted
30 *
31 * options:
32 * - model: CRM.UF.UFGroupModel
33 */
34 CRM.Designer.DesignerDialog = Backbone.Marionette.Layout.extend({
35 serializeData: extendedSerializeData,
36 template: '#designer_dialog_template',
37 className: 'crm-designer-dialog',
38 regions: {
39 designerRegion: '.crm-designer'
40 },
41 /** @var bool whether this dialog is currently open */
42 isDialogOpen: false,
43 /** @var bool whether any changes have been made */
44 isUfUnsaved: false,
45 /** @var obj handle for the CRM.alert containing undo link */
46 undoAlert: null,
47 /** @var bool whether this dialog is being re-opened by the undo link */
48 undoState: false,
49
50 initialize: function(options) {
51 CRM.designerApp.vent.on('ufUnsaved', this.onUfChanged, this);
52 },
53 onClose: function() {
54 this.undoAlert && this.undoAlert.close && this.undoAlert.close();
55 CRM.designerApp.vent.off('ufUnsaved', this.onUfChanged, this);
56 },
57 onUfChanged: function(isUfUnsaved) {
58 this.isUfUnsaved = isUfUnsaved;
59 },
60 onRender: function() {
61 var designerDialog = this;
62 designerDialog.$el.dialog({
63 autoOpen: true, // note: affects accordion height
64 title: 'Edit Profile',
65 width: '75%',
66 height: 600,
67 minWidth: 500,
68 minHeight: 600, // to allow dropping in big whitespace, coordinate with min-height of .crm-designer-fields
69 open: function() {
70 // Prevent conflicts with other onbeforeunload handlers
71 designerDialog.oldOnBeforeUnload = window.onbeforeunload;
72 // Warn of unsaved changes when navigating away from the page
73 window.onbeforeunload = function() {
74 if (designerDialog.isDialogOpen && designerDialog.isUfUnsaved) {
75 return ts("Your profile has not been saved.");
76 }
77 if (designerDialog.oldOnBeforeUnload) {
78 return designerDialog.oldOnBeforeUnload.apply(arguments);
79 }
80 };
81 designerDialog.undoAlert && designerDialog.undoAlert.close && designerDialog.undoAlert.close();
82 designerDialog.isDialogOpen = true;
83 // Initialize new dialog if we are not re-opening unsaved changes
84 if (designerDialog.undoState === false) {
85 designerDialog.designerRegion && designerDialog.designerRegion.close && designerDialog.designerRegion.close();
86 designerDialog.$el.block({message: 'Loading...', theme: true});
87 designerDialog.options.findCreateUfGroupModel({
88 onLoad: function(ufGroupModel) {
89 designerDialog.model = ufGroupModel;
90 var designerLayout = new CRM.Designer.DesignerLayout({
91 model: ufGroupModel,
92 el: '<div class="full-height"></div>'
93 });
94 designerDialog.$el.unblock();
95 designerDialog.designerRegion.show(designerLayout);
96 CRM.designerApp.vent.trigger('resize');
97 designerDialog.isUfUnsaved = false;
98 }
99 });
100 }
101 designerDialog.undoState = false;
4151fff2
CW
102 // CRM-12188
103 CRM.designerApp.DetachedProfiles = [];
6a488035
TO
104 },
105 close: function() {
106 window.onbeforeunload = designerDialog.oldOnBeforeUnload;
107 designerDialog.isDialogOpen = false;
108
109 designerDialog.undoAlert && designerDialog.undoAlert.close && designerDialog.undoAlert.close();
110 if (designerDialog.isUfUnsaved) {
111 designerDialog.undoAlert = CRM.alert('<p>' + ts('Your changes to "%1" have not been saved.', {1: designerDialog.model.get('title')}) + '</p><a href="#" class="crm-undo">' + ts('Restore unsaved changes') + '</a>', ts('Unsaved Changes'), 'alert', {expires: 60000});
112 $('.ui-notify-message a.crm-undo').click(function() {
113 designerDialog.undoState = true;
114 designerDialog.$el.dialog('open');
115 return false;
116 });
117 }
4151fff2
CW
118 // CRM-12188
119 CRM.designerApp.restorePreviewArea();
6a488035
TO
120 },
121 resize: function() {
122 CRM.designerApp.vent.trigger('resize');
123 }
124 });
125 }
126 });
127
128 /**
129 * Display a complete form-editing UI, including canvas, palette, and
130 * buttons.
131 *
132 * options:
133 * - model: CRM.UF.UFGroupModel
134 */
135 CRM.Designer.DesignerLayout = Backbone.Marionette.Layout.extend({
136 serializeData: extendedSerializeData,
137 template: '#designer_template',
138 regions: {
139 buttons: '.crm-designer-buttonset-region',
140 palette: '.crm-designer-palette-region',
141 form: '.crm-designer-form-region',
142 fields: '.crm-designer-fields-region'
143 },
144 initialize: function() {
145 CRM.designerApp.vent.on('resize', this.onResize, this);
146 },
147 onClose: function() {
148 CRM.designerApp.vent.off('resize', this.onResize, this);
149 },
150 onRender: function() {
151 this.buttons.show(new CRM.Designer.ToolbarView({
152 model: this.model
153 }));
154 this.palette.show(new CRM.Designer.PaletteView({
155 model: this.model
156 }));
157 this.form.show(new CRM.Designer.UFGroupView({
158 model: this.model
159 }));
160 this.fields.show(new CRM.Designer.UFFieldCanvasView({
161 model: this.model
162 }));
163 },
164 onResize: function() {
165 if (! this.hasResizedBefore) {
166 this.hasResizedBefore = true;
167 this.$('.crm-designer-toolbar').resizable({
168 handles: 'w',
169 maxWidth: 400,
170 minWidth: 150,
171 resize: function(event, ui) {
172 $('.crm-designer-canvas').css('margin-right', (ui.size.width + 10) + 'px');
173 $(this).css({left: '', height: ''});
174 }
175 }).css({left: '', height: ''});
176 }
177 }
178 });
179
180 /**
181 * Display toolbar with working button
182 *
183 * options:
184 * - model: CRM.UF.UFGroupModel
185 */
186 CRM.Designer.ToolbarView = Backbone.Marionette.ItemView.extend({
187 serializeData: extendedSerializeData,
188 template: '#designer_buttons_template',
189 previewMode: false,
190 events: {
191 'click .crm-designer-save': 'doSave',
192 'click .crm-designer-preview': 'doPreview'
193 },
194 onRender: function() {
95269eab
CW
195 this.$('.crm-designer-save').button().attr({
196 disabled: 'disabled',
197 style: 'opacity:.5; box-shadow:none; cursor:default;'
198 });
6a488035
TO
199 this.$('.crm-designer-preview').button();
200 },
95269eab
CW
201 initialize: function(options) {
202 CRM.designerApp.vent.on('ufUnsaved', this.onUfChanged, this);
203 },
204 onUfChanged: function(isUfUnsaved) {
205 if (isUfUnsaved) {
206 this.$('.crm-designer-save').removeAttr('style').removeAttr('disabled');
207 }
208 },
6a488035
TO
209 doSave: function(event) {
210 var ufGroupModel = this.model;
211 if (ufGroupModel.getRel('ufFieldCollection').hasDuplicates()) {
212 CRM.alert(ts('Please correct errors before saving.'), '', 'alert');
213 return;
214 }
215 var $dialog = this.$el.closest('.crm-designer-dialog'); // FIXME use events
216 $dialog.block({message: 'Saving...', theme: true});
217 var profile = ufGroupModel.toStrictJSON();
218 profile["api.UFField.replace"] = {values: ufGroupModel.getRel('ufFieldCollection').toSortedJSON(), 'option.autoweight': 0};
219 CRM.api('UFGroup', 'create', profile, {
220 success: function(data) {
221 $dialog.unblock();
222 var error = false;
223 if (data.is_error) {
224 CRM.alert(data.error_message);
225 error = true;
226 }
227 _.each(data.values, function(ufGroupResponse) {
228 if (ufGroupResponse['api.UFField.replace'].is_error) {
229 CRM.alert(ufGroupResponse['api.UFField.replace'].error_message);
230 error = true;
231 }
232 });
233 if (!error) {
234 if (!ufGroupModel.get('id')) {
235 ufGroupModel.set('id', data.id);
236 }
237 CRM.designerApp.vent.trigger('ufUnsaved', false);
238 CRM.designerApp.vent.trigger('ufSaved');
239 $dialog.dialog('close');
240 }
241 }
242 });
243 return false;
244 },
245 doPreview: function(event) {
246 this.previewMode = !this.previewMode;
247 if (!this.previewMode) {
248 $('.crm-designer-preview-canvas').html('');
249 $('.crm-designer-canvas > *, .crm-designer-palette-region').show();
250 $('.crm-designer-preview span').html(ts('Preview'));
251 return;
252 }
253 if (this.model.getRel('ufFieldCollection').hasDuplicates()) {
254 CRM.alert(ts('Please correct errors before previewing.'), '', 'alert');
255 return;
256 }
257 var $dialog = this.$el.closest('.crm-designer-dialog'); // FIXME use events
258 $dialog.block({message: 'Loading...', theme: true});
4151fff2
CW
259 // CRM-12188
260 CRM.designerApp.clearPreviewArea();
6a488035
TO
261 $.ajax({
262 url: CRM.url("civicrm/ajax/inline"),
263 type: 'POST',
264 data: {
265 'qfKey': CRM.profilePreviewKey,
266 'class_name': 'CRM_UF_Form_Inline_Preview',
267 'snippet': 1,
268 'ufData': JSON.stringify({
269 ufGroup: this.model.toStrictJSON(),
270 ufFieldCollection: this.model.getRel('ufFieldCollection').toSortedJSON()
271 })
272 }
273 }).done(function(data) {
274 $dialog.unblock();
275 $('.crm-designer-canvas > *, .crm-designer-palette-region').hide();
276 $('.crm-designer-preview-canvas').html(data).show();
277 $('.crm-designer-preview span').html(ts('Edit'));
278 });
279 return false;
280 }
281 });
282
283 /**
284 * Display a selection of available fields
285 *
286 * options:
287 * - model: CRM.UF.UFGroupModel
288 */
289 CRM.Designer.PaletteView = Backbone.Marionette.ItemView.extend({
290 serializeData: extendedSerializeData,
291 template: '#palette_template',
292 el: '<div class="full-height"></div>',
293 events: {
294 'keyup .crm-designer-palette-search input': 'doSearch',
295 'click .crm-designer-palette-clear-search': 'clearSearch',
6a488035
TO
296 'click .crm-designer-palette-toggle': 'toggleAll'
297 },
298 initialize: function() {
299 this.model.getRel('ufFieldCollection')
300 .on('add', this.toggleActive, this)
301 .on('remove', this.toggleActive, this);
302 this.model.getRel('paletteFieldCollection')
303 .on('reset', this.render, this);
304 CRM.designerApp.vent.on('resize', this.onResize, this);
305 },
306 onClose: function() {
307 this.model.getRel('ufFieldCollection')
308 .off('add', this.toggleActive, this)
309 .off('remove', this.toggleActive, this);
310 this.model.getRel('paletteFieldCollection')
311 .off('reset', this.render, this);
312 CRM.designerApp.vent.off('resize', this.onResize, this);
313 },
314 onRender: function() {
315 var paletteView = this;
316
317 // Prepare data for jstree
318 var treeData = [];
319 var paletteFieldsByEntitySection = this.model.getRel('paletteFieldCollection').getFieldsByEntitySection();
320
321 paletteView.model.getRel('ufEntityCollection').each(function(ufEntityModel){
322 _.each(ufEntityModel.getSections(), function(section, sectionKey){
323 var entitySection = ufEntityModel.get('entity_name') + '-' + sectionKey;
324 var items = [];
325 if (paletteFieldsByEntitySection[entitySection]) {
326 _.each(paletteFieldsByEntitySection[entitySection], function(paletteFieldModel, k) {
327 items.push({data: paletteFieldModel.getLabel(), attr: {'class': 'crm-designer-palette-field', 'data-plm-cid': paletteFieldModel.cid}});
328 });
329 }
0249f58e 330 if (section.is_addable) {
6a488035
TO
331 items.push({data: 'placeholder', attr: {'class': 'crm-designer-palette-add', 'data-entity': ufEntityModel.get('entity_name'), 'data-section': sectionKey}});
332 }
333 if (items.length > 0) {
334 treeData.push({data: section.title, children: items});
335 }
336 })
337 });
338
339 this.$('.crm-designer-palette-tree').jstree({
340 'json_data': {data: treeData},
341 'search': {
342 'case_insensitive' : true,
343 'show_only_matches': true
344 },
345 themes: {
346 "theme": 'classic',
347 "dots": false,
4441df69
CW
348 "icons": false,
349 "url": CRM.config.resourceBase + 'packages/jquery/plugins/jstree/themes/classic/style.css'
6a488035
TO
350 },
351 'plugins': ['themes', 'json_data', 'ui', 'search']
352 }).bind('loaded.jstree', function () {
353 $('.crm-designer-palette-field', this).draggable({
354 appendTo: '.crm-designer',
355 zIndex: $(this.$el).zIndex() + 5000,
356 helper: 'clone',
357 connectToSortable: '.crm-designer-fields' // FIXME: tight canvas/palette coupling
358 });
359 $('.crm-designer-palette-field', this).dblclick(function(event){
360 var paletteFieldModel = paletteView.model.getRel('paletteFieldCollection').get($(event.currentTarget).attr('data-plm-cid'));
361 paletteFieldModel.addToUFCollection(paletteView.model.getRel('ufFieldCollection'));
362 event.stopPropagation();
363 });
364 paletteView.model.getRel('ufFieldCollection').each(function(ufFieldModel) {
365 paletteView.toggleActive(ufFieldModel, paletteView.model.getRel('ufFieldCollection'))
366 });
367 paletteView.$('.crm-designer-palette-add a').remove();
368 paletteView.$('.crm-designer-palette-add').append('<button>'+ts('Add Field')+'</button>');
369 paletteView.$('.crm-designer-palette-add button').button()
370 .click(function(event){
371 var entityKey = $(event.currentTarget).closest('.crm-designer-palette-add').attr('data-entity');
372 var sectionKey = $(event.currentTarget).closest('.crm-designer-palette-add').attr('data-section');
373 var ufEntityModel = paletteView.model.getRel('ufEntityCollection').getByName(entityKey);
374 var sections = ufEntityModel.getSections();
375 paletteView.doAddField(sections[sectionKey]);
376 event.stopPropagation();
377 })
378 ;
379 }).bind("select_node.jstree", function (e, data) {
380 $(this).jstree("toggle_node", data.rslt.obj);
381 $(this).jstree("deselect_node", data.rslt.obj);
382 });
383
384 // FIXME: tight canvas/palette coupling
385 this.$(".crm-designer-fields").droppable({
386 activeClass: "ui-state-default",
387 hoverClass: "ui-state-hover",
388 accept: ":not(.ui-sortable-helper)"
389 });
390
391 this.onResize();
392 },
393 onResize: function() {
394 var pos = this.$('.crm-designer-palette-tree').position();
395 var div = this.$('.crm-designer-palette-tree').closest('.crm-container').height();
396 this.$('.crm-designer-palette-tree').css({height: div - pos.top});
397 },
398 doSearch: function(event) {
399 $('.crm-designer-palette-tree').jstree("search", $(event.target).val());
400 },
401 doAddField: function(section) {
402 var paletteView = this;
3fde8ee5
CW
403 var url = CRM.url('civicrm/admin/custom/group/field/add', {
404 reset: 1,
405 action: 'add',
406 gid: section.custom_group_id
407 });
408 CRM.loadForm(url, {
409 resetButton: 'next_new',
410 onSuccess: function(data, settings) {
0b1bae4a 411 paletteView.doRefresh('custom_' + data.customField.id);
3fde8ee5
CW
412 if (data.buttonName != 'next_new') {
413 $(settings.target).dialog('close');
6a488035 414 }
3fde8ee5
CW
415 }
416 });
6a488035
TO
417 return false;
418 },
0b1bae4a 419 doRefresh: function(fieldToAdd) {
6a488035
TO
420 var ufGroupModel = this.model;
421 CRM.Schema.reloadModels()
422 .done(function(data){
423 ufGroupModel.resetEntities();
0b1bae4a
CW
424 if (fieldToAdd) {
425 var field = ufGroupModel.getRel('paletteFieldCollection').getFieldByName(null, fieldToAdd);
426 field.addToUFCollection(ufGroupModel.getRel('ufFieldCollection'));
427 }
6a488035
TO
428 })
429 .fail(function() {
430 CRM.alert(ts('Failed to retrieve schema'), ts('Error'), 'error');
431 });
432 return false;
433 },
434 clearSearch: function(event) {
435 $('.crm-designer-palette-search input').val('').keyup();
436 return false;
437 },
438 toggleActive: function(ufFieldModel, ufFieldCollection, options) {
439 var paletteFieldCollection = this.model.getRel('paletteFieldCollection');
440 var paletteFieldModel = paletteFieldCollection.getFieldByName(ufFieldModel.get('entity_name'), ufFieldModel.get('field_name'));
441 var isAddable = ufFieldCollection.isAddable(ufFieldModel);
442 this.$('[data-plm-cid='+paletteFieldModel.cid+']').toggleClass('disabled', !isAddable);
443 },
444 toggleAll: function(event) {
445 if ($('.crm-designer-palette-search input').val() == '') {
446 $('.crm-designer-palette-tree').jstree($(event.target).attr('rel'));
447 }
448 return false;
449 }
450 });
451
452 /**
453 * Display all UFFieldModel objects in a UFGroupModel.
454 *
455 * options:
456 * - model: CRM.UF.UFGroupModel
457 */
458 CRM.Designer.UFFieldCanvasView = Backbone.Marionette.View.extend({
459 initialize: function() {
460 this.model.getRel('ufFieldCollection')
461 .on('add', this.updatePlaceholder, this)
462 .on('remove', this.updatePlaceholder, this)
463 .on('add', this.addUFFieldView, this);
464 },
465 onClose: function() {
466 this.model.getRel('ufFieldCollection')
467 .off('add', this.updatePlaceholder, this)
468 .off('remove', this.updatePlaceholder, this)
469 .off('add', this.addUFFieldView, this);
470 },
471 render: function() {
472 var ufFieldCanvasView = this;
473 this.$el.html(_.template($('#field_canvas_view_template').html()));
474
475 // BOTTOM: Setup field-level editing
476 var $fields = this.$('.crm-designer-fields');
477 this.updatePlaceholder();
478 var ufFieldModels = this.model.getRel('ufFieldCollection').sortBy(function(ufFieldModel) {
479 return parseInt(ufFieldModel.get('weight'));
480 });
481 _.each(ufFieldModels, function(ufFieldModel) {
482 ufFieldCanvasView.addUFFieldView(ufFieldModel, ufFieldCanvasView.model.getRel('ufFieldCollection'), {skipWeights: true});
483 });
484 this.$(".crm-designer-fields").sortable({
485 placeholder: 'crm-designer-row-placeholder',
486 forcePlaceholderSize: true,
487 receive: function(event, ui) {
488 var paletteFieldModel = ufFieldCanvasView.model.getRel('paletteFieldCollection').get(ui.item.attr('data-plm-cid'));
489 var ufFieldModel = paletteFieldModel.addToUFCollection(
490 ufFieldCanvasView.model.getRel('ufFieldCollection'),
491 {skipWeights: true}
492 );
493 if (null == ufFieldModel) {
494 ufFieldCanvasView.$('.crm-designer-fields .ui-draggable').remove();
495 } else {
496 // Move from end to the 'dropped' position
497 var ufFieldViewEl = ufFieldCanvasView.$('div[data-field-cid='+ufFieldModel.cid+']').parent();
498 ufFieldCanvasView.$('.crm-designer-fields .ui-draggable').replaceWith(ufFieldViewEl);
499 }
500 // note: the sortable() update callback will call updateWeight
501 },
502 update: function() {
503 ufFieldCanvasView.updateWeights();
504 }
505 });
506 },
507 /** Determine visual order of fields and set the model values for "weight" */
508 updateWeights: function() {
509 var ufFieldCanvasView = this;
510 var weight = 1;
511 var rows = this.$('.crm-designer-row').each(function(key, row) {
512 if ($(row).hasClass('placeholder')) {
513 return;
514 }
515 var ufFieldCid = $(row).attr('data-field-cid');
516 var ufFieldModel = ufFieldCanvasView.model.getRel('ufFieldCollection').get(ufFieldCid);
517 ufFieldModel.set('weight', weight);
518 weight++;
519 });
520 },
521 addUFFieldView: function(ufFieldModel, ufFieldCollection, options) {
522 var paletteFieldModel = this.model.getRel('paletteFieldCollection').getFieldByName(ufFieldModel.get('entity_name'), ufFieldModel.get('field_name'));
523 var ufFieldView = new CRM.Designer.UFFieldView({
524 el: $("<div></div>"),
525 model: ufFieldModel,
526 paletteFieldModel: paletteFieldModel
527 });
528 ufFieldView.render();
529 this.$('.crm-designer-fields').append(ufFieldView.$el);
530 if (! (options && options.skipWeights)) {
531 this.updateWeights();
532 }
533 },
534 updatePlaceholder: function() {
535 if (this.model.getRel('ufFieldCollection').isEmpty()) {
536 this.$('.placeholder').css({display: 'block', border: '0 none', cursor: 'default'});
537 } else {
538 this.$('.placeholder').hide();
539 }
540 }
541 });
542
543 /**
544 * options:
545 * - model: CRM.UF.UFFieldModel
546 * - paletteFieldModel: CRM.Designer.PaletteFieldModel
547 */
548 CRM.Designer.UFFieldView = Backbone.Marionette.Layout.extend({
549 serializeData: extendedSerializeData,
550 template: '#field_row_template',
551 expanded: false,
552 regions: {
553 summary: '.crm-designer-field-summary',
554 detail: '.crm-designer-field-detail'
555 },
556 events: {
557 "click .crm-designer-action-settings": 'doToggleForm',
558 "click .crm-designer-action-remove": 'doRemove'
559 },
560 modelEvents: {
561 "destroy": 'remove',
562 "change:is_duplicate": 'onChangeIsDuplicate'
563 },
564 onRender: function() {
565 this.summary.show(new CRM.Designer.UFFieldSummaryView({
566 model: this.model,
567 fieldSchema: this.model.getFieldSchema(),
568 paletteFieldModel: this.options.paletteFieldModel
569 }));
570 this.detail.show(new CRM.Designer.UFFieldDetailView({
571 model: this.model,
572 fieldSchema: this.model.getFieldSchema()
573 }));
574 this.onChangeIsDuplicate(this.model, this.model.get('is_duplicate'))
575 if (!this.expanded) {
576 this.detail.$el.hide();
577 }
578 var that = this;
579 CRM.designerApp.vent.on('formOpened', function(event) {
580 if (that.expanded && event != that.cid) {
581 that.doToggleForm(false);
582 }
583 });
584 },
585 doToggleForm: function(event) {
586 this.expanded = !this.expanded;
587 if (this.expanded && event !== false) {
588 CRM.designerApp.vent.trigger('formOpened', this.cid);
589 }
590 this.$el.toggleClass('crm-designer-open', this.expanded);
591 var $detail = this.detail.$el;
592 if (!this.expanded) {
593 $detail.toggle('blind', 250);
594 }
595 else {
596 var $canvas = $('.crm-designer-canvas');
597 var top = $canvas.offset().top;
598 $detail.slideDown({
599 duration: 250,
600 step: function(num, effect) {
601 // Scroll canvas to keep field details visible
602 if (effect.prop == 'height') {
603 if (effect.now + $detail.offset().top - top > $canvas.height() - 9) {
604 $canvas.scrollTop($canvas.scrollTop() + effect.now + $detail.offset().top - top - $canvas.height() + 9);
605 }
606 }
607 }
608 });
609 }
610 },
611 onChangeIsDuplicate: function(model, value, options) {
612 this.$el.toggleClass('crm-designer-duplicate', value);
613 },
614 doRemove: function(event) {
615 var that = this;
616 this.$el.hide(250, function() {
617 that.model.destroyLocal();
618 });
619 }
620 });
621
622 /**
623 * options:
624 * - model: CRM.UF.UFFieldModel
625 * - fieldSchema: (Backbone.Form schema element)
626 * - paletteFieldModel: CRM.Designer.PaletteFieldModel
627 */
628 CRM.Designer.UFFieldSummaryView = Backbone.Marionette.ItemView.extend({
629 serializeData: extendedSerializeData,
630 template: '#field_summary_template',
631 modelEvents: {
632 'change': 'render'
633 },
634
635 /**
636 * Compose a printable string which describes the binding of this UFField to the data model
637 * @return {String}
638 */
639 getBindingLabel: function() {
640 var result = this.options.paletteFieldModel.getSection().title + ": " + this.options.paletteFieldModel.getLabel();
641 if (this.options.fieldSchema.civiIsPhone) {
642 result = result + '-' + CRM.PseudoConstant.phoneType[this.model.get('phone_type_id')];
643 }
644 if (this.options.fieldSchema.civiIsLocation) {
645 var locType = this.model.get('location_type_id') ? CRM.PseudoConstant.locationType[this.model.get('location_type_id')] : ts('Primary');
646 result = result + ' (' + locType + ')';
647 }
648 return result;
649 },
650
651 /**
652 * Return a string marking if the field is required
653 * @return {String}
654 */
655 getRequiredMarker: function() {
656 if (this.model.get('is_required') == 1) {
657 return ' <span class="crm-marker">*</span> ';
658 }
659 return '';
660 },
661
662 onRender: function() {
663 this.$el.toggleClass('disabled', this.model.get('is_active') != 1);
664 if (this.model.get("is_reserved") == 1) {
665 this.$('.crm-designer-buttons').hide();
666 }
667 }
668 });
669
670 /**
671 * options:
672 * - model: CRM.UF.UFFieldModel
673 * - fieldSchema: (Backbone.Form schema element)
674 */
675 CRM.Designer.UFFieldDetailView = Backbone.View.extend({
676 initialize: function() {
677 // FIXME: hide/display 'in_selector' if 'visibility' is one of the public options
678 var fields = ['location_type_id', 'phone_type_id', 'label', 'is_multi_summary', 'is_required', 'is_view', 'visibility', 'in_selector', 'is_searchable', 'help_pre', 'help_post', 'is_active'];
679 if (! this.options.fieldSchema.civiIsLocation) {
680 fields = _.without(fields, 'location_type_id');
681 }
682 if (! this.options.fieldSchema.civiIsPhone) {
683 fields = _.without(fields, 'phone_type_id');
684 }
685 if (!this.options.fieldSchema.civiIsMultiple) {
686 fields = _.without(fields, 'is_multi_summary');
687 }
688
689 this.form = new Backbone.Form({
690 model: this.model,
691 fields: fields
692 });
693 this.form.on('change', this.onFormChange, this);
8fd0e719 694 this.model.on('change', this.onModelChange, this);
6a488035
TO
695 },
696 render: function() {
697 this.$el.html(this.form.render().el);
698 this.onFormChange();
699 },
8fd0e719
CW
700 onModelChange: function() {
701 $.each(this.form.fields, function(i, field) {
702 this.form.setValue(field.key, this.model.get(field.key));
703 });
704 },
6a488035
TO
705 onFormChange: function() {
706 this.form.commit();
707 this.$('.field-is_multi_summary').toggle(this.options.fieldSchema.civiIsMultiple ? true : false);
708 this.$('.field-in_selector').toggle(this.model.isInSelectorAllowed());
709 // this.$(':input').attr('disabled', this.model.get("is_reserved") == 1);
710
711 if (!this.model.isInSelectorAllowed() && this.model.get('in_selector') != "0") {
712 this.model.set('in_selector', "0");
713 this.form.setValue('in_selector', "0");
714 // TODO: It might be nicer if we didn't completely discard in_selector -- e.g.
715 // if the value could be restored when the user isInSelectorAllowed becomes true
716 // again. However, I haven't found a simple way to do this.
717 }
718 }
719 });
720
721 /**
722 * options:
723 * - model: CRM.UF.UFGroupModel
724 */
725 CRM.Designer.UFGroupView = Backbone.Marionette.Layout.extend({
726 serializeData: extendedSerializeData,
727 template: '#form_row_template',
728 expanded: false,
729 regions: {
730 summary: '.crm-designer-form-summary',
731 detail: '.crm-designer-form-detail'
732 },
733 events: {
734 "click .crm-designer-action-settings": 'doToggleForm'
735 },
736 onRender: function() {
737 this.summary.show(new CRM.Designer.UFGroupSummaryView({
738 model: this.model
739 }));
740 this.detail.show(new CRM.Designer.UFGroupDetailView({
741 model: this.model
742 }));
743 if (!this.expanded) {
744 this.detail.$el.hide();
745 }
746 var that = this;
747 CRM.designerApp.vent.on('formOpened', function(event) {
748 if (that.expanded && event !== 0) {
749 that.doToggleForm(false);
750 }
751 });
752 },
753 doToggleForm: function(event) {
754 this.expanded = !this.expanded;
755 if (this.expanded && event !== false) {
756 CRM.designerApp.vent.trigger('formOpened', 0);
757 }
758 this.$el.toggleClass('crm-designer-open', this.expanded);
759 this.detail.$el.toggle('blind', 250);
760 }
761 });
762
763 /**
764 * options:
765 * - model: CRM.UF.UFGroupModel
766 */
767 CRM.Designer.UFGroupSummaryView = Backbone.Marionette.ItemView.extend({
768 serializeData: extendedSerializeData,
769 template: '#form_summary_template',
770 modelEvents: {
771 'change': 'render'
772 },
773 onRender: function() {
774 this.$el.toggleClass('disabled', this.model.get('is_active') != 1);
775 if (this.model.get("is_reserved") == 1) {
776 this.$('.crm-designer-buttons').hide();
777 }
778 }
779 });
780
781 /**
782 * options:
783 * - model: CRM.UF.UFGroupModel
784 */
785 CRM.Designer.UFGroupDetailView = Backbone.View.extend({
786 initialize: function() {
787 this.form = new Backbone.Form({
788 model: this.model,
789 fields: ['title', 'help_pre', 'help_post', 'is_active']
790 });
791 this.form.on('change', this.form.commit, this.form);
792 },
793 render: function() {
794 this.$el.html(this.form.render().el);
795 }
796 });
797
798})(cj);