CRM-10693 - crmSnippet - Convert clientside helpers to use $.widget; standardize...
[civicrm-core.git] / js / view / crm.designer.js
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;
23 };
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;
102 // CRM-12188
103 CRM.designerApp.DetachedProfiles = [];
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 }
118 // CRM-12188
119 CRM.designerApp.restorePreviewArea();
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() {
195 this.$('.crm-designer-save').button().attr({
196 disabled: 'disabled',
197 style: 'opacity:.5; box-shadow:none; cursor:default;'
198 });
199 this.$('.crm-designer-preview').button();
200 },
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 },
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});
259 // CRM-12188
260 CRM.designerApp.clearPreviewArea();
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 openTreeNodes: [],
294 events: {
295 'keyup .crm-designer-palette-search input': 'doSearch',
296 'click .crm-designer-palette-clear-search': 'clearSearch',
297 'click .crm-designer-palette-toggle': 'toggleAll',
298 'click .crm-designer-palette-add button': 'doNewCustomFieldDialog',
299 'dblclick .crm-designer-palette-field': 'doAddToCanvas'
300 },
301 initialize: function() {
302 this.model.getRel('ufFieldCollection')
303 .on('add', this.toggleActive, this)
304 .on('remove', this.toggleActive, this);
305 this.model.getRel('paletteFieldCollection')
306 .on('reset', this.render, this);
307 CRM.designerApp.vent.on('resize', this.onResize, this);
308 },
309 onClose: function() {
310 this.model.getRel('ufFieldCollection')
311 .off('add', this.toggleActive, this)
312 .off('remove', this.toggleActive, this);
313 this.model.getRel('paletteFieldCollection')
314 .off('reset', this.render, this);
315 CRM.designerApp.vent.off('resize', this.onResize, this);
316 },
317 onRender: function() {
318 var paletteView = this;
319
320 // Prepare data for jstree
321 var treeData = [];
322 var paletteFieldsByEntitySection = this.model.getRel('paletteFieldCollection').getFieldsByEntitySection();
323
324 paletteView.model.getRel('ufEntityCollection').each(function(ufEntityModel){
325 _.each(ufEntityModel.getSections(), function(section, sectionKey){
326 var entitySection = ufEntityModel.get('entity_name') + '-' + sectionKey;
327 var items = [];
328 if (paletteFieldsByEntitySection[entitySection]) {
329 _.each(paletteFieldsByEntitySection[entitySection], function(paletteFieldModel, k) {
330 items.push({data: paletteFieldModel.getLabel(), attr: {'class': 'crm-designer-palette-field', 'data-plm-cid': paletteFieldModel.cid}});
331 });
332 }
333 if (section.is_addable) {
334 items.push({data: ts('+ Add New Field'), attr: {'class': 'crm-designer-palette-add'}});
335 }
336 if (items.length > 0) {
337 treeData.push({
338 data: section.title,
339 children: items,
340 state: _.contains(paletteView.openTreeNodes, sectionKey) ? 'open' : 'closed',
341 attr: {
342 'class': 'crm-designer-palette-section',
343 'data-section': sectionKey,
344 'data-entity': ufEntityModel.get('entity_name')
345 }
346 });
347 }
348 })
349 });
350
351 this.$('.crm-designer-palette-tree').jstree({
352 'json_data': {data: treeData},
353 'search': {
354 'case_insensitive' : true,
355 'show_only_matches': true
356 },
357 themes: {
358 "theme": 'classic',
359 "dots": false,
360 "icons": false,
361 "url": CRM.config.resourceBase + 'packages/jquery/plugins/jstree/themes/classic/style.css'
362 },
363 'plugins': ['themes', 'json_data', 'ui', 'search']
364 }).bind('loaded.jstree', function () {
365 $('.crm-designer-palette-field', this).draggable({
366 appendTo: '.crm-designer',
367 zIndex: $(this.$el).zIndex() + 5000,
368 helper: 'clone',
369 connectToSortable: '.crm-designer-fields' // FIXME: tight canvas/palette coupling
370 });
371 paletteView.model.getRel('ufFieldCollection').each(function(ufFieldModel) {
372 paletteView.toggleActive(ufFieldModel, paletteView.model.getRel('ufFieldCollection'))
373 });
374 paletteView.$('.crm-designer-palette-add a').replaceWith('<button>' + $('.crm-designer-palette-add a').first().text() + '</<button>');
375 paletteView.$('.crm-designer-palette-add button').button();
376 }).bind("select_node.jstree", function (e, data) {
377 $(this).jstree("toggle_node", data.rslt.obj);
378 $(this).jstree("deselect_node", data.rslt.obj);
379 });
380
381 // FIXME: tight canvas/palette coupling
382 this.$(".crm-designer-fields").droppable({
383 activeClass: "ui-state-default",
384 hoverClass: "ui-state-hover",
385 accept: ":not(.ui-sortable-helper)"
386 });
387
388 this.onResize();
389 },
390 onResize: function() {
391 var pos = this.$('.crm-designer-palette-tree').position();
392 var div = this.$('.crm-designer-palette-tree').closest('.crm-container').height();
393 this.$('.crm-designer-palette-tree').css({height: div - pos.top});
394 },
395 doSearch: function(event) {
396 $('.crm-designer-palette-tree').jstree("search", $(event.target).val());
397 },
398 doAddToCanvas: function(event) {
399 var paletteFieldModel = this.model.getRel('paletteFieldCollection').get($(event.currentTarget).attr('data-plm-cid'));
400 paletteFieldModel.addToUFCollection(this.model.getRel('ufFieldCollection'));
401 event.stopPropagation();
402 },
403 doNewCustomFieldDialog: function(event) {
404 var paletteView = this;
405 var entityKey = $(event.currentTarget).closest('.crm-designer-palette-section').attr('data-entity');
406 var sectionKey = $(event.currentTarget).closest('.crm-designer-palette-section').attr('data-section');
407 var ufEntityModel = paletteView.model.getRel('ufEntityCollection').getByName(entityKey);
408 var sections = ufEntityModel.getSections();
409 var url = CRM.url('civicrm/admin/custom/group/field/add', {
410 reset: 1,
411 action: 'add',
412 gid: sections[sectionKey].custom_group_id
413 });
414 CRM.loadForm(url).on('crmFormSuccess', function(e, data) {
415 paletteView.doRefresh('custom_' + data.id);
416 });
417 return false;
418 },
419 doRefresh: function(fieldToAdd) {
420 var ufGroupModel = this.model;
421 this.getOpenTreeNodes();
422 CRM.Schema.reloadModels()
423 .done(function(data){
424 ufGroupModel.resetEntities();
425 if (fieldToAdd) {
426 var field = ufGroupModel.getRel('paletteFieldCollection').getFieldByName(null, fieldToAdd);
427 field.addToUFCollection(ufGroupModel.getRel('ufFieldCollection'));
428 }
429 })
430 .fail(function() {
431 CRM.alert(ts('Failed to retrieve schema'), ts('Error'), 'error');
432 });
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 getOpenTreeNodes: function() {
451 var paletteView = this;
452 this.openTreeNodes = [];
453 this.$('.crm-designer-palette-section.jstree-open').each(function() {
454 paletteView.openTreeNodes.push($(this).data('section'));
455 })
456 }
457 });
458
459 /**
460 * Display all UFFieldModel objects in a UFGroupModel.
461 *
462 * options:
463 * - model: CRM.UF.UFGroupModel
464 */
465 CRM.Designer.UFFieldCanvasView = Backbone.Marionette.View.extend({
466 initialize: function() {
467 this.model.getRel('ufFieldCollection')
468 .on('add', this.updatePlaceholder, this)
469 .on('remove', this.updatePlaceholder, this)
470 .on('add', this.addUFFieldView, this);
471 },
472 onClose: function() {
473 this.model.getRel('ufFieldCollection')
474 .off('add', this.updatePlaceholder, this)
475 .off('remove', this.updatePlaceholder, this)
476 .off('add', this.addUFFieldView, this);
477 },
478 render: function() {
479 var ufFieldCanvasView = this;
480 this.$el.html(_.template($('#field_canvas_view_template').html()));
481
482 // BOTTOM: Setup field-level editing
483 var $fields = this.$('.crm-designer-fields');
484 this.updatePlaceholder();
485 var ufFieldModels = this.model.getRel('ufFieldCollection').sortBy(function(ufFieldModel) {
486 return parseInt(ufFieldModel.get('weight'));
487 });
488 _.each(ufFieldModels, function(ufFieldModel) {
489 ufFieldCanvasView.addUFFieldView(ufFieldModel, ufFieldCanvasView.model.getRel('ufFieldCollection'), {skipWeights: true});
490 });
491 this.$(".crm-designer-fields").sortable({
492 placeholder: 'crm-designer-row-placeholder',
493 forcePlaceholderSize: true,
494 receive: function(event, ui) {
495 var paletteFieldModel = ufFieldCanvasView.model.getRel('paletteFieldCollection').get(ui.item.attr('data-plm-cid'));
496 var ufFieldModel = paletteFieldModel.addToUFCollection(
497 ufFieldCanvasView.model.getRel('ufFieldCollection'),
498 {skipWeights: true}
499 );
500 if (null == ufFieldModel) {
501 ufFieldCanvasView.$('.crm-designer-fields .ui-draggable').remove();
502 } else {
503 // Move from end to the 'dropped' position
504 var ufFieldViewEl = ufFieldCanvasView.$('div[data-field-cid='+ufFieldModel.cid+']').parent();
505 ufFieldCanvasView.$('.crm-designer-fields .ui-draggable').replaceWith(ufFieldViewEl);
506 }
507 // note: the sortable() update callback will call updateWeight
508 },
509 update: function() {
510 ufFieldCanvasView.updateWeights();
511 }
512 });
513 },
514 /** Determine visual order of fields and set the model values for "weight" */
515 updateWeights: function() {
516 var ufFieldCanvasView = this;
517 var weight = 1;
518 var rows = this.$('.crm-designer-row').each(function(key, row) {
519 if ($(row).hasClass('placeholder')) {
520 return;
521 }
522 var ufFieldCid = $(row).attr('data-field-cid');
523 var ufFieldModel = ufFieldCanvasView.model.getRel('ufFieldCollection').get(ufFieldCid);
524 ufFieldModel.set('weight', weight);
525 weight++;
526 });
527 },
528 addUFFieldView: function(ufFieldModel, ufFieldCollection, options) {
529 var paletteFieldModel = this.model.getRel('paletteFieldCollection').getFieldByName(ufFieldModel.get('entity_name'), ufFieldModel.get('field_name'));
530 var ufFieldView = new CRM.Designer.UFFieldView({
531 el: $("<div></div>"),
532 model: ufFieldModel,
533 paletteFieldModel: paletteFieldModel
534 });
535 ufFieldView.render();
536 this.$('.crm-designer-fields').append(ufFieldView.$el);
537 if (! (options && options.skipWeights)) {
538 this.updateWeights();
539 }
540 },
541 updatePlaceholder: function() {
542 if (this.model.getRel('ufFieldCollection').isEmpty()) {
543 this.$('.placeholder').css({display: 'block', border: '0 none', cursor: 'default'});
544 } else {
545 this.$('.placeholder').hide();
546 }
547 }
548 });
549
550 /**
551 * options:
552 * - model: CRM.UF.UFFieldModel
553 * - paletteFieldModel: CRM.Designer.PaletteFieldModel
554 */
555 CRM.Designer.UFFieldView = Backbone.Marionette.Layout.extend({
556 serializeData: extendedSerializeData,
557 template: '#field_row_template',
558 expanded: false,
559 regions: {
560 summary: '.crm-designer-field-summary',
561 detail: '.crm-designer-field-detail'
562 },
563 events: {
564 "click .crm-designer-action-settings": 'doToggleForm',
565 "click .crm-designer-action-remove": 'doRemove'
566 },
567 modelEvents: {
568 "destroy": 'remove',
569 "change:is_duplicate": 'onChangeIsDuplicate'
570 },
571 onRender: function() {
572 this.summary.show(new CRM.Designer.UFFieldSummaryView({
573 model: this.model,
574 fieldSchema: this.model.getFieldSchema(),
575 paletteFieldModel: this.options.paletteFieldModel
576 }));
577 this.detail.show(new CRM.Designer.UFFieldDetailView({
578 model: this.model,
579 fieldSchema: this.model.getFieldSchema()
580 }));
581 this.onChangeIsDuplicate(this.model, this.model.get('is_duplicate'))
582 if (!this.expanded) {
583 this.detail.$el.hide();
584 }
585 var that = this;
586 CRM.designerApp.vent.on('formOpened', function(event) {
587 if (that.expanded && event != that.cid) {
588 that.doToggleForm(false);
589 }
590 });
591 },
592 doToggleForm: function(event) {
593 this.expanded = !this.expanded;
594 if (this.expanded && event !== false) {
595 CRM.designerApp.vent.trigger('formOpened', this.cid);
596 }
597 this.$el.toggleClass('crm-designer-open', this.expanded);
598 var $detail = this.detail.$el;
599 if (!this.expanded) {
600 $detail.toggle('blind', 250);
601 }
602 else {
603 var $canvas = $('.crm-designer-canvas');
604 var top = $canvas.offset().top;
605 $detail.slideDown({
606 duration: 250,
607 step: function(num, effect) {
608 // Scroll canvas to keep field details visible
609 if (effect.prop == 'height') {
610 if (effect.now + $detail.offset().top - top > $canvas.height() - 9) {
611 $canvas.scrollTop($canvas.scrollTop() + effect.now + $detail.offset().top - top - $canvas.height() + 9);
612 }
613 }
614 }
615 });
616 }
617 },
618 onChangeIsDuplicate: function(model, value, options) {
619 this.$el.toggleClass('crm-designer-duplicate', value);
620 },
621 doRemove: function(event) {
622 var that = this;
623 this.$el.hide(250, function() {
624 that.model.destroyLocal();
625 });
626 }
627 });
628
629 /**
630 * options:
631 * - model: CRM.UF.UFFieldModel
632 * - fieldSchema: (Backbone.Form schema element)
633 * - paletteFieldModel: CRM.Designer.PaletteFieldModel
634 */
635 CRM.Designer.UFFieldSummaryView = Backbone.Marionette.ItemView.extend({
636 serializeData: extendedSerializeData,
637 template: '#field_summary_template',
638 modelEvents: {
639 'change': 'render'
640 },
641
642 /**
643 * Compose a printable string which describes the binding of this UFField to the data model
644 * @return {String}
645 */
646 getBindingLabel: function() {
647 var result = this.options.paletteFieldModel.getSection().title + ": " + this.options.paletteFieldModel.getLabel();
648 if (this.options.fieldSchema.civiIsPhone) {
649 result = result + '-' + CRM.PseudoConstant.phoneType[this.model.get('phone_type_id')];
650 }
651 if (this.options.fieldSchema.civiIsLocation) {
652 var locType = this.model.get('location_type_id') ? CRM.PseudoConstant.locationType[this.model.get('location_type_id')] : ts('Primary');
653 result = result + ' (' + locType + ')';
654 }
655 return result;
656 },
657
658 /**
659 * Return a string marking if the field is required
660 * @return {String}
661 */
662 getRequiredMarker: function() {
663 if (this.model.get('is_required') == 1) {
664 return ' <span class="crm-marker">*</span> ';
665 }
666 return '';
667 },
668
669 onRender: function() {
670 this.$el.toggleClass('disabled', this.model.get('is_active') != 1);
671 if (this.model.get("is_reserved") == 1) {
672 this.$('.crm-designer-buttons').hide();
673 }
674 }
675 });
676
677 /**
678 * options:
679 * - model: CRM.UF.UFFieldModel
680 * - fieldSchema: (Backbone.Form schema element)
681 */
682 CRM.Designer.UFFieldDetailView = Backbone.View.extend({
683 initialize: function() {
684 // FIXME: hide/display 'in_selector' if 'visibility' is one of the public options
685 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'];
686 if (! this.options.fieldSchema.civiIsLocation) {
687 fields = _.without(fields, 'location_type_id');
688 }
689 if (! this.options.fieldSchema.civiIsPhone) {
690 fields = _.without(fields, 'phone_type_id');
691 }
692 if (!this.options.fieldSchema.civiIsMultiple) {
693 fields = _.without(fields, 'is_multi_summary');
694 }
695
696 this.form = new Backbone.Form({
697 model: this.model,
698 fields: fields
699 });
700 this.form.on('change', this.onFormChange, this);
701 this.model.on('change', this.onModelChange, this);
702 },
703 render: function() {
704 this.$el.html(this.form.render().el);
705 this.onFormChange();
706 },
707 onModelChange: function() {
708 $.each(this.form.fields, function(i, field) {
709 this.form.setValue(field.key, this.model.get(field.key));
710 });
711 },
712 onFormChange: function() {
713 this.form.commit();
714 this.$('.field-is_multi_summary').toggle(this.options.fieldSchema.civiIsMultiple ? true : false);
715 this.$('.field-in_selector').toggle(this.model.isInSelectorAllowed());
716 // this.$(':input').attr('disabled', this.model.get("is_reserved") == 1);
717
718 if (!this.model.isInSelectorAllowed() && this.model.get('in_selector') != "0") {
719 this.model.set('in_selector', "0");
720 this.form.setValue('in_selector', "0");
721 // TODO: It might be nicer if we didn't completely discard in_selector -- e.g.
722 // if the value could be restored when the user isInSelectorAllowed becomes true
723 // again. However, I haven't found a simple way to do this.
724 }
725 }
726 });
727
728 /**
729 * options:
730 * - model: CRM.UF.UFGroupModel
731 */
732 CRM.Designer.UFGroupView = Backbone.Marionette.Layout.extend({
733 serializeData: extendedSerializeData,
734 template: '#form_row_template',
735 expanded: false,
736 regions: {
737 summary: '.crm-designer-form-summary',
738 detail: '.crm-designer-form-detail'
739 },
740 events: {
741 "click .crm-designer-action-settings": 'doToggleForm'
742 },
743 onRender: function() {
744 this.summary.show(new CRM.Designer.UFGroupSummaryView({
745 model: this.model
746 }));
747 this.detail.show(new CRM.Designer.UFGroupDetailView({
748 model: this.model
749 }));
750 if (!this.expanded) {
751 this.detail.$el.hide();
752 }
753 var that = this;
754 CRM.designerApp.vent.on('formOpened', function(event) {
755 if (that.expanded && event !== 0) {
756 that.doToggleForm(false);
757 }
758 });
759 },
760 doToggleForm: function(event) {
761 this.expanded = !this.expanded;
762 if (this.expanded && event !== false) {
763 CRM.designerApp.vent.trigger('formOpened', 0);
764 }
765 this.$el.toggleClass('crm-designer-open', this.expanded);
766 this.detail.$el.toggle('blind', 250);
767 }
768 });
769
770 /**
771 * options:
772 * - model: CRM.UF.UFGroupModel
773 */
774 CRM.Designer.UFGroupSummaryView = Backbone.Marionette.ItemView.extend({
775 serializeData: extendedSerializeData,
776 template: '#form_summary_template',
777 modelEvents: {
778 'change': 'render'
779 },
780 onRender: function() {
781 this.$el.toggleClass('disabled', this.model.get('is_active') != 1);
782 if (this.model.get("is_reserved") == 1) {
783 this.$('.crm-designer-buttons').hide();
784 }
785 }
786 });
787
788 /**
789 * options:
790 * - model: CRM.UF.UFGroupModel
791 */
792 CRM.Designer.UFGroupDetailView = Backbone.View.extend({
793 initialize: function() {
794 this.form = new Backbone.Form({
795 model: this.model,
796 fields: ['title', 'help_pre', 'help_post', 'is_active']
797 });
798 this.form.on('change', this.form.commit, this.form);
799 },
800 render: function() {
801 this.$el.html(this.form.render().el);
802 }
803 });
804
805 })(cj);