【问题标题】:Cakephp how to pass array from view to controllerCakephp如何将数组从视图传递到控制器
【发布时间】:2016-10-18 00:03:50
【问题描述】:

使用 Cakephp 2 我试图从列表中选择一个或多个单击复选框的记录 命名为 my_id[] :

<input type="checkbox" name="my_id[]" value="<?php echo $Myobj['My']['id']; ?>

我有一个指向控制器 processBatch 方法的链接,但不知道如何使用复选框将所选数据数组传递到视图文件中。

<?= $this->Html->link('Batch process','proccessBatch')?>

我正在尝试:

public function proccessBatch( ) //array of $ids  
{        
    pr($this->request);

但是没有看到 $this-request->data。如何获取复选框选定的值?

【问题讨论】:

  • 您可以通过提交表单将数据发布到 proccessBatch() 函数中。然后你会将数据放入 "$this->request->data" 数组中。

标签: cakephp


【解决方案1】:

我在下面为您创建了一个示例。

这是我的看法

    <?php
    //sample list of items with 'id'=>'name
    $arrayList = [
        0=>'item 1',
        1=>'Item 2',
        2=>'Item 3'
    ];
    //create the form
    echo $this->Form->create('listofitems',array('novalidate' => true));
    //generate the checkboxes by looping through the items(this is just one way of doing it)
        for($i=0;$i<count($arrayList);$i++){
            //concatenate the value of the id ($i in my case) with the name
            // of the field to uniquely identify it.
            echo $this->Form->checkbox("my_id".$i);
        }
    echo $this->Form->end('save');//end form and save button
    ?>

这是我的控制器及其操作

<?php
App::uses('AppController', 'Controller');
class SampleController extends AppController {

    public function arrays(){
        pr($this->request->data); //just pr the posted data
    }

}
?>

以及控制器中pr线的结果

Array
(
    [listofitems] => Array
        (
            [my_id0] => 1
            [my_id1] => 0
            [my_id2] => 1
        )

)

希望这对您的问题有所帮助。请注意,只有选中项的值为 1,而未选中项的值为 0

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多