我正在使用CI 3.1.9,并在下面的HTML表单中,使用如下键和值从PHP创建动态输入:
<form action="<?= base_url();?>/process" method="post">
<?php
foreach ($invoices as $invoice) {
// $invoice has values like 124-55441
?>
<input type="text" name="amounts[<?= $invoice; ?>]">
<?php } ?>
<input type="submit", value="submit">
</form>
现在在config文件夹中,我放置了一个带有验证规则数组的form_validation.php文件,如下所示:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* Custom Validation Rules */
$config = array(
'invoices' => array(
array(
'field' => 'amounts[]',
'rules' => 'trim|callback_checkAmountsToPay'
)
);
?>
在我的控制器Process.php中,我放置了以下代码:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Process extends CI_Controller {
public function index(){
if ($this->input->method(TRUE) === "POST") {
if ($this->form_validation->run("invoices") == FALSE) {
echo "Validation Failed";
} else {
$amounts = $this->input->post("amounts");
var_dump($amounts);
}
} else {
$this->load->view('invoices');
//Loading the form to view
}
}
//Custom validation form
public function checkAmountsToPay($arrAmounts) {
var_dump($arrAmounts);//Shows empty value
$this->input->post("amounts"); //Shows all array sent by the form.
die();
}
}
?>
checkAmountsToPay定制验证方法始终显示由表单发送的输入数组“ amounts []”的空值,但是如果我输入$ this-> input-> post(“ amounts”);它显示了整个数组,所以为什么post参数没有发送到自定义验证功能?
谢谢。
答案 0 :(得分:0)
由于arrays
表单验证库的限制,没有正确的方法在回调或验证规则中使用Codeigniter's
,因此您必须使用字符串。
尝试一下:
if ($this->input->method(TRUE) === 'POST') {
$amounts = json_encode($this->input->post('amounts'));
$this->form_validation->set_rules('amounts', 'Amounts', 'callback_checkAmountsToPay[' . $amounts . ']');
if ($this->form_validation->run('invoices') == FALSE) {
echo 'Validation Failed';
} else {
$amounts = $this->input->post('amounts');
var_dump($amounts);
}
} else {
$this->load->view('welcome_message');
//Loading the form to view
}
像这样得到:
public function checkAmountsToPay($value, $amounts) {
// $value returns first value of $_POST['amounts'][0]
$amounts = json_decode($amounts);
print_r($amounts);
}
或者只是用作回调函数中的代码
$this->input->post('amounts');