adonisjs:表单中的多个复选框给出不同类型的结果:如果仅选中一个,则为字符串,如果选中多个,则为数组

问题描述 投票:0回答:1

我正在使用 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' ] }

问题是:被调用的控制器如何接受表单结果?

  • 测试结果的类型?我不知道该怎么做
  • 我可以测试值的数量吗?我不知道
  • 还有其他想法吗?

感谢您的专业知识

forms adonis.js
1个回答
0
投票

天啊!对象 Array 及其函数 isArray 是我的朋友:

async return({ request, session, response }: HttpContext) {
    const payload = request.body()

const loanid = Array.isArray(payload.loanid) ? payload.loanid : payload.loanid.split(' ')

谢谢大家!

© www.soinside.com 2019 - 2024. All rights reserved.