You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter4中如何获取同名输入文本框的所有值?

CodeIgniter4 获取同名数组输入框的所有值

要获取name="prodquantity[]"的所有输入值,需按以下方式调整:

1. 正确获取数组参数

在Controller中,根据表单提交方式选择对应方法获取数组参数:

  • 若表单为POST提交,使用getPost():
// 返回包含所有输入值的数组
$prodquantity = $this->request->getPost('prodquantity');
  • 若表单为GET提交,改用getGet():
$prodquantity = $this->request->getGet('prodquantity');

getVar()虽支持多请求类型,但针对数组参数,明确使用对应请求类型的方法可避免优先级问题,确保拿到完整数组。

2. 数组参数验证(可选)

如果需要验证输入值,需为数组和数组元素分别设置规则:

$validation = \Config\Services::validation();
$rules = [
    'prodquantity' => 'required|array|min_length[1]', // 确保是有效数组
    'prodquantity.*' => 'required|integer|greater_than[0]' // 验证每个元素为正整数
];

if (!$validation->run($this->request->getPost(), $rules)) {
    // 处理验证错误逻辑
}

在View中可针对性获取错误信息:

// 数组整体错误
if ($validation->getError('prodquantity')) {
    echo '<span class="text-danger">'.$validation->getError('prodquantity').'</span>';
}

// 单个元素错误(如第一个输入框)
if ($validation->getError('prodquantity.0')) {
    echo '<span class="text-danger">'.$validation->getError('prodquantity.0').'</span>';
}

3. 额外注意点

  • 表单需设置正确的method属性(如POST),避免GET请求对数组参数的处理限制。
  • 不要给多个输入框设置重复的id属性(当前代码中id="prodquantity[]"重复),ID需唯一,可改为prodquantity_0、prodquantity_1这类标识。

内容的提问来源于stack exchange,提问作者Mayur Koshti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:47:24