ErlangFormDocs v1.0
BasicArrays

Basic Array

Membuat array object dinamis.

Daftar Kontak

Kontak #1

Array memakai z.array(z.object(...)) untuk membuat daftar item yang bisa ditambah dan dihapus. Contoh ini dimulai dengan satu kontak.

Penggunaan

Simpan form.tsx dan schema.ts di folder yang sama.

"use client";

import { useForm } from "@tanstack/react-form";
import { ErlForm } from "erlangform";
import { schema, type FormValues } from "./schema";

export default function ContactsForm() {
  const form = useForm({
   defaultValues: {
      contacts: [
        {
          type: "personal",
          phone: "",
          active: true,
        },
      ],
    },
    validators: { onChange: schema },
    onSubmit: ({ value }) => console.log(value),
  });

  return (
     <form
          className="demo-form"
          onSubmit={(event) => {
            event.preventDefault();
            void form.handleSubmit();
          }}
        >
          <ErlForm<FormValues>
            form={form}
            schema={schema}
            fieldConfig={{
              contacts: {
                section: "Daftar Kontak",
                array: {
                  itemLabel: (_, index) => `Kontak #${index + 1}`,
                  addLabel: "+ Tambah Kontak Baru",
                  removeLabel: "Hapus Kontak",
                },
                type: {
                  label: () => "Tipe Kontak",
                  options: [
                    { label: "Personal", value: "personal" },
                    { label: "Perusahaan", value: "company" },
                  ],
                },
                phone: {
                  label: "Nomor Telepon",
                  placeholder: "0812xxxxxxxx",
                },
              },
            }}
            sectionConfig={{
              contacts: {
                title: "Daftar Kontak",
              },
            }}
          />
          <button type="submit" className="demo-button">Simpan</button>
        </form>
  );
}

fieldConfig.contacts.array mengatur label item dan tombol tambah/hapus. Untuk array di dalam array, lanjutkan ke Nested Array.

On this page