Copied!

A Complete How-To Guide To Build Prefilled Forms

Prefilled Forms

Prefilled forms is one of the first and most basic requirements to deliver a truly dynamic experience to your users in your app.

The most obvious benefit of prefilled forms for users is not requiring them to enter redundant information that you may have already requested from them previously.

In addition, there are lots of use-cases where you just want to display data from another system, resource, or database in the context of a form.

This guide will show you 2 ways you can pre-fill fields in a form.

Who Is This Guide For?

Form.io helps developers build custom, business process web applications without having to deal with all the frustrating things with forms and data management that are necessary in these types of applications.

This is for power users and developers who are building a dynamic application that leverages forms or you are just dealing with a lot of forms.

Setting The Stage

The scenario for this guide is a super simple project tracking app.

We are going to create a resource to store customer data, then create a form to simulate creating a new project we want to track. The project form will display data from the customer resource.

Set Up Your Local Files

For the purposes of this guide, I will be running a simple, flat HTML file and a JavaScript file to simulate an app. Use your preferred code editor to follow along. I will being using VS Code.

For Method 1 below, this section is unnecessary. You can achieve everything without code in Form.io by using the Launch feature that lets you test any form in a single page app that’s created with 1 click.

However, embedding a form in a web page or app is a simple process of copying and pasting the embed code, so I will be guiding you through this process as well—with no steps missed of course.

Plus we’ll need these local files for Method 2, which does require coding.

If you are familiar with how to set up a simple HTML and JS file, skip this section.

  1. Using a file manager, create a folder on your machine in which you will store and develop the application:

    Form.io Prefilled Forms Step

    In my example, the folder is called /app

  2. Launch VS Code on your machine, then select file—open folder:

    Form.io Prefilled Forms Step

  3. Navigate to /app and then click Select Folder:

    Form.io Prefilled Forms Step

    Form.io Prefilled Forms Step

  4. Click File—New Text File:

    Form.io Prefilled Forms Step

  5. Click File—Save As, and name the file app.js:

    Form.io Prefilled Forms Step

    Form.io Prefilled Forms Step

  6. Repeat steps 4 and 5, but name the second fole index.html.

  7. With index.html selected, type ! and press enter to generate the basic HTML structure of a simple web page:

    Form.io Prefilled Forms Step

  8. Change the title from Document to something else if you want:

    Form.io Prefilled Forms Step

  9. Copy the code below and paste it right before the closing </head> tag:

    <script src="app.js"></script>

    Form.io Prefilled Forms Step

  10. In order for the embedded forms to not display 100% across a standard screen size (which is ugly), let’s implement some CSS in order to frame the form in the middle of the page. Normally I would do this in a separate file, but for the purposes of this demo, that won’t be necessary.

    Copy the code below and paste it before the script tag you added in the previous step:

    <style>
    .app-wrap { width: 100%; max-width: 700px; height: 100%; max-height: 500px; padding: 30px; border-radius: 5px; box-shadow: 0 0 30px rgba(0,0,0,.1); position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; }
    </style>

    Form.io Prefilled Forms Step

  11. Copy the following HTML element code and paste it in between the opening and closing body tags:

    <div class="app-wrap"></div>

    Form.io Prefilled Forms Step

    Now we have a basic setup. We’ll come back to this later.

Method 1: The Prefilled Select Drop Down Field

This is the simplest method for building prefilled forms and it doesn’t require any coding unless you are embedding the form in your app, which requires some simple copying and pasting.

  1. Sign into the Form.io Developer Portal at portal.form.io.

    1. If you are using Form.io Enterprise embedded in your environment, the URL to access the Developer Portal will be unique to your organization. If you would like to use the Form.io SaaS offering or just test things out, you can create an account at portal.form.io (30 day trial). In either case, the steps will be the same.
    2. Once logged in, go to Projects and click Create Project:

      Form.io Prefilled Forms Step

    3. Name the project whatever you want and click Create project. This should automatically open the newly created project.
  2. If necessary, open the project you are working on by clicking the project name:

    Form.io Prefilled Forms Step

    (To get back to the list of projects, click the Form.io logo at the top left).

    By default, Form.io automatically generates the necessary Forms and Resources to handle authentication when a new project is created. This is why you will see some pre-created forms and resources.

    Structurally, forms and resources are the same thing—both can be presented as UI elements on a page and both can store submission data. The main difference is that Resources are used to model data and they can be used as source data for prefilled forms.

  3. On the left menu, click Resources, then click New Resource:

    Form.io Prefilled Forms Step

  4. For this guide, I will be creating a resource to store customer data. Type Customers in the Title field:

    Form.io Prefilled Forms Step

    If you are new to this sort of thing and if you plan on working through Method #2, I recommend naming things exactly as I have in order to minimize potential frustrations when implementing code. If you change the name of something, you will need to change the code syntax in various places that I may not call out specifically.

  5. Drag a text field component into the component area:

    Form.io Prefilled Forms Step

  6. Enter Name in the label field and click Save:

    Form.io Prefilled Forms Step

    (This field is referring to the business name, organization, etc).

  7. Add a few more fields to your liking (it won’t matter what you name these):

    Form.io Prefilled Forms Step

  8. Click Create Resource at the bottom right:

    Form.io Prefilled Forms Step

  9. Select the Use tab, enter some data for testing purposes, then click submit:

    Form.io Prefilled Forms Step

  10. Repeat step 10 so you have at least 3 submissions in the resource.

  11. Click on the Access tab and change the permissions for the following settings below:

    • Create Own Submissions: Anonymous
    • Create All Submissions: Anonymous
    • Read Own Submissions: Anonymous
    • Read All Submissions: Anonymous
    • Update Own Submissions: Anonymous
    • Update All Submissions: Anonymous
    • Delete Own Submissions: Anonymous
    • Delete All Submissions: Anonymous
  12. Form.io Prefilled Forms Step

    Since users do not have to log in to use this app demo, every user is essentially anonymous. Therefore, we need to set the permissions to allow that. For simplicity, I’ve opened the entire resource up so that any anonymous user can basically do anything.

    If this were to go into production, only authenticated users should be able to perform tasks and usually only on their own submissions.

  13. Click Save Settings at the bottom right:

    Form.io Prefilled Forms Step

  14. Now let’s set up the Projects form. In Form.io, click Forms, then click New Form:

    Form.io Prefilled Forms Step

  15. Select API Web Form:

    Form.io Prefilled Forms Step

  16. For the title, enter Projects:

    Form.io Prefilled Forms Step

  17. Add a Text Component, give it the label Project Name, then click Save:

    Form.io Prefilled Forms Step

  18. Add a Select Component, give it the label Type:

    Form.io Prefilled Forms Step

    The Type field is to simulate the type of project this is.

  19. Click the Data tab, then feel free to make up what kinds of projects you will be tracking. Use the Add Another button to add different options that will appear in the drop down box. Add a few options. Once finished, click Save:

    Form.io Prefilled Forms Step

  20. Add another Select Component and give it the label Customer:

    Form.io Prefilled Forms Step

  21. Click the Data tab, then change the Data Source Type drop down to Resource:

    Form.io Prefilled Forms Step

  22. Change the Resource drop down to Customers:

    Form.io Prefilled Forms Step

  23. Change the Value Property to Name (which is the organization/business name we created earlier):

    Form.io Prefilled Forms Step

  24. Click Save to save the component:

    Form.io Prefilled Forms Step

  25. Click Save Form to save the component:

    Form.io Prefilled Forms Step

  26. Click on the Access tab and change the permissions for the following settings below:

    • Create Own Submissions: Anonymous
    • Create All Submissions: Anonymous
    • Read Own Submissions: Anonymous
    • Read All Submissions: Anonymous
    • Update Own Submissions: Anonymous
    • Update All Submissions: Anonymous
    • Delete Own Submissions: Anonymous
    • Delete All Submissions: Anonymous
  27. These are the same permission settings in step 12 above.

    Don’t forget to click Save Settings.

  28. Let’s embed the form on our simple page. Click on the Embed tab at the top, then click the Copy to Clipboard button on the right side:

    Form.io Prefilled Forms Step

  29. In VS Code, make sure you have index.html selected, place your cursor in between the opening and closing DIV tags and press enter to create a new line:

    Form.io Prefilled Forms Step

  30. Paste the embed code on the new line you created:

    Form.io Prefilled Forms Step

    Important: This embed code calls Form.io’s library as well as the Bootstrap library which applies some default styling to the forms. Without the Form.io library, the forms will not render. Without the Bootstrap Library, you will be required to style everything by hand, which is beyond the scope of this guide.

    In the next section, we are going to change how we load the forms so that we can more easily attach functionality to events, such as when a user clicks submit.

  31. From your file manager where the files are stored, double-click the index.html file OR drag it on to a browser to open the page:

    Form.io Prefilled Forms Step

    You should now see your simple app with the form:

    Form.io Prefilled Forms Step

  32. Enter some data to test the form. Observe that the customer field makes this a prefilled form, since it has prefilled available options that are coming from your customers resource:

    Form.io Prefilled Forms Step

    Whenever new customers are added to the Customers resource, they will automatically appear as available options on this form.

    Click Submit when ready.

  33. You can view the submitted data on the Data tab in form.io:

    Form.io Prefilled Forms Step

Method 2: Use Form.io’s API To Create Prefilled Forms

This is will be the beginning of a bare-bones app build.

A common use-case that requires prefilled forms is when users need to edit a previously entered submission. For example, what if a user needs to change the name, type, or customer for a project they just created?

In this section, we are going to use Form.io’s API to display the projects in our app as buttons. When a user clicks on an available project, it will prefill the form with that project data, allowing the user to edit the project.

  1. Copy the CSS code below and paste it over everything in the <style> block in your index.html file so that what’s there is overwritten.

    .blackcover { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 90; background: rgba(0,0,0,.8); visibility: hidden; opacity: 0; pointer-events: none;
                transition: .15s linear all; }
            .blackcover.active { visibility: visible; opacity: 1; pointer-events: all; transition: .15s linear all; }
    
            .lightbox { width: 100%; max-width: 500px; height: 100%; max-height: 500px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; z-index: 100;
                visibility: hidden; opacity: 0; pointer-events: none; transition: .15s linear all; padding: 30px; background: #fff; border-radius: 5px; }
            .lightbox.active { visibility: visible; opacity: 1; pointer-events: all; transition: .15s linear all; }
    
                button.close { position: absolute; top: 20px; right: 20px; font-size: 20px; z-index: 10; }
    
            .project-list button.new-project { width: auto; padding: 5px 12px; background: #69b342; color: #fff; border-radius: 5px; transition: .15s linear all; font-size: 14px; font-weight: bold;
                border: 0; }
            .project-list button.new-project:hover { background: #78cd4b; transition: .15s linear all; }
    
            .app-wrap { width: 100%; max-width: 800px; height: 100%; max-height: 850px; padding: 30px; border-radius: 5px; box-shadow: 0 0 30px rgba(0,0,0,.1);
            position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; display: grid; grid-template-columns: 1fr 3fr; gap: 30px; }
            .app-wrap h1 { font-size: 20px; font-weight: bold; margin-bottom: 10px; }
    
            .new-wrap { display: none; }
    
                .projects { display: flex; flex-direction: column; gap: 5px; margin-top: 20px; }
                .projects button { background: #f3f3f8; border: 1px solid #e1e1e6; padding: 5px 15px; border-radius: 5px; width: 100%; text-align: left; transition: .15s linear all;  }
                .projects button:hover { background: #fff; transition: .15s linear all; }

    Form.io Prefilled Forms Step

    This styling will enable us to do the following:

    • Place the New Project form in a modal lightbox that is displayed when the user clicks a button
    • Create a left panel to display the existing projects
    • Display the form on the right side that will display the contents of a submission when a project is clicked.
  2. Delete the script call and the HTML that’s inside of the body tags:

    Form.io Prefilled Forms Step

  3. Copy the code below and paste it right before the script that calls app.js in the header:

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.form.io/formiojs/formio.full.min.css">
    <script src="https://cdn.form.io/formiojs/formio.full.min.js"></script>

    Form.io Prefilled Forms Step

    What we’ve done is change the way that the Form.io library and the accompanying bootstrap library is loaded. Before, the form and all of these things were loaded with one line of code.

    Now we’re going to load the Projects form twice (one for new projects and one for editing existing projects) and attach it to two separate HTML elements. To do this, we need to load the forms differently.

  4. Copy the HTML below and paste it inside of the opening and closing <body> tags:

    <div class="blackcover"></div>
      <div class="lightbox">
          <button class="close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"></path><path d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z" fill="rgba(0,0,0,1)"></path></svg></button>
          <div id="newProject"></div>
      </div>
    
      <div class="app-wrap">
    
          <div class="project-list">
              <h1>Projects</h1>
              <button class="new-project">New Project</button>
              <div class="projects"></div>
          </div>
    
          <div class="edit-wrap">
              <div id="editProject"></div>
          </div>
      </div>

    Form.io Prefilled Forms Step

    If you refresh your page, you should see this (and nothing will work):

    Form.io Prefilled Forms Step

  5. Copy the code below and paste it in your index.html file right before the closing tag:

    <script type="text/javascript">
        window.onload = function() {
            Formio.createForm(document.getElementById('newProject'), 'YOUR FORM API URL');
            Formio.createForm(document.getElementById('editProject'), 'YOUR FORM API URL');
            displayProjects(); // Call this function to display the projects
        };
    </script>

    Form.io Prefilled Forms Step

  6. In Form.io, open your Projects form, click on the Embed tab, and copy the URL in the first box in the main content:

    Form.io Prefilled Forms Step

  7. Select the first instance of the text YOUR FORM API URL, delete it, and paste the URL in its place. Make sure the URL is inside of the single quotes:

    Form.io Prefilled Forms Step

    Overwrite the second instance of the placeholder text with the same URL:

    Form.io Prefilled Forms Step

    If you refresh your page, you should see this:

    Form.io Prefilled Forms Step

  8. Copy the code below and paste it inside of your app.js file:

    document.addEventListener('DOMContentLoaded', function() {
        // Function to add the 'active' class
        function addActiveClass() {
            const blackCover = document.querySelector('.blackcover');
            const modal = document.querySelector('.lightbox');
    
            if (blackCover && modal) {
                blackCover.classList.add('active');
                modal.classList.add('active');
            }
        }
    
        // Function to remove the 'active' class
        function removeActiveClass() {
            const blackCover = document.querySelector('.blackcover');
            const modal = document.querySelector('.lightbox');
    
            if (blackCover && modal) {
                blackCover.classList.remove('active');
                modal.classList.remove('active');
            }
        }
    
        // Attach event listener to 'new-project' button
        const newProjectButton = document.querySelector('button.new-project');
        if (newProjectButton) {
            newProjectButton.addEventListener('click', addActiveClass);
        } else {
            console.log('New Project button not found');
        }
    
        // Attach event listener to 'close' button
        const closeButton = document.querySelector('button.close');
        if (closeButton) {
            closeButton.addEventListener('click', removeActiveClass);
        } else {
            console.log('Close button not found');
        }
    });

    Form.io Prefilled Forms Step

    This code will wait for the page to load, then enable the New Project button to display a modal lightbox that contains the projects form when it’s clicked. This is what users will interact with to create new projects.

    Refresh the page and then click the New Project button to verify that the modal lightbox appears:

    Form.io Prefilled Forms Step

  9. Use the New Project form to create a few more example projects:

    Form.io Prefilled Forms Step

  10. Copy the function (code) below and paste it at the top of your app.js file:

    async function displayProjects() {
        const projectsContainer = document.querySelector('.projects');
    
        try {
            let response = await fetch('YOUR FORM API SUBMISSION URL');
    
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
    
            let responseData = await response.json();
    
            projectsContainer.innerHTML = ''; // Clear existing content
    
            responseData.forEach(project => {
                if (project.data && project.data.projectName) {
                    let projectButton = document.createElement('button');
                    projectButton.textContent = project.data.projectName;
                    projectButton.addEventListener('click', () => populateForm(project._id));
                    projectsContainer.appendChild(projectButton);
                }
            });
        } catch (error) {
            console.error('Error fetching project data:', error);
            projectsContainer.innerHTML = '<p>Error loading projects.</p>';
        }
    }

    Form.io Prefilled Forms Step

    This function is what will display the project names as buttons in your app.

  11. In Form.io with your Projects form selected, click the Form API tab at the top right:

    Form.io Prefilled Forms Step

  12. Copy the Submissions endpoint API URL:

    Form.io Prefilled Forms Step

  13. In your app.js file, select the text YOUR FORM API SUBMISSION URL, delete it, and then replace it with the submissions API url you copied from the previous step:

    Form.io Prefilled Forms Step

    Make sure the URL is inside of the single quotes.

  14. Refresh your page to verify that the projects display:

    Form.io Prefilled Forms Step

    Observe the projects now display in the left panel. Clicking them won’t do anything at this point.

  15. Copy the function below and paste it immediately after the previous function you just added to your app.js file:

    async function populateForm(projectId) {
        try {
            const form = await Formio.createForm(document.getElementById('editProject'), 'YOUR FORM API URL');
    
            let response = await fetch(`YOUR FORM SUBMISSIONS API URL/${projectId}`);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            let projectData = await response.json();
    
            form.submission = {
                data: {
                    projectName: projectData.data.projectName,
                    type: projectData.data.type,
                    customer: projectData.data.customer
                },
                _id: projectId
            };
    
            // Listen for the form submission
            form.on('submitDone', () => {
                displayProjects(); // Refresh the projects list
            });
    
        } catch (error) {
            console.error('Error in populateForm:', error);
        }
    }

    Form.io Prefilled Forms Step

  16. Copy the same URL from the function named displayProjects from step 13 (your submissions API URL):

    Form.io Prefilled Forms Step

  17. Overwrite the text YOUR FORM API URL inside of this new, additional function named populateForm and then delete the /submission portion:

    Form.io Prefilled Forms Step

  18. Overwrite the text YOUR FORM SUBMISSIONS API URL that’s 2 lines below. Make sure to keep the snytax /${projectId} intact:

    Form.io Prefilled Forms Step

  19. Refresh your page and test the functionality:

    • Click on a project. The project contents should populate the form.
    • Edit the contents of an existing project and click submit. You should see that instead of creating a new project, the existing one that you had selected is updated.

Conclusion

You are now on your way to building a simple business process application that leverages the power of prefilled forms.

Form.io is targeted to developers who are already building business process applications, but who don’t want to hassle with all of the heavy-lifting that comes with forms, building form APIS, or managing form data. All of these things are done for you with Form.io.

This No-Steps-Missed Guide To Set Up Form.io To Give You Prefilled Forms And Fields Using 2 Different Methods In Form.io.

Published by

Form.io Wizard

Form.io is a zero-trust, data governance strategy platform, embedded in your environment, that enables you to build business process workflow applications or anything that uses forms with lightning bolt speed. Form.io is unique in its reach to the application layer regarding governance because we acknowledge forms are the primary entry point into everything data related. Forms are the UI, forms are the data model, and forms are the API model.

LighthouseHQ Case Study: Digital Transformation
Get Answers

Need More Answers?

Ask and we'll get back with you in 1 business day.

Contact Us

Send us a message to contact support or ask a question.

Schedule a meeting

Open Source Platform

Read our FAQ to find out what exactly is Open Source

View the Platform Documentation

View the API Documentation

View the Open Source Code

Learn More

Learn How It Works

Read the Release Notes

Discover Industries that use Form.io

Read our Blog