Saving form changes to the database

Append this method to source\empcontrol.d.

  void postEditEmployee(Employee e)
  {
    import std.file;
    import std.path;
    import std.algorithm;
    import vibe.http.auth.digest_auth;
    string photopath = e.photo;
    auto pic = "picture" in request.files;
    if(pic !is null)
    {
      string ext = extension(pic.filename.name);
      string[] exts = [".jpg", ".jpeg", ".png", ".gif"];
      if(canFind(exts, ext))
      {
        photopath = "uploads/photos/" ~ e.fname ~ "_" ~ e.lname ~ ext;
        string dir = "./public/uploads/photos/";
        mkdirRecurse(dir);
        string fullpath = dir ~ e.fname ~ "_" ~ e.lname ~ ext;
        try moveFile(pic.tempPath, NativePath(fullpath));
        catch (Exception ex) copyFile(pic.tempPath, NativePath(fullpath), true);
      }
    }
    e.photo = photopath;
    if(e.phone.length == 0) e.phone = "(123) 456 7890";
    if(e.paygd.length == 0) e.paygd = "none yet";
    if(e.postcode.length == 0) e.postcode = "A1A 1A1";
    e.pword = createDigestPassword(realm, e.email, e.pword);
    empModel.editEmployee(e);
    redirect("all_employees");
  }

The only differences between this method and the postAddEmployee() method are the fifth line and the second to the last line, which is the call to empModel.editEmployee() method, which we haven’t defined yet.

Let’s add this method at the end of source\empmodel.d:

  ulong editEmployee(Employee e)
  {
    string sql = "update employees set empid=?,
      deprt=?, paygd=?, email=?, pword=?,
      fname=?, lname=?, phone=?, photo=?,
      street=?, city=?, province=?, postcode=?
      where id=?";
    Prepared pstmt = conn.prepare(sql);
    pstmt.setArgs
    (
      to!string(e.empid),
      to!string(e.deprt),
      to!string(e.paygd),
      to!string(e.email),
      to!string(e.pword),
      to!string(e.fname),
      to!string(e.lname),
      to!string(e.phone),
      to!string(e.photo),
      to!string(e.street),
      to!string(e.city),
      to!string(e.province),
      to!string(e.postcode),
      to!int(to!string(e.id))
    );
    return conn.exec(pstmt);
  }

The SQL statement says ‘look for the record with the same value in the id field, then update that record with the following data’.

Compile, run and refresh the browser, then click on a pencil icon to display that record for editing.

Make some changes to the record and press Submit. You should be able to see your changes saved.

Time to implement the deletion of records to make the trash bin icon functional.

Last updated