Sign up
Login
New
Trending
Archive
English
English
Sign up
Login
New Paste
Add Image
<script> window.DynamicSchemaForm = { template: ` <v-form ref="form" class="pa-4"> <v-card v-for="(group, gIdx) in groups" :key="gIdx" v-if="groups.length" class="mb-4" variant="outlined" style="border-color: rgba(var(--v-theme-primary),0.3)" > <v-card-title class="text-subtitle-1 text-primary font-weight-bold"> {{ group.title }} </v-card-title> <v-card-text> <v-row dense> <v-col v-for="field in group.fields" :key="group.title + '_' + field" cols="12" > <component :is="resolveComponent(group.schema.properties?.[field])" v-model="model[group.title][field]" :label="fieldLabel(group, field)" :items="getEnumOptions(group.schema.properties[field])" :type="inputType(group.schema.properties[field])" :placeholder="group.schema.properties[field]['ui:placeholder']" :error-messages="ajvErrors[group.title]?.[field]" variant="filled" density="compact" hide-details="auto" class="mb-2" /> </v-col> </v-row> </v-card-text> </v-card> <v-row justify="end" class="mt-4" dense> <v-btn variant="outlined" color="grey" size="small" class="mr-2" @click="resetForm" > RESET </v-btn> <v-btn color="primary" size="small" class="px-6" @click="submit" > INVIA DATI </v-btn> </v-row> </v-form> `, props: ['msg'], data() { return { schemas: [], groups: [], model: {}, validators: {}, ajvErrors: {}, ajv: null } }, mounted() { this.loadAjv() }, watch: { msg: { handler(v) { if (v?.payload?.properties) { this.schemas = [v.payload] this.prepareSchemas() } else if (Array.isArray(v?.payload)) { this.schemas = v.payload this.prepareSchemas() } else if (v?.payload) { this.applyIncomingPayload(v.payload) } }, immediate: true, deep: true } }, methods: { loadAjv() { if (window.Ajv) { this.initAjv() return } const s = document.createElement('script') s.src = "/ajv.min.js" s.onload = () => { console.log("AJV caricato") this.initAjv() } s.onerror = () => { console.error("Errore caricamento AJV") } document.head.appendChild(s) }, initAjv() { this.ajv = new window.Ajv({ allErrors: true, strict: false }) this.ajv.addFormat( "email", /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i ) if (this.schemas.length > 0) { this.prepareSchemas() } }, prepareSchemas() { this.groups = [] this.validators = {} this.ajvErrors = {} const newModel = {} this.schemas.forEach(s => { const schemaTitle = s.title || "Schema" // 🔹 usa gruppi se presenti const schemaGroups = s["ui:groups"] || [{ title: schemaTitle, fields: Object.keys(s.properties || {}) }] // 🔹 crea gruppi reali schemaGroups.forEach(g => { this.groups.push({ title: g.title, fields: g.fields, schema: s }) // init model per gruppo if (!newModel[g.title]) newModel[g.title] = {} g.fields.forEach(f => { const p = s.properties[f] newModel[g.title][f] = p?.type === 'boolean' ? (p.default ?? false) : (p.default ?? "") }) }) // 🔹 validator per schema if (this.ajv) { this.validators[schemaTitle] = this.ajv.compile(s) } }) // Vue reactivity safe this.model = Object.assign({}, newModel) }, validate() { let okAll = true; const errs = {}; // 1. Crea un payload globale unificando tutti i gruppi per ogni schema const globalDataBySchema = {}; this.groups.forEach(g => { const schemaTitle = g.schema.title || "Schema"; if (!globalDataBySchema[schemaTitle]) globalDataBySchema[schemaTitle] = {}; // Unisce i dati del gruppo nel contenitore dello schema globale Object.assign(globalDataBySchema[schemaTitle], this.model[g.title]); }); // 2. Valida il payload unificato contro lo schema this.groups.forEach(g => { const schemaTitle = g.schema.title || "Schema"; const v = this.validators[schemaTitle]; // Applichiamo il casting e la validazione sul set di dati COMPLETO dello schema const fullData = this.castPayload(g.schema, globalDataBySchema[schemaTitle]); const ok = v(fullData); errs[g.title] = {}; if (!ok && Array.isArray(v.errors)) { v.errors.forEach(e => { let path = e.instancePath || e.dataPath || ""; let f = path.replace(/^\//,'').replace(/^\./,''); if (e.keyword === 'required') f = e.params.missingProperty; // Assegna l'errore al gruppo solo se quel campo appartiene a quel gruppo if (f && g.fields.includes(f)) { errs[g.title][f] = this.humanMessage(e); } }); } if (!ok) { // Controlla se gli errori appartengono effettivamente a questo gruppo const hasLocalErrors = v.errors.some(e => { let f = (e.keyword === 'required') ? e.params.missingProperty : (e.instancePath || "").replace('/',''); return g.fields.includes(f); }); if (hasLocalErrors) okAll = false; } }); this.ajvErrors = errs; return okAll; }, castPayload(schema, data) { const o = {} Object.entries(data).forEach(([k,v]) => { const p = schema.properties[k] const t = p?.type const isReq = schema.required?.includes(k) // 🔥 required vuoto → NON inserire if (isReq && (v === "" || v === null || v === undefined)) { return } if (p?.format === 'date-time') { // input datetime-local: YYYY-MM-DDTHH:mm if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(v)) { // aggiunge secondi + timezone UTC o[k] = v + ":00Z" } else { o[k] = v } return } // opzionale vuoto → NON inserire if (!isReq && (v === "" || v === null || v === undefined)) { return } if (t === 'integer' || t === 'number') { const n = Number(v) o[k] = isNaN(n) ? v : n } else o[k] = v }) return o }, humanMessage(e) { if (e.keyword === 'required') return "Campo obbligatorio" if (e.keyword === 'minLength') return `Min ${e.params.limit}` if (e.keyword === 'maximum') return `Max ${e.params.limit}` if (e.keyword === 'format' && e.params.format === 'email') return "Email non valida" return e.message || "Valore non valido" }, submit() { if (!this.validate()) return const result = {} this.groups.forEach(g => { const schema = g.schema const groupName = g.title const data = this.castPayload( schema, this.model[groupName] ) result[groupName] = data }) console.log("FINAL PAYLOAD:", result) if (this.send) this.send({ payload: result }) else this.$emit("submit", result) }, resetForm() { this.groups.forEach(g => { Object.entries(g.schema.properties).forEach( ([k,p]) => { this.model[g.title][k] = p.type === 'boolean' ? (p.default ?? false) : (p.default ?? "") } ) }) this.ajvErrors = {} }, applyIncomingPayload(payload) { this.groups.forEach(g => { const d = payload[g.title] if (!d || !this.model[g.title]) return this.model[g.title] = { ...this.model[g.title], ...d } }) }, resolveComponent(f) { if (f?.enum) return 'v-select' if (f?.type === 'boolean') return 'v-switch' return 'v-text-field' }, inputType(f) { if (f?.["ui:widget"] === "password") return "password" if (f?.["ui:widget"] === "email") return "email" if (f?.format === 'date-time') return "datetime-local" if (f?.type === 'number') return "number" return 'text' }, getEnumOptions(f) { if (!f?.enum) return [] return f.enum.map((v,i)=>({ title: f.enumNames?.[i] ?? v, value: v })) }, fieldLabel(group, name) { const p = group.schema.properties[name] const base = p?.title || name const req = group.schema.required?.includes(name) return req ? `${base} *` : base } } } </script> <!-- Script per registrare il componente nella Dashboard 2.0 --> <script> // Usa una IIFE (Immediately Invoked Function Expression) per evitare conflitti di scope (function() { // Accedi all'istanza Vue principale della Dashboard 2.0 tramite window.NodeRED.dashboard.app const app = window.NodeRED.dashboard.app; if (app) { // Registra il tuo oggetto JavaScript come un componente Vue utilizzabile tramite il tag <dynamic-schema-form> app.component('dynamic-schema-form', window.DynamicSchemaForm); } else { console.error("Istanza Dashboard 2.0 non trovata, registrazione componente fallita."); } })(); </script>
Settings
Title :
[Optional]
Paste Folder :
[Optional]
Select
Syntax :
[Optional]
Select
Markup
CSS
JavaScript
Bash
C
C#
C++
Java
JSON
Lua
Plaintext
C-like
ABAP
ActionScript
Ada
Apache Configuration
APL
AppleScript
Arduino
ARFF
AsciiDoc
6502 Assembly
ASP.NET (C#)
AutoHotKey
AutoIt
Basic
Batch
Bison
Brainfuck
Bro
CoffeeScript
Clojure
Crystal
Content-Security-Policy
CSS Extras
D
Dart
Diff
Django/Jinja2
Docker
Eiffel
Elixir
Elm
ERB
Erlang
F#
Flow
Fortran
GEDCOM
Gherkin
Git
GLSL
GameMaker Language
Go
GraphQL
Groovy
Haml
Handlebars
Haskell
Haxe
HTTP
HTTP Public-Key-Pins
HTTP Strict-Transport-Security
IchigoJam
Icon
Inform 7
INI
IO
J
Jolie
Julia
Keyman
Kotlin
LaTeX
Less
Liquid
Lisp
LiveScript
LOLCODE
Makefile
Markdown
Markup templating
MATLAB
MEL
Mizar
Monkey
N4JS
NASM
nginx
Nim
Nix
NSIS
Objective-C
OCaml
OpenCL
Oz
PARI/GP
Parser
Pascal
Perl
PHP
PHP Extras
PL/SQL
PowerShell
Processing
Prolog
.properties
Protocol Buffers
Pug
Puppet
Pure
Python
Q (kdb+ database)
Qore
R
React JSX
React TSX
Ren'py
Reason
reST (reStructuredText)
Rip
Roboconf
Ruby
Rust
SAS
Sass (Sass)
Sass (Scss)
Scala
Scheme
Smalltalk
Smarty
SQL
Soy (Closure Template)
Stylus
Swift
TAP
Tcl
Textile
Template Toolkit 2
Twig
TypeScript
VB.Net
Velocity
Verilog
VHDL
vim
Visual Basic
WebAssembly
Wiki markup
Xeora
Xojo (REALbasic)
XQuery
YAML
HTML
Expiration :
[Optional]
Never
Self Destroy
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Status :
[Optional]
Public
Unlisted
Private (members only)
Password :
[Optional]
Description:
[Optional]
Tags:
[Optional]
Encrypt Paste
(
?
)
Create Paste
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Site Languages
×
English