如何将多个复选框值从视图传递到控制器(使用代码点火器框架)

时间:2018-08-23 02:49:17

标签: php codeigniter

我尝试使用网站提供的教程来学习CodeIgniter框架,而我对php还是很陌生,我可能会问一个愚蠢的问题。  我试图将复选框状态值从“视图”传递给控制器​​(是否选中了复选框的状态),它在错误消息之后显示。

  

遇到PHP错误

     

严重性:警告

     

消息:为foreach()提供了无效的参数

     

文件名:controllers / Todos.php

     

行号:29

当我在控制器中跟踪时,这是由于foreach循环初始化所致。然后我回声

echo $completed_todos; 
echo $completed_todos[0];
echo $completed_todos[1]; — No value;

我认为是什么,它不会将所有复选框值都传递给控制器​​。

在View中,我使用了以下代码: (index.php)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple CodeIgniter App - Todos</title>
<link rel="stylesheet"
href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>


<div class="container">

<?php echo form_open('todos/update_completed'); ?>

<h1>Todos</h1>

<div class="list-group">
<?php foreach ($todos as $todo) { ?>
<div class="list-group-item clearfix">
<?php
echo form_checkbox('completed', $todo->id, $todo->completed);
?>
<?php echo $todo->task; ?>

</div>

在我使用以下代码的控制器中

Todos控制器代码

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Todos extends CI_Controller {

public function __construct() {
parent::__construct();

// Load the todo model to make it available 
// to *all* of the controller's actions 
$this->load->model('Todo_model');
$this->load->helper('form'); 
}

public function update_completed() {

$completed_todos = $this->input->post('completed');
echo $completed_todos;
foreach ($completed_todos as $todo_id) {
echo 'The todo with id = ' . $todo_id
. ' is marked as completed.<br>';
}
}

1 个答案:

答案 0 :(得分:5)

在这里您要获取多个复选框的值,因此需要放入数组中。但是您尝试了简单的字符串,并在foreach循环中使用了它,这就是为什么它会导致错误。

请检查以下代码。

index.php(查看文件)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple CodeIgniter App - Todos</title>
    <link rel="stylesheet"
    href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1>Todos</h1>
        <?php echo form_open('todos/update_completed'); ?>
            <div class="list-group">
                <?php foreach ($todos as $todo) { ?>
                    <div class="list-group-item clearfix">
                        <?php echo form_checkbox('completed[]', $todo->id, $todo->completed); ?>
                        <?php echo $todo->task; ?>
                    </div>
                <?php } ?>
            </div>
            <button type="submit">Submit</button>
        <?php echo form_close();
    </div>
</body>
</html>

Todos(控制器文件)

public function update_completed() {
   $completed_todos = $this->input->post('completed');
   // No need to echo $completed_todos. If you want then please do below line.
   // var_dump($completed_todos);
   foreach ($completed_todos as $todo_id) {
      echo 'The todo with id = ' . $todo_id. ' is marked as completed.<br>';
   }
}