前言:
本篇继续在前一篇的基础上实现
表单提交数据的方式很常见,之前直接使用url放入参数,本次使用表单实现
一、修改控制器源码
1.编辑src/books.h并输入以下方法:
class Books : public Controller
{
public:
...
/**
* Display form to collect information for book to create
*/
C_ATTR(form_create, :Chained("base") :PathPart("form_create") :Args(0))
void form_create(Context *c);
/**
* Take information from form and add to database
*/
C_ATTR(form_create_do, :Chained("base") :PathPart("form_create_do") :Args(0))
void form_create_do(Context *c);
};
本次添加了两个函数 ,第一个用来显示表单用,第二个处理表单提交的数据
2.编辑src/books.cpp,以实现方法
void Books::form_create(Context *c)
{
// Set the Grantlee Template to use
c->setStash("template", "books/form_create.html");
}
void Books::form_create_do(Context *c)
{
// Retrieve the values from the form
QString title = c->request()->bodyParam("title", "N/A");
QString rating = c->request()->bodyParam("rating", "N/A");
QString authorId = c->request()->bodyParam("author_id", "1");
// Insert the book into it's table
QSqlQuery query = CPreparedSqlQueryThreadForDB("INSERT INTO book (title, rating) VALUES (:title, :rating)", "MyDB");
query.bindValue(":title", title);
query.bindValue(":rating", rating);
int bookId = 0;
bool error = true;
if (query.exec()) {
bookId = query.lastInsertId().toInt();
query = CPreparedSqlQueryThreadForDB("INSERT INTO book_author (book_id, author_id) VALUES (:book_id, :author_id)", "MyDB");
query.bindValue(":book_id", bookId);
query.bindValue(":author_id", authorId);
if (query.exec()) {
error = false;
}
}
// On error show the last one
if (error) {
c->stash()["error_msg"] = query.lastError().text();
}
// Assign the Book object to the stash for display and set template
c->stash({
{"book", QVariant::fromValue(c->request()->bodyParams())},
{"template", "books/create_done.html"}
});
}
二、添加动作模板
创建root/src/books/form_create.html,并输入如下内容
<form method="post" action="form_create_do">
<table>
<tr><td>Title:</td><td><input type="text" name="title"></td></tr>
<tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
<tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
</table>
<input type="submit" name="Submit" value="Submit">
</form>
这个模板用于输入要提交的表单数据
三、编译并测试
直接编译,生成动态库,并运行服务,输出如下
这个变化比较大,又多出了2个链
在浏览器中访问http://localhost:3000/books/form_create
运行如下所示
输入“TCP/IP Illustrated, Vol 3”作为标题,评分为5,作者ID为4,提交下显示如下
点击Home,可以看到又多了一行数据
本测试源码下载
后记:
表单提交实现了,但还没实现删除功能
下一篇,笔者探究添加删除功能相关