Week 6: Working with Selects, Files, and more

Different types of data require different UI elements to interact with them. This week we'll look at different elements in forms and how they can be used to manipulate, enter and edit the information in our database.

So far we have made 5 pages in our management space, each managing a different entity:

  • Articles
  • Books
  • People
  • Roles
  • Publishers

Each of these writes to our database, presents a list of items in our database and allows us to edit the items without making duplicates. Pretty straight forward so far.

We are 100% complete with Articles, People, Roles, and Publishers. Their whole role is to give us some data to use with our books.

Our books form, however, is incomplete. We are going to add the publisher and author data as well as the ability to upload images. Below are the steps for this week. Don't forget to make a week 6 branch!

Create the publisher's select
1
Make sure that your books table has a publisherId field

If it doesn't, open Datagrip and connect to the database server. Right click on your schema to open it. Right click on the books table and choose New --> Column. Call it publisherId and make it an integer. If you remember from the Introduction To Modelling article from last week, this field is going to store the id value from the publisher field. This makes it a foreign key.

2
In management/manageBooks - Instantiate our Publisher class

We are going to have a select box on our form which lists all of the publishers in our database. Yes, in real life there would be to many to list which would require more of a search than a straight list but we are going to start here.

<bx:output>
<bx:param name="isbn13" default="" />
<bx:set bookService = new finalProject.common.Books() />
<bx:set publisherService = new finalProject.common.Publishers() />
<bx:if form.keyExists("isbn13")>
3
Then query the database
    <div class="col-sm-9">
        <bx:if isbn13 neq "">
            <bx:set publishers = publisherService.allPublishers() />
            <bx:set books = bookService.allBooks(isbn13=isbn13) />
            <bx:set bookData = books.len() && isbn13 neq "" ? books[1] : {"isbn13":"","title":"","isbn":"","weight":"","pages":""} />

            <form method="POST" action="#cgi.script_name#?tool=manageBooks" >
4
Then create the select control

Can you identify what each line here does?

    </div>
                <div class="form-floating mb-3">
                    <select name="publisherId" class="form-select" aria-label="Default select example" id="publisherId">
                        <option value="">Select Publisher</option>
                        <bx:loop array="#publishers#" index="publisher">
                            <option value="#publisher.id#" #bookData.publisherId eq publisher.id ? "selected" : ""#>#publisher.name#</option>
                        </bx:loop>
                    </select>
                    <label for="publisherId">Publisher</label>    
                </div>
Adapt common.Books.saveBooks() to save our publisherId
1
Adapt the call to saveBooks()
<bx:set publisherService = new finalProject.common.Publishers() />
<bx:if form.keyExists("isbn13")>

    <bx:set bookService.saveBooks(form.isbn13, form.title, form.isbn, form.weight, form.pages, form.publisherId) />
</bx:if>
2
And finally adapt the saveBooks() function
function saveBooks( required string isbn13="", required string title="", required string isbn="", required string weight="", required string pages="" ){
function saveBooks( required string isbn13="", required string title="", required string isbn="", required string weight="", required string pages="",publisherId=0 ){
        queryExecute("
                INSERT into books (isbn13, title, isbn, weight, pages) 
                INSERT into books (isbn13, title, isbn, weight, pages, publisherId) 
                VALUES (:isbn13, :title, :isbn, :weight, :pages)
                VALUES (:isbn13, :title, :isbn, :weight, :pages, :publisherId) 
                ON DUPLICATE KEY UPDATE title=:title,
                isbn=:isbn,weight=:weight,pages=:pages
                isbn=:isbn,weight=:weight,pages=:pages,publisherId=:publisherId
            ",{
                isbn13:arguments.isbn13,
                title:arguments.title,
                isbn:arguments.isbn,
                weight:arguments.weight,
                pages:arguments.pages,
                publisherId:arguments.publisherId
            });
    }
Adding Images

We are going to add a control to upload an image. When a cover is associated with a book we are also going to display the image next to the upload control.

1
Check for an image field in your DB

If there isn't one, create it. Make it an nvarchar(300) to make sure it can handle long file names

2
Handle if we are adding a book and need default values
    <div class="col-sm-9">
        <bx:if isbn13 neq "">
            <bx:set publishers = publisherService.allPublishers() />
            <bx:set books = bookService.allBooks(isbn13=isbn13) />
            <bx:set bookData = books.len() && isbn13 neq "" ? books[1] : {"isbn13":"","title":"","isbn":"","weight":"","pages":""} />
            <bx:set bookData = books.len() && isbn13 neq "" ? books[1] : {"isbn13":"","title":"","isbn":"","weight":"","pages":"",image:""} />
            <form method="POST" action="#cgi.script_name#?tool=manageBooks" >
                <div class="form-floating mb-3">
3
Change our form to submit images and other files

A form by default string all of the values together in a long string. However, this would render any binary files, such as images and files, unusable. By adding the enctype="multipart/form-data" the submitted data is broken up with each value being submitted as a separate "chunk". This allows the data to stay complete and other information such as the file name and type to accompany the form submission.

      <bx:if isbn13 neq "">
            <bx:set publishers = publisherService.allPublishers() />
            <bx:set books = bookService.allBooks(isbn13=isbn13) />
            <bx:set bookData = books.len() && isbn13 neq "" ? books[1] : {"isbn13":"","title":"","isbn":"","weight":"","pages":""} />
            
            <form method="POST" action="#cgi.script_name#?tool=manageBooks">
            <form method="POST" action="#cgi.script_name#?tool=manageBooks" enctype="multipart/form-data" >
                <div class="form-floating mb-3">

4
Add your file Control

We need to add 2 columns - one to display the image the other to have the Upload control. We are also going to have a third input which is hidden. This third input is the name of the image as it is saved in the database. For the time we don't upload a new file, this ensures that the data is

<label for="bookCover">Cover</label>
<div class="row">
    <div class="col-sm-3">
        <img src="/images/#bookData.image#" alt="#bookData.title#" class="img-fluid">
    </div>
    <div class="col-sm-9">
        <input type="hidden" class="form-control" id="floatingInput" placeholder="Image" name="image" value="#bookData.image#">
        <input type="file" name="bookCover" id="bookCover" accept="image/*" class="form-control">
    </div>
</div>


5
Handle the file upload

We are not going to save the image directly into the database itself, although with some databases you can do that. We are going to upload the image to our finalproject/images folder and the save the filename into the database. First the image gets saved to a temporary folder. Then we move it to its final spot. Dump out the contents of fileData and see what information you can know about the file upload.

<bx:if form.keyExists("isbn13")>
    <bx:if form.keyExists("bookCover") && form.bookCover.len()>
        <bx:file action="upload" filefield="bookCover" destination="/images" nameconflict="makeunique" result="fileData" />
        <bx:file action="move" source="#fileData.serverDirectory#/#fileData.serverFile#" destination="#expandpath('/images')#" />
        <bx:set form.image=fileData.serverFile />
    </bx:if>
    <bx:set bookService.saveBooks(form.isbn13, form.title, form.isbn, form.weight, form.pages, form.publisherId) />
    <bx:set bookService.saveBooks(form.isbn13, form.title, form.isbn, form.weight, form.pages, form.publisherId, form.image) />
</bx:if>
6
And finally adapt the saveBooks() function

We need to handle the arguments and the query to accomodate the new image data.

function saveBooks( required string isbn13="", required string title="", required string isbn="", required string weight="", required string pages="", publisherId=0 ){
function saveBooks( required string isbn13="", required string title="", required string isbn="", required string weight="", required string pages="", publisherId=0, image="" ){
        queryExecute("
                INSERT into books (isbn13, title, isbn, weight, pages, publisherId) 
                INSERT into books (isbn13, title, isbn, weight, pages, publisherId, image) 
                VALUES (:isbn13, :title, :isbn, :weight, :pages, :publisherId) 
                VALUES (:isbn13, :title, :isbn, :weight, :pages, :publisherId, :image) 
                ON DUPLICATE KEY UPDATE title=:title,
                isbn=:isbn,weight=:weight,pages=:pages,publisherId=:publisherId
                isbn=:isbn,weight=:weight,pages=:pages,publisherId=:publisherId,image=:image
            ",{
                isbn13:arguments.isbn13,
                title:arguments.title,
                isbn:arguments.isbn,
                weight:arguments.weight,
                pages:arguments.pages,
                publisherId:arguments.publisherId,
                image:arguments.image
            });
Lesson 1 of 1 - Week 6: Final Project