Bootcamp
Search…
3.4.5: Forms for One-to-Many Relationships

Introduction

When we create new data and wish to associate that data to data in other tables, such as creating new recipes and associating them to categories, we need to have the user input the selected category when they create a recipe.

Input ID Implementation

The naïve way to do this is to create another text input for the user to input the relevant category's ID, but this isn't great because the user may not know what the categories are and what the categories' IDs are. We want to give the user the ability to select from all the possible categories and for the user not to have to deal with the IDs.
1
<form action="/recipe" method="POST">
2
<input type="text" name="label" />
3
<input type="text" name="category_id" />
4
<input type="submit" value="Submit" />
5
</form>
Copied!

Select from Dropdown Implementation

A recipe can only have one category, and the user has to choose from available categories, so we'll do this with a dropdown menu. A dropdown menu facilitates choosing from several selections, and our dropdown will only allow a single selection.
We need to populate this dropdown with all categories in the DB, so before we render the form we'll do a SQL query to get them.

Query for Categories to Render Dropdown

When we send a GET request to render the create recipe form, we also query the DB for a list of all categories.
index.js
1
app.get('/recipe/new', (request, response) => {
2
pool.query('SELECT * from categories', (error, result) => {
3
const data = {
4
categories: result.rows,
5
};
6
response.render('recipe/new', data);
7
});
8
});
Copied!

Render Dropdown

We can set the ID of each category in option tags in our form. The user never has to know which category names map to which category IDs.
recipe/new.ejs
1
<form action="/recipe" method="POST">
2
<select name="category_id">
3
<% categories.forEach((category) => { %>
4
<option value="<%= category.id %>"><%= category.name %></option>
5
<% }); %>
6
</select>
7
<input type="text" name="label" />
8
<input type="submit" value="Submit" />
9
</form>
Copied!