如何从数据库加载FormKit模式并使用Laravel – Inertia js和Vue 3生成表单

huangapple go评论58阅读模式
英文:

How to load from database FormKit schema and generate form using Laravel - Inertia js ans Vue 3

问题

const schema = JSON.parse(props.form.json_schema)
英文:

here is my goal: I have a simple form for testing purpose. I defined and saved to database the Formkit schema definition and I want to load it from the db and generate the form on the page. This is the simple schema:

[
    {
        $formkit: 'email',
        label: 'Email address',
        validation: 'required'
    },
  {
    $formkit: 'select',
    name: 'role',
    label: 'Ruolo',
    options: {
      sa: 'Super Admin',
      manager: 'Manager',
      user: 'User'
    },
    help: 'Insert your job role?'
    validation: 'required'
  }
]

I want to load this schema from db and preview it in a page.

In my Laravel controller:

public function preview(Form $form) {
    return Inertia::render('Forms/Anteprima', [
        'form' => $form
    ]);
}

Then the Anteprima.vue file

<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import PortalMenu from '@/Components/PortalMenu.vue';
import { Head, Link } from '@inertiajs/vue3';
import '@formkit/themes/genesis'

const props = defineProps({
    form: Array
})

const schema = JSON.parse(props.form.json_schema)
// const schema = [
//     {
//         $formkit: 'email',
//         label: 'Email address',
//         validation: 'required'
//     },
//   {
//     $formkit: 'select',
//     name: 'ruolo',
//     label: 'Ruolo',
//     options: {
//       sa: 'Super Admin',
//       manager: 'Editor',
//       user: 'User'
//     },
//     help: 'Insert your job role?',
//     validation: 'required'
//   }
// ]


const inviaForm = async (fields) => {
    await new Promise((r) => setTimeout(r, 1000))
    alert(JSON.stringify(fields))
    console.log(fields)
}
</script>

<template>
    <Head title="Form schema sample"></Head>

    <AuthenticatedLayout>
        <template v-slot:navigation><PortalMenu /></template>
        <template v-slot:header><div class="pb-3"><h2>Form preview: {{ form.name }}</h2></div></template>

        <div class="row">
            <FormKit type="form" @submit="inviaForm" submit-label="Invia modulo">
                <FormKitSchema :schema="schema" />
            </FormKit>
        </div>
        
    </AuthenticatedLayout>
</template>

If I uncomment the "local" definition of the schema it works, but if I use the string passed from the db I'm not able to get it.
I tried in different ways: with JSON.parse I get an error about json structure, if I remove JSON.parse it shows the json schema string on the page and not the form. I tried also removing "[" and "]" from the db without success.

答案1

得分: -2

根据您提供的代码,看起来您正在将模式作为 JSON 字符串从数据库传递给 Anteprima.vue 组件。为了在组件中使用模式,您需要将 JSON 字符串解析为实际的 JavaScript 对象。

以下是您的代码的更新版本,应该可以正常工作:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->
<script setup>
import { defineProps } from 'vue';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import PortalMenu from '@/Components/PortalMenu.vue';
import { Head, Link } from '@inertiajs/vue3';
import '@formkit/themes/genesis';

const props = defineProps({
  form: Object // 假设 'form' 是 props 中的一个对象
});

const schema = JSON.parse(props.form.json_schema);

const inviaForm = async (fields) => {
  await new Promise((r) => setTimeout(r, 1000));
  alert(JSON.stringify(fields));
  console.log(fields);
};
</script>

<template>
  <Head title="Form schema sample" />

  <AuthenticatedLayout>
    <template v-slot:navigation><PortalMenu /></template>
    <template v-slot:header><div class="pb-3"><h2>Form preview: {{ form.name }}</h2></div></template>

    <div class="row">
      <FormKit type="form" @submit="inviaForm" submit-label="Invia modulo">
        <FormKitSchema :schema="schema" />
      </FormKit>
    </div>
  </AuthenticatedLayout>
</template>
<!-- end snippet -->

请确保来自数据库的 form 对象的 json_schema 属性包含一个有效的 JSON 字符串,如果数据库中的 json_schema 字段包含方括号 [ ],则在解析 JSON 字符串之前应将它们删除。

使用此代码,JSON 字符串应该能够正确解析,表单应该基于从数据库检索的模式生成。

英文:

Based on the code you provided, it seems like you're passing the schema as a JSON string from the database to the Anteprima.vue component. In order to use the schema in the component, you'll need to parse the JSON string into an actual JavaScript object.

Here's an updated version of your code that should work:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;script setup&gt;
import { defineProps } from &#39;vue&#39;;
import AuthenticatedLayout from &#39;@/Layouts/AuthenticatedLayout.vue&#39;;
import PortalMenu from &#39;@/Components/PortalMenu.vue&#39;;
import { Head, Link } from &#39;@inertiajs/vue3&#39;;
import &#39;@formkit/themes/genesis&#39;;

const props = defineProps({
  form: Object // Assuming &#39;form&#39; is an object in the props
});

const schema = JSON.parse(props.form.json_schema);

const inviaForm = async (fields) =&gt; {
  await new Promise((r) =&gt; setTimeout(r, 1000));
  alert(JSON.stringify(fields));
  console.log(fields);
};
&lt;/script&gt;

&lt;template&gt;
  &lt;Head title=&quot;Form schema sample&quot; /&gt;

  &lt;AuthenticatedLayout&gt;
    &lt;template v-slot:navigation&gt;&lt;PortalMenu /&gt;&lt;/template&gt;
    &lt;template v-slot:header&gt;&lt;div class=&quot;pb-3&quot;&gt;&lt;h2&gt;Form preview: {{ form.name }}&lt;/h2&gt;&lt;/div&gt;&lt;/template&gt;

    &lt;div class=&quot;row&quot;&gt;
      &lt;FormKit type=&quot;form&quot; @submit=&quot;inviaForm&quot; submit-label=&quot;Invia modulo&quot;&gt;
        &lt;FormKitSchema :schema=&quot;schema&quot; /&gt;
      &lt;/FormKit&gt;
    &lt;/div&gt;
  &lt;/AuthenticatedLayout&gt;
&lt;/template&gt;

<!-- end snippet -->

Make sure that the json_schema property of the form object from the database contains a valid JSON string representing the schema. If the json_schema field in the database includes square brackets [ ], you should remove them before parsing the JSON string.

With this code, the JSON string should be parsed correctly, and the form should be generated based on the schema retrieved from the database.

huangapple
  • 本文由 发表于 2023年6月8日 17:49:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定