BETAThis is a new service – your feedback will help us to improve it.

Making forms work

We've connected to a database and described how we want it to store our data.

Before we can read data from the database, we need to add some data to it.

One of the simplest ways to add data to a database is with a HTML form.

Get your form ready

You have probably already designed one or more forms for your app. You should revisit these now and make sure that you're still happy with them.

Make sure that the way your database stores data matches the way your form collects it.

We need to adapt some parts of our forms to make sure we're saving data in the way we need.

A basic form might look like this:

<form>
  <p>Your favourite color</p>
  <input type="radio" name="colour" id="red" value="red"/>
  <label for="red">Red</label>
  <input type="radio" name="colour" id="blue" value="blue"/>
  <label for="blue">Blue</label>

  <label for="postcode">Enter your postcode</label>
  <input type="text" id="postcode" name="postcode"/>

  <button type="submit">Submit</button>
</form>

Name

Each input has a name attribute. The radio buttons have name="colour" and the text field has name="postcode".

When we submit our form, our server will recieve an object something like this:

{
  colour: "red",
  postcode: "W1A 1AA"
}

Each piece of data is named with whatever is in the name attribute.

Each input's name attribute must match up with what you call that data in your model file.

Value

The other important attribute is value. The radio buttons have values of red and blue. These values are what actually get sent to the server, depending on the option the user picks.

The text field does not have a value attribute. Whatever the user types in the box becomes the value.

Checkboxes and dropdown menus also need value attributes.

Textareas, like simple text inputs, just send whatever the user types in the box.

To do

Make sure that:

  1. Your form's fields collect the right format of data for you to save in your database
  2. Each field has a name attribute that matches up with a name in the database model
  3. The value of each form input is correct for what you actually want to save in the database
Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Databases
  1. Introducing databases
  2. Organising a databaseP
  3. Using a database driverP
  4. Creating modelsP
  5. Making forms workP
  6. Collecting form dataP
  7. Saving form dataP