Advanced
You can easly get a form more reactive using hook preprocess.
Preprocess
import { createSignal, Show } from "solid-js";
import { Formly, IValue, IField } from "solid-formly";
const form_name = "formly_calculator";
const fields: IField[] = [
{
type: "input",
name: "number_a",
attributes: {
type: "number",
id: "number_a",
label: "Number A",
},
rules: ["required"],
},
{
type: "input",
name: "number_b",
attributes: {
type: "number",
id: "number_b",
label: "Number B",
},
rules: ["required"],
},
{
type: "input",
name: "total",
attributes: {
id: "total",
type: "number",
label: "Total = Number A + Number B",
},
preprocess: (field: IField, fields: IField[], values: any) => {
if (values.touched === "number_a" || values.touched === "number_b") {
field.value = parseInt(values.number_a) + parseInt(values.number_b);
}
return field;
},
},
];
const Form = () => {
return (
<Formly
form_name={form_name}
fields={fields}
onSubmit={onSubmit}
/>
);
};
export default Form;
here solid-formly fetch data type from jsonplaceholder by value category
fetch: done!
import { createSignal } from "solid-js";
import { Formly, IValue, IField } from "solid-formly";
const Form = () => {
const [loading, setLoading] = createSignal<boolean>(false);
// Fetch Users
const fetchUsers = async () => {
const res = await fetch(
"https://jsonplaceholder.cypress.io/users?_limit=10"
);
const data = await res.json();
return data.map((item) => ({ value: item.id, title: item.name }));
};
// Fetch posts
const fetchPosts = async () => {
const res = await fetch(
"https://jsonplaceholder.cypress.io/posts?_limit=10"
);
const data = await res.json();
return data.map((item) => ({ value: item.id, title: item.title }));
};
const onSubmit = (data: IValue) => {
console.log(data);
};
const fields: IField[] = [
{
type: "select",
name: "category",
attributes: {
id: "category",
label: "Category",
},
rules: ["required"],
extra: {
options: [
{
value: null,
title: "None",
},
{
value: 1,
title: "Users",
},
{
value: 2,
title: "Posts",
},
],
},
},
{
type: "select",
name: "items",
attributes: {
id: "items",
label: "Items",
},
extra: {},
preprocess: async (field: IField, fields: IField[], values: any) => {
if (values.touched === "category") {
setLoading(true);
field.extra.options =
values.category == 1 ? await fetchUsers() : await fetchPosts();
setLoading(false);
}
return field;
},
},
];
return (
<Formly
form_name={form_name}
fields={fields}
onSubmit={onSubmit}
/>
);
};
export default Form;