我正在使用 Adonisjs V6 和 Edge。
我有一个带有多个复选框的表单,控制器为视图提供一个复选框。项目显示在表格中。
从数据库获取数据并将其发送给查看器的控制器:
async returnList({ view }: HttpContext) {
const usersBooks = await db
.from('loans')
.join('users', 'user_id', '=', 'users.id')
.whereNull('realreturndate')
.orderBy('users.lastname')
.join('books', 'books.id', '=', 'loans.book_id')
.select('loans.id as loanId')
.select('users.id as userId')
.select('users.firstname')
.select('users.lastname')
.select('books.id as bookId')
.select('books.title')
.select('loans.loandate')
.select('loans.returndate')
return view.render('pages/loan/return', { usersBooks })
}
构建表单的查看器:
<form class="box" autocomplete="off" action="/return" method="POST">
{{ csrfField() }}
<div class="container is-fluid">
<div class="columns is-centered">
<div class="column is-half">
<h1 class="title is-1 has-text-link" style="text-align: center">Retour d'un livre</h1>
<table class="table is-striped">
<thead>
<tr>
<th>[X]</th>
<th><abbr title="lastname">Nom</abbr></th>
<th><abbr title="firstname">Prénom</abbr></th>
<th><abbr title="title">Titre du livre</abbr></th>
<th><abbr title="loandate">Date prêt</abbr></th>
<th><abbr title="returndate">Date retour prévu</abbr></th>
</tr>
</thead>
<tbody>
@each(loan in usersBooks)
<tr>
<td><input type="checkbox" name="loanid" value={{loan.loanId}}></td>
<td>{{loan.firstname}}</td>
<td>{{loan.lastname}}</td>
<td>{{loan.title}}</td>
<td>{{loan.loandate}}</td>
<td>{{loan.returndate}}</td>
</tr>
@end
</tbody>
</table>
</div>
</div>
</div>
如果选中一个复选框,则结果是一个字符串:{ Loanid: '8' }
如果选中多个复选框,则结果是一个数组:{loanid: [ '8', '9' ] }
问题是:被调用的控制器如何接受表单结果?
感谢您的专业知识
天啊!对象 Array 及其函数 isArray 是我的朋友:
async return({ request, session, response }: HttpContext) {
const payload = request.body()
const loanid = Array.isArray(payload.loanid) ? payload.loanid : payload.loanid.split(' ')
谢谢大家!