Nxdom Framework

Nusantara eXtreme Development Object Model — dokumentasi resmi

NexaForm Basics

Panduan lengkap membuat form dengan validasi, dropdown, dan file upload menggunakan NexaForm.

NexaForm · createForm() · Tested

Contoh Lengkap: Form dengan File Upload

Contoh ini menunjukkan implementasi form lengkap dengan validasi, dropdown kategori, dan file upload. Contoh ini sudah tested dan working

Live Example: Lihat implementasi lengkap di:
  • Controller: controllers/Frontend/ExampleController.php
  • Template: templates/theme/example/index.html
  • Route: /example (auto-routing)

1. Controller - Method index()

Method index() menampilkan form dan initialize data:

public function index(array $params = []): void { // Data kategori untuk dropdown $categoryOptions = [ ['value' => '1', 'label' => 'Teknologi'], ['value' => '2', 'label' => 'Bisnis'], ['value' => '3', 'label' => 'Pendidikan'], ['value' => '4', 'label' => 'Kesehatan'], ]; // Initialize empty values untuk form $this->setData([ 'page_title' => 'Form Basics Example', 'success_message' => '', 'informasi' => '', 'title' => '', 'category' => '', 'content' => '', 'image_info' => '', 'action' => '/example/add' ]); // Restore form state jika ada error $formState = $this->getState('form_example', []); // Handle SELECT - set selected berdasarkan formState $category = $formState['category'] ?? ''; foreach ($categoryOptions as &$option) selected unset($option); // Assign category options untuk select $this->assignBlock('categories', $categoryOptions); // Assign ke template jika ada error if (!empty($formState)) { $this->nexaVars($formState); } // Clear form state setelah ditampilkan $this->clearState('form_example'); }

2. Controller - Method add()

Method add() memproses form submission:

public function add(array $params = []): void { // Setup form dengan validasi $form = $this->createForm() ->fields([ 'title' => 'Name|3|Judul minimal 3 karakter', 'category' => 'Name|1|Kategori wajib dipilih', 'content' => 'Name|10|Konten minimal 10 karakter', 'image' => 'FileOptional|null|Upload file jika diperlukan' ]) ->setUpload([ 'maxSize' => '2MB', 'allowedExtensions' => ['jpg', 'jpeg', 'png', 'gif'] ]) ->setSuccess('Data berhasil disimpan!') ->setError('Mohon perbaiki kesalahan berikut!'); // Proses form $result = $form->process(); // Jika SUKSES if ($result['success']) { // TODO: Simpan ke database // $this->useModels('Article', 'create', [$result['data']]); // Prepare response dengan field yang DIBERSIHKAN $clearValues = true; $templateVars = $form->Response($result, $clearValues); // Tambahkan pesan sukses dan HAPUS informasi "file" $templateVars['success_message'] = 'Data berhasil disimpan!'; $templateVars['informasi'] = ''; // Clear informasi field // Simpan state untuk ditampilkan pesan sukses $this->setState('form_example', $templateVars); // Redirect ke halaman index $this->redirect('/example'); } // Jika GAGAL validasi else { // Prepare response dengan field yang TIDAK DIKOSONGKAN $clearValues = false; $templateVars = $form->Response($result, $clearValues); // Simpan state error $this->setState('form_example', $templateVars); // Redirect kembali ke halaman index $this->redirect('/example'); } }

3. Template HTML

Template form dengan Bootstrap classes:

<div class="container mt-5"> <div class="card shadow-lg"> <div class="card-header bg-primary text-white"> <h2>Form Basics Example</h2> </div> <div class="card-body"> <form method="POST" action="{action}" enctype="multipart/form-data"> <!-- Field: Title --> <div class="form-group mb-3"> <label for="title">Judul Artikel *</label> <input type="text" name="title" id="title" value="{title}" class="form-control " placeholder="Masukkan judul artikel" > <small class="form-text text-muted">Minimal 3 karakter</small> </div> <!-- Field: Category (Dropdown) --> <div class="form-group mb-3"> <label for="category">Kategori *</label> <select name="category" id="category" class="form-control " > <option value="">-- Pilih Kategori --</option> <!-- NEXA categories --> <option value="{value}" {selected}>{label}</option> <!-- END categories --> </select> </div> <!-- Field: Content (Textarea) --> <div class="form-group mb-3"> <label for="content">Konten Artikel *</label> <textarea name="content" id="content" class="form-control " rows="5" placeholder="Tulis konten artikel di sini..." >{content}</textarea> <small class="form-text text-muted">Minimal 10 karakter</small> </div> <!-- Field: Image (File Upload) --> <div class="form-group mb-3"> <label for="image">Gambar (Opsional)</label> <input type="file" name="image" id="image" class="form-control " accept="image/jpeg,image/jpg,image/png,image/gif" > <small class="form-text text-muted">Format: JPG, JPEG, PNG, GIF. Maksimal 2MB</small> </div> <button type="submit" class="btn btn-primary btn-lg"> Simpan Data </button> </form> </div> </div> </div>

🔑 Konsep Penting

1. Dua Method Pattern

  • index() - Menampilkan form dan restore state
  • add() - Memproses form submission

2. State Management

  • setState() - Simpan data untuk redirect
  • getState() - Ambil data setelah redirect
  • clearState() - Hapus state setelah ditampilkan

3. Response Method

  • Response($result, true) - Clear values (untuk sukses)
  • Response($result, false) - Keep values (untuk error)

4. Template Variables

  • {title}, {category}, {content} - Field values
  • {errors_title}, {errors_category} - Error messages
  • {informasi} - Info message (harus di-clear saat sukses!)
  • {success_message} - Success message

Format Validasi

NexaForm menggunakan Format OLD yang sederhana:

// Format: 'ValidationFunction|Parameter|ErrorMessage' 'title' => 'Name|3|Judul minimal 3 karakter', 'category' => 'Name|1|Kategori wajib dipilih', 'content' => 'Name|10|Konten minimal 10 karakter', 'email' => 'Email|null|Email harus valid', 'image' => 'FileOptional|null|Upload file jika diperlukan'

Validation Functions:

  • Name - Text input (min length)
  • Email - Email validation
  • FileOptional - Optional file upload

File Upload Configuration

Format setUpload() yang BENAR:

->setUpload([ 'maxSize' => '2MB', // String format 'allowedExtensions' => ['jpg', 'jpeg', 'png', 'gif'] // Array ])
PENTING:
  • Gunakan 'maxSize' (camelCase), bukan 'max_size'
  • Gunakan 'allowedExtensions', bukan 'allowed_types'
  • Format size: '2MB', '5MB', '10MB'

🐛 Bug Fix: Field informasi

Field informasi otomatis diset ke "file" oleh NexaForm ketika ada file upload. Ini harus di-clear manual saat sukses:

// Jika SUKSES if ($result['success']) { $templateVars = $form->Response($result, true); // PENTING: Clear informasi field $templateVars['informasi'] = ''; // ← Ini wajib! $this->setState('form_example', $templateVars); $this->redirect('/example'); }

Testing Results

Form ini sudah di-test dan bekerja dengan baik:

  • Validasi error: "Konten minimal 10 karakter" - WORKING
  • Upload file 1.32 MB PNG - SUCCESS
  • Upload file 1.79 MB PNG - SUCCESS
  • Dropdown kategori - WORKING
  • Form state restore setelah error - WORKING
  • Redirect setelah sukses - WORKING
Log File: Lihat system/log/form_debug.log untuk detail testing

Lanjut

Sebelumnya: Forms. Berikutnya: Validasi form. Indeks Forms · Dokumentasi · Beranda.