Reputation: 368
i've followed formio docs to create custom component but i'm just a beginner so i can't get it work. i want to create custom component to achieve this page
i want to create custom component like add new card which you can choose the children of that card, such as video, or images, inputs etc. basically i want to achieve google forms builder i found formio is the best choice for form builder but i got stuck with this custom component. i heard someone have finally create custom component here in stackoverflow, i also ask them in their question. So, anyone can help me with this? maybe you have source code for me to follow, or anything, really appreciate any help
Upvotes: 3
Views: 5066
Reputation: 415
I've been doing this successfully for a while.
First, find an existing component in Formio that does something close to what you want. If your new element just presents something non-interactive, then you an go with an 'HTML' component.
This is the code you need:
var htmlComponent = Formio.Components.components.htmlelement; // or whatever
class MyNewComponent extends htmlComponent{
static schema(...extend) {
return super.schema({
type: 'MyNewComponent',
label: "The Default Label",
any_other_fields: "",
}, ...extend);
static get builderInfo() {
return {
title: 'Name in the Builder',
group: 'custom',
icon: 'picture-o',
weight: 5,
schema: this.schema()
};
}
render(element) {
// Here's where you add your HTML to get put up.
//
tpl += "<div ref='myref'>Hi there!</div>";
// Note the use of the 'ref' tag, which is used later to find
// parts of your rendered element.
// If you need to render the superclass,
// you can do that with
// tpl+=super.render(element);
// This wraps your template to give it the standard label and bulider decorations
return Formio.Components.components.component.prototype.render.call(this,tpl);
}
attach(element) {
// This code is called after rendering, when the DOM has been created.
// You can find your elements above like this:
this.loadRefs(element, {myref: 'single'});
var superattach = super.attach(element);
// Here do whatever you need to attach event handlers to the dom.
this.refs.myref.on('click',()=>{alert("hi!");});
return superattach;
}
getvalue() {
return 3; // the value this element puts into the form
}
// OR, depending on which component type you're basing on:
getValueAt(index,value,flags) {}
setValue(value) {
// modify your DOM here to reflect that the value should be 'value'.
};
// OR, depending on what component type:
getValueAt(index) {}
}
// This sets the form that pops up in the Builder when you create
// one of these. It is basically just a standard form, and you
// can look at the contents of this in the debugger.
MyNewComponent.editForm = htmlComponent.editForm;
// Register your component to Formio
Formio.Components.addComponent('MyNewComponent', MyNewComponent);
This was hard-won knowledge; hope it helps someone else.
Upvotes: 4