formio.js
formio.js copied to clipboard
Manipulating schema in Custom Component
Hi,
I am building a custom component on top of ContentComponent. I have mostly done, but got stuck on updating the schema. My code follows below:
import ImageComponentDisplay from './ImageComponent.edit.display';
import _ from 'lodash';
import NativePromise from 'native-promise-only';
const imageViewComponent = (_module) => {
const Formio = _module;
const ContentComponent = Formio.Components.components.content;
class ImageComponent extends ContentComponent {
static schema(...extend) {
return ContentComponent.schema(
{
label: 'Image upload',
type: 'imageComponent',
key: 'imageComponent',
},
...extend
);
}
static get builderInfo() {
return {
title: 'Image',
icon: 'terminal',
group: 'Field',
weight: 3,
documentation: '/userguide/#html-element-component',
schema: ImageComponent.schema({}),
};
}
attach(element) {
const addImgDimension = () => {
const imgWidth = parseInt(this.schema.width);
const imgHeight = parseInt(this.schema.height);
const $img = element.querySelector('img');
if ($img) {
if (imgWidth) {
$img.width = imgWidth;
}
if (imgHeight) {
$img.height = imgHeight;
}
}
const innerElement = element.querySelector('[ref="html"]').innerHTML;
if (this.refs.html) {
this.setContent(this.refs.html, innerElement);
}
new Promise((resolve) => {
if (_.has(this.schema, 'html')) {
setTimeout(() => {
this.schema.html = innerElement;
console.log(this.schema);
}, 800);
resolve();
}
});
};
const setAltAttr = () => {
const figCaption = element.querySelector('figcaption');
if (figCaption) {
figCaption.style.display = 'none';
const $img = element.querySelector('img');
const altText = figCaption.textContent.trim();
$img.setAttribute('alt', altText);
console.log(this);
this.schema.alt = altText;
}
};
addImgDimension();
setAltAttr();
this.on('change', () => {
addImgDimension();
setAltAttr();
});
return super.attach(element);
}
}
ImageComponent.editForm = () => {
return {
components: [
{
key: 'tabs',
type: 'tabs',
components: ImageComponentDisplay,
},
],
};
};
Formio.Components.addComponent('imageComponent', ImageComponent);
};
export default imageViewComponent;
Trying to update the schema JSON html on change of the custom component, with this.schema.html = innerElement;, but I am stuck here as it is not updating the schema. Can't understand what I'm doing wrong. Any help would be highly appreciated. Thanks
I hope I correctly understand what you're trying to do. Try this instead:
this.component.html = innerElement