apphouse
Version:
Component library for React that uses observable state management and theme-able components.
141 lines (100 loc) • 2.5 kB
Markdown
<img src="https://apphouse-storybook.web.app/assets/ApphouseLogo-bceaa309.svg" width="80px">
# Form
https://apphousedocs.web.app/classes/FormModel.html
Typescript models to keep track of form fields and form data. The **Forms** class keeps track of a collection of **Form**
## Form Interfaces
The form takes for id an enum
```
interface enum FormOptionId {
signUp = "signUp"
}
```
Define the interface for your form fields
```
interface Fields {
username: string;
password: string
}
```
Define the form options interface
```
interface FormOptions {}
```
Initialize the form
```
const form = new Form<FormOptionId, Fields, FormOptions><({
id: 'uniqueFormId',
title: 'Form title',
fields: {
username: "",
password: "",
},
});
```
Using the form
Example of a form with 2 fields, name and email.
```
const form = new Form({
id: FormOptions.signUp,
title: 'Form title',
fields: {
name: "",
email: ""
},
validations: {
email: (value: string) => {
// do email validation
return true if valid, return false if invalid
}
},
options: {}, // no options
required: ['name', 'email'], // both name and email fields are required
```
## Initial Values
To add initial values, simple initialize the form with pre-filled field values
```
fields: {
name: "John Doe",
email: "Johndoe@somehosting.com",
},
```
## Updating Values
To update form field value simply:
```
form.setValue('name', 'updatedName');
```
## Accessing form values
```
const name = form.getValue('name');
```
## Get all form data
To get current form data
```
const formData = form.data;
```
NOTE: Ensure your component is an observer as this value is computed value
## Check if Form is Valid
```
const canSubmitForm = form.isValid; // if true, form has all required fields filled and inputs have passed validation
```
# Handling Multiple forms
The 'Forms' Class keeps track of multiple forms where you can access them by the method get.
```
const forms = new Forms();
forms.init(form);
const userDataForm = forms.get('uniqueIdForm');
```
## Accessing Apphouse Forms
In this app, we use the Forms class and we save it in the AppStore.
To access any of the forms on an app built with apphouse app simply:
```
const { app } = useApphouse();
const { forms } = app;
const form = forms.get('formId');
```
To initialize a form in the app simply:
```
const { app } = useApphouse();
const { forms } = app;
forms.init(form);
```