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.
-
Using a file manager, create a folder on your machine in which you will store and develop the application:
In my example, the folder is called
/app
-
Launch VS Code on your machine, then select file—open folder:
-
Navigate to
/app
and then click Select Folder: -
Click File—New Text File:
-
Click File—Save As, and name the file
app.js
: -
Repeat steps 4 and 5, but name the second fole
index.html
. -
With
index.html
selected, type!
and press enter to generate the basic HTML structure of a simple web page: -
Change the title from Document to something else if you want:
-
Copy the code below and paste it right before the closing
</head>
tag:<script src="app.js"></script>
-
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>
-
Copy the following HTML element code and paste it in between the opening and closing body tags:
<div class="app-wrap"></div>
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.
-
Sign into the Form.io Developer Portal at
portal.form.io
.- 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.
-
Once logged in, go to Projects and click Create Project:
- Name the project whatever you want and click Create project. This should automatically open the newly created project.
-
If necessary, open the project you are working on by clicking the project name:
(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.
-
On the left menu, click Resources, then click New Resource:
-
For this guide, I will be creating a resource to store customer data. Type Customers in the Title field:
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.
-
Drag a text field component into the component area:
-
Enter Name in the label field and click Save:
(This field is referring to the business name, organization, etc).
-
Add a few more fields to your liking (it won’t matter what you name these):
-
Click Create Resource at the bottom right:
-
Select the Use tab, enter some data for testing purposes, then click submit:
-
Repeat step 10 so you have at least 3 submissions in the resource.
-
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
- Create Own Submissions:
-
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.
-
Click Save Settings at the bottom right:
-
Now let’s set up the Projects form. In Form.io, click Forms, then click New Form:
-
Select API Web Form:
-
For the title, enter Projects:
-
Add a Text Component, give it the label Project Name, then click Save:
-
Add a Select Component, give it the label Type:
The Type field is to simulate the type of project this is.
-
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:
-
Add another Select Component and give it the label Customer:
-
Click the Data tab, then change the Data Source Type drop down to Resource:
-
Change the Resource drop down to Customers:
-
Change the Value Property to Name (which is the organization/business name we created earlier):
-
Click Save to save the component:
-
Click Save Form to save the component:
-
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
- Create Own Submissions:
-
These are the same permission settings in step 12 above.
Don’t forget to click Save Settings.
-
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:
-
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: -
Paste the embed code on the new line you created:
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.
-
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:You should now see your simple app with the form:
-
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:
Whenever new customers are added to the Customers resource, they will automatically appear as available options on this form.
Click Submit when ready.
-
You can view the submitted data on the Data tab in form.io:
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.
-
Copy the CSS code below and paste it over everything in the
<style>
block in yourindex.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; }
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.
-
Delete the script call and the HTML that’s inside of the body tags:
-
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>
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. -
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>
If you refresh your page, you should see this (and nothing will work):
-
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>
-
In Form.io, open your Projects form, click on the Embed tab, and copy the URL in the first box in the main content:
-
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:
Overwrite the second instance of the placeholder text with the same URL:
If you refresh your page, you should see this:
-
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'); } });
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:
-
Use the New Project form to create a few more example projects:
-
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>'; } }
This function is what will display the project names as buttons in your app.
-
In Form.io with your Projects form selected, click the Form API tab at the top right:
-
Copy the Submissions endpoint API URL:
-
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:Make sure the URL is inside of the single quotes.
-
Refresh your page to verify that the projects display:
Observe the projects now display in the left panel. Clicking them won’t do anything at this point.
-
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); } }
-
Copy the same URL from the function named displayProjects from step 13 (your submissions API URL):
-
Overwrite the text YOUR FORM API URL inside of this new, additional function named populateForm and then delete the
/submission
portion: -
Overwrite the text YOUR FORM SUBMISSIONS API URL that’s 2 lines below. Make sure to keep the snytax
/${projectId}
intact: -
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.