summaryrefslogtreecommitdiffstats
path: root/web/widget/field.js
blob: b0c603488a7e8fffa3230449206a7bf583693e3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
 * Copyright (c) 2012-2014 Kaarle Ritvanen
 * See LICENSE file for license details
 */

define(
    [
	"acf2/dom",
	"acf2/error",
	"acf2/statusbar",
	"acf2/widget/abstract/base",
	"jquery",
	"underscore"
    ],
    function(dom, formatError, statusBar, Base, $, _) {
	return Base.extend({
	    init: function(
		data, name, meta, level, editable, removable
	    ) {
		this.editable = editable && meta.editable;

		var el = Base.init.call(
		    this,
		    data,
		    name,
		    meta,
		    level,
		    editable,
		    removable
		);

		if (this.editable)
		    this.field.change(_.bind(this.validateChange, this));

		return el;
	    },

	    staticRender: function(value, meta) {
		return $("<td>").text(value ? value : "");
	    },

	    makeEl: function() {
		Base.makeEl.call(this);
		if (!this.field) this.field = this.el;
	    },

	    createEl: function() { return $("<input>"); },

	    render: function(value, meta) {
		this.field.attr({type: "text", value: value});
	    },

	    wrap: function() {
		var td = $("<td>");
		this.msg = $("<div>");
		td.append(this.msg);
		td.append(this.el);
		return td;
	    },

	    validate: function(value) {
		Base.validate.call(this, value);
		if (!this.visible || !this.editable) return;
		this.validateChange();
	    },

	    validateChange: function() {
		this.msg.text("[checking]");
		statusBar.setError("Validating changes", "validate");

		var self = this;

		this.data.set(this.name, this.get())
		    .done(function(txnValid) {
			self.msg.empty()
			self.updateStatus();
			statusBar.validationReady(txnValid);
			self.el.trigger("validated");

		    })
		    .fail(function(xhr) {
			dom.setText(self.msg, self.formatValidationError(xhr));
			self.setStatus("invalid");
			statusBar.validationReady(false);
		    });
	    },

	    get: function() {
		return this.editable ?
		    (this.field.val() || null) : this.data.get(this.name);
	    }
	});
    }
);