owned this note
owned this note
Published
Linked with GitHub
# Making a FormApplication
###### tags: `module-tutorial` `foundry-vtt`
Our Module has an API for our data layer and we are injecting a button into an existing UI element. The last (large) piece of the puzzle is our new UI for interacting with ToDo lists.
To make this we'll need three things:
1. A [`FormApplication`](https://foundryvtt.wiki/en/development/guides/understanding-form-applications) subclass which gathers our data for a Template, and which handles the logic for interacting with that template.
2. A handlebars template which displays the information and controls that the FormApplication gathers/handles.
3. Styling, because what's the point if it's not pretty?
It's easiest to work in steps, so let's start by making a rough window which displays the current ToDos for the logged in user. We'll get around to adding and editing them next.
## I. FormApplication subclass
Foundry Core provides a rudimentary UI framework to make interacting with data via UI easier for itself and modules. The FormApplication class is the most suitable of the tools available to us for what we are looking at doing, and so we need to make our own subclass of it.
:::info
**Programming Concept: Subclass and Inheritance**
ES2020 (a fancy way to say 'modern javascript') classes have the ability to 'extend' other classes, ['inheriting'](https://developer.mozilla.org/en-US/docs/Glossary/Inheritance) the properties and methods from the other class.
There's a lot of nuance explained in detail in [other guides](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain), but in short if Class Foo extends Class Bar, all of Class Bar's methods and properties are available on Class Foo.
:::
```js=
class ToDoListConfig extends FormApplication {
}
```
### defaultOptions
First step in setting up our ToDoListConfig class is to give it some overrides to the FormApplication's `defaultOptions` [getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get).
```js=
static get defaultOptions() {
const defaults = super.defaultOptions;
const overrides = {
height: 'auto',
id: 'todo-list',
template: ToDoList.TEMPLATES.TODOLIST,
title: 'To Do List',
userId: game.userId,
};
const mergedOptions = foundry.utils.mergeObject(defaults, overrides);
return mergedOptions;
}
```
:::info
**Programming Concept: `super`**
Like everything else, there's nuance to this. You can think of `super` as "the parent class". In this example, we're getting the `defaultOptions` of the parent class (`FormApplication`) since we know there's some good stuff in there and we don't want to override all of it.
:::
We have some `options` we know our FormApplication should always have:
1. It should calculate its own height.
1. It has the id `todo-list`.
1. It uses the handlebars template we defined when we were Setting Up our module's `ToDoList` class.
1. It displays the title "To Do List."
Lastly, there is one additional option we are defining that is not one of the normal options for a FormApplication: `userId`. This is the userId whose ToDos we will display with this FormApplication. We are setting it by default to be the logged in user, but doing it this way leaves it possible to render a different user's ToDo List if we desire to later.
Additionally, we know we want all of the existing defaults from FormApplication, and we only want to override a the few we have defined.
> #### [mergeObject](https://foundryvtt.com/api/module-helpers.html#.mergeObject)
> This is a utility function that Foundry Core provides. It allows one to merge two objects like a zipper, with some logic about which definition should overwrite the other in the returned object.
### getData
Secondly, we need to override the `getData` method of our FormApplication to gather the data for our specific template. For our purposes, this is delightfully simple:
```js=
getData(options) {
return {
todos: ToDoListData.getToDosForUser(options.userId)
}
}
```
Notice how we're relying on the `userId` passed to `options` here. These options are the same options we defined the defaults for above. They also are the options passed to [`FormApplication#render`](https://foundryvtt.com/api/FormApplication.html#render)'s second argument.
And that's it! Now we need the `todo-list.hbs` template to display something.
## II. Handlebars Template
[Handlebars](https://handlebarsjs.com/) is the templating engine which powers all of the UI in Foundry Core. It is very simplistic in nature which makes it easy to pick up but sometimes hard to work with.
Our ToDo list needs to display two pieces of information for each ToDo: `title` and `isDone`. We're going to go super simple initially and make the whole thing an unordered list.
```hbs=
<ul>
{{#each todo-list}}
<li>{{label}} | Done: {{isDone}}</li>
{{/each}}
</ul>
```
### Test!
With our `ToDoListConfig` defined and our basic Template created, we should be able to see something in-foundry.
We need to manually call the [`render` method](https://foundryvtt.com/api/FormApplication.html#render) of an instance of `ToDoListConfig` for now since we haven't made our button work. We also need to give that render method an argument of `true` to force it to paint on the page.
```
new ToDoListConfig().render(true, { userId: game.userId })
```
Paste that on into your console and everything should work!
> ***Narrator:*** It did not work. Well I mean it kind of worked.
A window popped up but we also got a console error, so half credit?
### Debugging `Cannot set property 'onsubmit' of undefined`
:::danger
TypeError: An error occurred while rendering ToDoListConfig 27: Cannot set property 'onsubmit' of undefined
:::
This is a gotchya when using a FormApplication that is just something you have to know about. In the [documentation](https://foundryvtt.com/api/FormApplication.html) for FormApplication it details some of the assumptions the class makes, the second of which is:
> 2. The template used contains one (and only one) HTML form as it's outer-most element
Our outermost element is a `<ul>`, not a `<form>`.
Easy to fix, then lets refresh and try again.
```hbs=
<form>
<ul>
{{#each todo-list}}
<li>{{label}} | Done: {{isDone}}</li>
{{/each}}
</ul>
</form>
```
> ***Narrator:*** It still did not work.
### Debugging our Empty Window
#### Is our DOM there at all?
Open DevTools and inspect the popped up window with this tool:

When inspecting the DOM of our window, I see:
```
<section class="window-content">
<form>
<ul>
</ul>
</form>
</section>
```
The `section` element comes from Foundry Core and everything inside it is from our Template. So that's good, our template is taking effect and we can see our elements. Something must be wrong with our `#each`.
#### Is our handlebars getting the data we expect?
There's a number of [built-in helpers](https://handlebarsjs.com/guide/builtin-helpers.html) in handlebars. One of these is `{{log}}` which acts as a console.log.
Let's go ahead and put a one of those at the top of our template file to see what the data getting to the template looks like.
```hbs=
{{log 'todo-list-template' this}}
<form>
...
```

Ah. There's the problem. We are feeding the template the data in the form of `todos` (from our `ToDoListConfig#getData` method), but in our template, we expected to see `todo-list`.
Simple change to our template and now surely it will work (remember to take out the log).
```hbs
<ul>
{{#each todos}}
<li>{{label}} | Done: {{isDone}}</li>
{{/each}}
</ul>
```

Success!
## III. Adding buttons and inputs
Now that we have things displaying, let's add some buttons, inputs, and css classes to make things look more like our end-game.
```hbs
<form>
<ul class="todo-list flexcol">
{{#each todos}}
<li class="flexrow" data-todo-id="{{id}}">
<input type="checkbox" name="{{id}}.isDone" title="Mark Done" data-dtype="Boolean" {{checked isDone}} />
<input type="text" value="{{label}}" name="{{id}}.label" data-dtype="String" />
<button type="button" title="Delete To Do" data-action="delete" class="flex0 todo-list-icon-button">
<i class="fas fa-trash"></i>
</button>
</li>
{{/each}}
</ul>
<button type="button" data-action="create"><i class="fas fa-plus"></i> Add To Do</button>
</form>
```
### Styling
We'll use `flexrow` and `flexcol` as some more of those [built-in Foundry Core classes](https://foundryvtt.wiki/en/development/guides/builtin-css) to make things line up nicely.
Notice we're also re-using our `.todo-list-icon-button` style to make the button at the end have the same style as the one we injected into the Player List.
Here's the CSS to style those classes.
```css=
.todo-list {
padding: 0;
margin-top: 0;
gap: 1em;
}
.todo-list > li {
align-items: center;
gap: 0.5em;
}
```
### Functionality notes
#### How do the inputs know what value to display?
Simply put, we're telling them the values from the object populating the template (the one we defined in `ToDoListConfig#getData`).
- the checkbox input uses a built in helper `checked` to display the proper state of the ToDo based on the `isDone` property
- the label input uses `value="{{label}}"` to know what its contents should be
#### What's this `name` for?
When we make the inputs actually edit things, the `name` will be how we tell Foundry which property to edit. To make life easier for future us, we're setting this to be the `id` of the ToDo plus the property we're displaying/editing.
#### What are these custom data attributes for?
On the inputs, we define `data-dtype` to help Foundry know what kind of data to expect from this input. This isn't relevant right now but will be in our next step when we make this form actually do something.
On the buttons, we define `data-action` to help future us know what the button is supposed to do when clicked. This isn't something Foundry Core does for us, we'll be defining this behavior in the next step.
## IV. Localization in Handlebars
The keen eyed among you will have noticed that we have made a blunder. We've got hard-coded English language strings in our UI. If someone speaking a different language wanted to translate our module, they would have an exceptionally difficult time doing so.
Instead, we need to leverage Foundry's i18n implementation like we did while Injecting a Button. Foundry Core provides a Handlebars Helper for localization which makes this easy to do from inside a template.
Add these to our `languages/en.json` file so they're available. Don't forget to ensure your JSON is valid after adding these.
```json=
"add-todo": "Add To-Do",
"delete-todo": "Delete To-Do",
"mark-done": "Mark Done"
```
Next use the [`localize`](https://foundryvtt.com/api/HandlebarsHelpers.html#.localize) helper in our Handlebars Template instead of our hardcoded strings.
```hbs
<input ... title="{{localize "TODO-LIST.mark-done"}}"
// ...
<button ... title="{{localize "TODO-LIST.delete-todo"}}"
// ...
<button ... {{localize "TODO-LIST.add-todo"}}</button>
```
## V. Wrapping Up
If you've refreshed and tested this recently, you've seen that we're looking good. We have everything set up and ready for interactivty.

In this section we:
- Learned about FormApplications, Subclasses, and Inheritence in ES2020
- Set up our own `ToDoListConfig` subclass of `FormApplication` with:
- customized `defaultOptions`
- a `getData` method which populates the ToDos for a given user
- Created a Handlebars template which displays a list of ToDos
- Debugged why that template wasn't actually displaying anything initially
- Added some input elements, buttons, and localization to said template
<details>
<summary>Full ToDoListConfig class</summary>
```js=
class ToDoListConfig extends FormApplication {
static get defaultOptions() {
const defaults = super.defaultOptions;
const overrides = {
closeOnSubmit: false,
height: 'auto',
id: 'todo-list',
submitOnChange: true,
template: ToDoList.TEMPLATES.TODOLIST,
title: 'To Do List',
userId: game.userId,
};
const mergedOptions = foundry.utils.mergeObject(defaults, overrides);
return mergedOptions;
}
getData(options) {
return {
todos: ToDoListData.getToDosForUser(options.userId)
}
}
}
```
</details>
<details>
<summary>Full todo-list.hbs</summary>
```hbs=
<form>
<ul class="todo-list flexcol">
{{#each todos}}
<li class="flexrow" data-todo-id="{{id}}">
<input type="checkbox" name="{{id}}.isDone" title="{{localize "TODO-LIST.mark-done"}}" data-dtype="Boolean" {{checked isDone}} />
<input type="text" value="{{label}}" name="{{id}}.label" data-dtype="String" />
<button type="button" title="{{localize "TODO-LIST.delete-todo"}}" data-action="delete" class="flex0 todo-list-icon-button">
<i class="fas fa-trash"></i>
</button>
</li>
{{/each}}
</ul>
<button type="button" data-action="create"><i class="fas fa-plus"></i> {{localize "TODO-LIST.add-todo"}}</button>
</form>
```
</details>
<details>
<summary>Full en.json</summary>
```json=
{
"TODO-LIST": {
"button-title": "Open To-Do list",
"add-todo": "Add To-Do",
"delete-todo": "Delete To-Do",
"mark-done": "Mark Done"
}
}
```
</details>
Next Step: [Interactivity](/yatbVbgzSxSMqHl5qoegpA)
{%hackmd io_aG7zdTKyRe3cpLcsxzw %}