Add a form to the web app that will allow the user to edit the information for an existing player in the database. First, create an "Edit Player" route that will be accessible via a GET request.
The GET request for the "Edit Player" page requires a player id
to render. The id
can be passed as a route parameter in Express. The user should be able to direct their browser to http://127.0.0.1:3000/edit/5
and the handler will know that the user would like to edit the player with an id
of 5
.
- In the
module.exports
object in the player.js file, define a neweditPlayerPage
function withrequest
andresponse
parameters - In the body of the
editPlayerPage
function, logrequest.params.id
to the console - Under the log, use
request.render
to render the edit-player.ejs page:editPlayerPage: function (request, response) { console.log(request.params.id); response.render('edit-player'); }
- In the app.js file, under the
app.get
calls, add anotherapp.get
to hook up/edit/:id
toplayer.editPlayerPage
- This means that whatever comes after the
edit/
will be mapped to theid
property ofparams
in the handler
- This means that whatever comes after the
- Navigate to the
/edit/5
route and verify that5
is properly logged in the console as theid
!
The GET handler function should query the database to find the information about the player with the given id
. It should then pass that data along to the EJS for rendering.
- Remove the code currently in the body of the
editPlayerPage
function - Declare a new variable
playerId
and set it torequest.params.id
- Define a new string variable
query
that holds a SQL statement to get all data for the player with the given id:SELECT * FROM players WHERE id = ${playerId};
- Call the
db.query
function to execute the statement, passing inquery
and a new anonymous function - Give the anonymous function two parameters:
error
andresult
- In the body of the anonymous function, if there is an error, return a 500 server error with the error message
- If there is no error in the callback, log
result[0]
to the consoleresult[0]
will contain the data for the player with the givenid
- Under the log, render the edit-player.ejs page, and pass in a data object with
player: result[0]
- This will give the EJS template access to the player's data
- Direct a web browser to the
edit/:id
endpoint, and verify that the data for the player with theid
is correct!
// Load the form to edit a player - GET
editPlayerPage: function (request, response) {
// Get player ID from the request
let playerId = request.params.id;
// Query to find information about the player with the given ID
let query = `SELECT * FROM players WHERE id = ${playerId};`;
// Execute the query
db.query(query, function (error, result) {
if (error) {
// Send server Error
return response.status(500).send(error);
}
console.log(result[0]);
// Load the page
response.render('edit-player', {
player: result[0]
});
});
}
Currently, the edit-player.ejs file can only handle adding new players. Update the EJS so that it will dynamically handle adding or editing players. If it is editing an existing player, the player data should be auto-filled in the form.
- In the player.js file, find the
addPlayerPage
function - Update the
response.render
call, and pass in{ add: true }
for the data parameter - In the
editPlayerPage
function, update theresponse.render
call and pass inadd: false
- This will allow the EJS to render differently for the "Add Player" page and the "Edit Player" page
- In the edit-player.ejs file, find the
input
for "First Name" and add avalue
attribute - Set the
value
attribute to an EJS segment that takes thefirst_name
property from theplayer
object - Using a ternary operator, update the EJS segment so that if
add
istrue
, it returns an empty string:<%=add ? '' : player.first_name%>
- Make similar updates for the "Last Name" and "Number"
input
elements - For the "Position"
select
, create a newoption
with theselected
attribute containing an EJS segment withplayer.position
- Wrap the new
option
in an EJS scriptlet with anif (!add)
so that it only appears while editing an existing player - In the "Submit" button
input
, replace "Add" with an EJS segment that could be either "Add" or "Update":<%= add ? 'Add' : 'Update' %>
- In the main
form
element, update theaction
attribute so that it can either go to/add
OR/edit/{player.id}
:<%=add ? 'add' : `edit/${player.id}`%>
- Wrap the entire
form
element in an EJS scriptlet with anif (add || player)
- This means if the user attempts to edit a player that does not exist, the form will not render
- Under the
form
, add anelse
EJS scriptlet with ap
that says "Player Not Found." - Load up the "Edit Player" page for a given
id
, and verify that the proper player information appears - Load up the "Add Player" page, and verify that everything still works the same way
<%- include('partials/header') %>
<div class="container">
<% if (add || player) { %>
<form method="post" action="/<%=add ? 'add' : `edit/${player.id}`%>">
<div class="form-row">
<div class="form-group col-md-6">
<label for="first-name">First Name</label>
<input type="text" class="form-control" name="first_name" value="<%=add ? '' : player.first_name%>" required>
</div>
<div class="form-group col-md-6">
<label for="last-name">Last Name</label>
<input type="text" class="form-control" name="last_name" value="<%=add ? '' : player.last_name%>" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="number">Number</label>
<input type="number" class="form-control" name="number" value="<%=add ? '' : player.number%>" required>
</div>
<div class="form-group col-md-6">
<label for="position">Position</label>
<select name="position" class="form-control" required>
<% if (!add) { %>
<option selected><%= player.position %></option>
<% } %>
<option>Goalkeeper</option>
<option>Defender</option>
<option>Midfielder</option>
<option>Forward</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-success float-right"><%= add ? 'Add' : 'Update' %> Player</button>
</form>
<% } else { %>
<p class="text-center">Player Not Found.</p>
<% } %>
</div>
</div>
</body>
</html>
Now that the "Edit Player" page loads properly, the user needs a way to navigate to it! Add "Edit" buttons to each player in the home page table.
- In the index.ejs file, add another
th
to thetable
header row with the text "Action" - Within the
for
loop row, add anothertd
under the numbertd
- Within the new
td
, add ana
with the text "Edit" that points the user to/edit/
with the player'sid
- Set the
class
attribute of thea
to "btn btn-sm btn-success" to make it appear like a green button:<td> <a href="/edit/<%= players[i].id %>" class="btn btn-sm btn-success">Edit</a> </td>
- Load up the homepage, and verify that the "Edit" button links to the "Edit" page for the proper player!