# 3.4 Understanding the Data Model (and Page Data Model UI)

In this final section of core concepts, you'll master the **Page Data Model** - the foundation of how your BetterForms pages store, display, and manipulate data.

## What is the Page Data Model?

The **Data Model** is a JSON structure that stores all data accessible to the current page. Think of it as the "variables" or "fields" available to your page - similar to how FileMaker fields store data, but more flexible.

**Key Characteristics:**

* **JSON Format:** All data is stored as a JSON object
* **Page-Specific:** Each page has its own data model
* **Dynamic:** Data can change through user interactions and hooks
* **Bindable:** Page elements connect to specific data model keys

### Simple Data Model Example

```json
{
  "user": {
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com"
  },
  "preferences": {
    "theme": "dark",
    "notifications": true
  }
}
```

## How Data Binding Works

Data binding connects page elements to your data model using the `model` property.

### Input Field Example

**Data Model:**

```json
{
  "user": {
    "firstName": ""
  }
}
```

**Page Element:**

```json
{
  "type": "input",
  "label": "First Name",
  "model": "user.firstName",
  "inputType": "text"
}
```

**Result:** The input field displays and updates the `user.firstName` value in real-time.

### HTML Display Example

You can also display data in HTML elements:

```html
<h1>Welcome, {{model.user.firstName}}!</h1>
<p>Your email is: {{model.user.email}}</p>
```

## Where to Find Data Model in the BetterForms IDE

### Data Model Tab (Primary Interface)

1. **Open any Page** in the BetterForms IDE
2. **Navigate to the Data Model tab**
3. **Two main sections available:**

| **Section**                | **Purpose**                              | **When Used**                                                    |
| -------------------------- | ---------------------------------------- | ---------------------------------------------------------------- |
| **Default Data Model**     | Production data loaded when page renders | Live application data sent to FileMaker via `onFormRequest` hook |
| **Development Data Model** | Mock data for IDE testing                | Preview and development in BetterForms IDE only                  |

### Page Builder Integration

The **Page Builder** tab works hand-in-hand with your data model:

1. **Schema Editor** - Define elements that bind to data model keys
2. **Real-time Preview** - See how your data model affects page rendering
3. **Snippets** - Use "HTML - Data Model Inspector" to debug data

**Data Model Inspector Snippet:**

```json
{
  "type": "html",
  "label": "Data Model Inspector",
  "html": "<pre>{{model}}</pre>",
  "styleClasses": "col-md-12"
}
```

## Data Model Lifecycle

Understanding when and how data flows is crucial:

### 1. Page Load

* **Default Data Model** loads first
* **onFormRequest Hook** (if enabled) can override with FileMaker data
* **Development Data Model** merges for IDE previews only

### 2. User Interaction

* Input fields update data model in real-time
* Changes are reflected immediately in bound elements
* No automatic saving - requires explicit actions

### 3. Data Persistence

* Use `runUtilityHook` action to send data to FileMaker
* FileMaker scripts receive the current data model
* Server can modify and return updated data

## Development vs Production Data

### Development Data Model

**Purpose:** Testing and development without affecting live data

**Features:**

* **IDE Only:** Never sent to FileMaker server
* **Merged with Default:** Combines with default data during previews
* **Caching:** Can be synced across IDE sessions

**Example Use Cases:**

```json
{
  "user": {
    "firstName": "Test User",
    "lastName": "Developer",
    "role": "admin"
  },
  "debugMode": true
}
```

### Default Data Model (Production)

**Purpose:** Real application data used in live environment

**Features:**

* **FileMaker Integration:** Sent to `onFormRequest` hook
* **User Data:** Updated through page interactions
* **Persistence:** Saved via `runUtilityHook` actions

## Data Model Best Practices

### 1. Structure Your Data Logically

**Good:**

```json
{
  "user": {
    "personal": { "firstName": "", "lastName": "" },
    "contact": { "email": "", "phone": "" }
  },
  "settings": { "theme": "light", "notifications": true }
}
```

**Avoid:**

```json
{
  "firstName": "",
  "lastName": "",
  "email": "",
  "phone": "",
  "theme": "",
  "notifications": ""
}
```

### 2. Use Meaningful Key Names

* Use `user.firstName` instead of `fn`
* Use `invoice.items` instead of `data`
* Be consistent with naming conventions

### 3. Plan for FileMaker Integration

Structure your data model to match how FileMaker will process it:

```json
{
  "record": {
    "id": "",
    "name": "",
    "created": ""
  },
  "metadata": {
    "lastModified": "",
    "version": ""
  }
}
```

## Common Data Model Patterns

### Master-Detail Pattern

```json
{
  "invoice": {
    "id": "INV-001",
    "customer": "Acme Corp",
    "total": 0
  },
  "lineItems": [
    { "product": "Widget A", "qty": 2, "price": 10.00 },
    { "product": "Widget B", "qty": 1, "price": 15.00 }
  ]
}
```

### Form Wizard Pattern

```json
{
  "step1": { "personal": { "firstName": "", "lastName": "" }},
  "step2": { "contact": { "email": "", "phone": "" }},
  "step3": { "preferences": { "newsletter": false }},
  "wizardState": { "currentStep": 1, "completed": false }
}
```

## Troubleshooting Data Model Issues

### Data Not Displaying

1. **Check binding:** Verify `model` property matches data structure
2. **Inspect with HTML:** Use Data Model Inspector snippet
3. **Check console:** Look for JavaScript errors

### Data Not Saving

1. **Verify hook configuration:** Ensure `runUtilityHook` action is configured
2. **Check FileMaker script:** Verify script receives `$$BF_Model` correctly
3. **Test locally:** Use Helper File "Run Hook" button

## Next Steps

Congratulations! You now understand all three core BetterForms concepts:

✅ **Hooks** - Connect to FileMaker scripts\
✅ **Actions** - Control application behavior\
✅ **Data Model** - Manage page data and binding

**Ready to build:** You can now create sophisticated BetterForms applications with confidence.

**What's next:** Explore [Common Customizations](https://github.com/DelfsEngineering/fm-betterforms/blob/master/getting-started/ide-quick-tour/4.-common-customizations-and-expanding-your-app) to learn practical implementation patterns.

{% hint style="info" %}
**Pro Tip:** The Data Model Inspector is your best friend for debugging. Add it to any page when troubleshooting data flow issues.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.klai.studio/getting-started/ide-quick-tour/3.-understanding-core-betterforms-concepts/3.4-understanding-the-data-model-and-page-data-model-ui.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
