Saving form data into the database
Let us add the postAddEmployee() method to source\empcontrol.d:
The photo being uploaded is in request.files. Remember that the HTTPServerRequest and the HTTPServerResponse are automatically available to us as the request and response variables.
So the line
auto pic = "picture" in request.files;
means we are extracting the uploaded file from request.files into the pic variable.
The word picture in that line corresponds to the name we gave to the button field in the views\empadd.dt form, which becomes the picture variable.
input.form-grid-input(type="file", name=
"picture"
)
The data-entry form requires a photo image file to be uploaded. Uploaded image files are usually not saved into the database as that would easily make the database bloated, so we need to save them into a folder which, if not already existing, we should create. Hence, we need to import some library modules related to file operations
so we can call these file operation functions:
The uploaded photos will be saved in the \public\uploads\photos\ folder and the filename will be changed to the employee’s name (firstname_lastname.ext).
The passwords need to be encrypted before they are saved so even if the database is hacked and bad guys gained access to the data, the passwords are still safely unreadable. The employees may need to have access to their own data in the future, such as access to time worked and salary for the period, so we need to keep their passwords safe.
So we need to import the relevant library for encryption:
import vibe.http.auth.digest_auth;
so we can call this function:
e.pword = createDigestPassword(realm, e.email, e.pword);
We created the realm variable near the top of the class:
private string realm = "The Lorem Ipsum Company";
as it is needed by the createDigestPassword() function.
Vibe.d sometimes generates errors when importing blank data from the database. If some of the non-required fields are blank, we need to fill them with dummy data:
before saving the record to the database.
The line
empModel.addEmployee(e);
does the actual saving into the database.
Now we can test the whole thing.
Last updated