Correct way to create custom widget
Raphael-johanne opened this issue · comments
Hi,
i would like add a custom widget for my forms without to override form module; it is for a file/image overview field.
I found #48 but it seems to be not usesable yet.
I found also this #158 but I want to create a fully new widget, as image tag.
Is there some documentation to create custom widget properly ?
Where could I find some examples ?
Thank in advance !
Per #158 (comment) - a widget is just a function. That comment contains an example of how to create a custom widget. If you don't want to depend on existing widgets, you can look at their code, and replicate what they do.
Hi,
var email = require('forms/lib/widgets/email');
function customWidget(options) {
var w = email(options);
var originalHTML = w.toHTML;
w.toHTML = function (name, f) {
var html = originalHTML(name, f);
return html + '<span>custom</span>';
};
return w;
}
What is var email = require('forms/lib/widgets/email'); ? 'forms/lib/widgets/email' does not exist.
Furthermore, i don't want to create an email field, but an img field.
Thanks in advance !
oops, the require is incorrect there - it should point to https://github.com/caolan/forms/blob/master/lib/widgets.js#L47 - ie, require('forms/lib/widgets').email
Hi,
thank you for answer. I did it by this way :
// in mynodemodule/forms/widgets/widgets.js
var tag = require('forms/lib/tag');
exports.media = function (options) {
var opt = options || {};
var w = {
classes: opt.classes || options
};
w.toHTML = function (name, field) {
var f = field || {};
var attrs = {
'src': '/media/get/' + f.value, // specific route to treat secure media files
classes: w.classes,
height:100,
width : 100
};
var imgHTML = tag('img', [attrs, [], w.attrs || {}], opt.content);
return imgHTML;
};
return w;
};
// in mymodule/form.js
...
var customWigets = require('./widgets/widgets.js');
...
Form.prototype.getFields = function() {
...
field.widget = customWigets.media();
...
};
It is only an img tag to show an image on the server but it works !
Many thanks !
np! if you think the documentation could be improved, pull requests are always welcome!
Hi,
With pleasure, is that my method the good way to create custom widget ? If it is, I will push some documentation to do it.
I think that seems reasonable, yes.