Listing all the employees
Edit source\empcontrol.d and add this code:
void getAllEmployees()
{
Employee[] emps = empModel.getEmployees;
render!("emplistall.dt", emps);
}Now, that’s a very simple method. Two lines!
But it is calling the empModel.getEmployees() method, which we haven’t written yet, and also needs the emplistall.dt file, which we haven’t created yet, so let’s resolve that.
First, let’s define the getEmployees() method at the end of source\empmodel.d:
Employee[] getEmployees()
{
Employee[] emps;
string sql = "select * from employees";
Row[] rows = conn.query(sql).array;
if(rows.length == 0) return emps;
return prepareEmployees(rows);
}This method returns all the records in the table. But this method calls the prepareEmployees() method, so let’s define it.
Employee[] prepareEmployees(Row[] rows)
{
Employee[] emps;
foreach(row; rows)
{
Employee e = prepareEmployee(row);
emps ~= e;
}
return emps;
}This method in turn calls the prepareEmployee() (singular, no ‘s’) method, so let’s define that too.
You should make sure the order of fields in prepareEmployee() follows the order of fields in the MySQL employees table. Sometimes MySQL does not save the fields in the same order as in your SQL CREATE TABLE statement. Check the Schemas view of MySQL Browser.

Now let’s create views\emplistall.dt.
As mentioned before, we can mix D code inside a Diet template file with – (hyphen)
Remember that we passed an Employee array emps to the template views\emplistall.dt:
Hence, we can inject this code:
-foreach(e; emps)
which will iterate through all of emps, which is an array of Employees, with e representing the current Employee record being processed inside the loop.
To display the value of a variable passed to the template, we use the construct #{variable}. This is equivalent to JSP’s <%= variable %> construct.
Hence the line
td #{e.deprt}
means display the value of e.deprt inside that table cell.
And here is views\csstable.dt which is needed by emplistall.dt.
Compile and run the app and refresh the browser. Click on New employee again and add another employee, then click the Submit button.
And after adding some employees, you should see this:

I got the icons for the pencil and the trash bin by simply googling for ‘pencil icon’ and ‘trash bin icon’ and saving the icons into the \public\images\ folder.
In the views\emplistall.dt file, we have these lines
input(type="image", src="images/pencil.ico", height="15px")
input(type="image", src="images/trash.ico", height="15px")
so save and name the icon files in the \public\images\ folder with the same names.
Add more sample records by clicking on the Add employee link after each submission.
So here is the full source\empmodel.d so far:
And here is the full source\empcontrol.d file so far:
Now let’s implement the editing of records to make the pencil icon functional.
Last updated