Andrew Krigline
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 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: ![](https://i.imgur.com/GHXwjpr.png) 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> ... ``` ![Image showing the todo-list template data](https://i.imgur.com/wo5jcL6.png) 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> ``` ![Image showing our todo list](https://i.imgur.com/o80S22G.png) 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. ![Image showing our styled to-do list](https://i.imgur.com/pgli9K5.png) 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 %}

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully