Search code examples
phpcodeigniter-4

How to get insertBatch() with checkbox in codeigniter 4


How to get the checkbox data? This is my view

<form method="post" action="<?= current_url();?>" >
<?php foreach($checklist as $item) : ?>
<ul>
  <li>
     <input type="hidden" name="name[]" value="<?= $item->name; ?>">
     <div>
        <label><?= $item->name; ?><label>
        <input type="hidden" value="0" name="status=[]>
        <input type="checkbox" value="1" name="status[]">
     </div>
  </li>
</ul>
  <button type="submit">Submit</button>

</form>

this is my controller

public function checklist() {
if($this->request->getMethod() === 'post') {
$name = $this->request->getPost('nama');
$status = $this->request->getPost('status');
 foreach($name as $key => $value) {
  $checklist[] = [
   'name' => $name[$key],
   'status' => $status[$key] 
  ];
}
$this->model->insertBatch($checklist);

return view('data',$data);
}

how to get the status if checked it get double array?


Solution

  • I assume this is a multi-item list with an item key. I assume $item['id'] is a unique key.

    View

    <?php
        $checklist = [['id'=>1,'name'=>'Test name 1','status'=>1],
                    ['id'=>2,'name'=>'Test name 2','status'=>0],
                    ['id'=>3,'name'=>'Test name 3','status'=>1],
                    ['id'=>4,'name'=>'Test name 4','status'=>0],
                    ['id'=>5,'name'=>'Test name 5','status'=>0]];
    ?>
    <pre>
    <?=print_r($checklist)?>
    </pre>
    <form method="post" action="<?= current_url()?>" >
        <ul>
            <?php foreach($checklist as $item) : ?>
            <li>
                <input type="hidden" name="name[<?=$item['id']?>]" value="<?=$item['name']?>">
                <div>
                    <label><?=$item['name']?><label>
                    <input type="checkbox" value="1" name="status[<?=$item['id']?>]"<?=$item['status']?' checked':''?>>
                </div>
            </li>
            <?php endforeach;?>
        </ul>
        <button type="submit">Submit</button>
    </form>
    getPost
    <pre>
    <?php 
        if(isset($getPost))
            print_r($getPost);
    ?>
    </pre>
    return
    <pre>
    <?php 
        if(isset($return))
            print_r($return);
    ?>
    </pre>
    

    Controller

    public function index()
    {
        $checklist = [];
        if($this->request->getPost()) {
            $getPost = $this->request->getPost();
            $status = $this->request->getPost('status');
            foreach($getPost['name'] as $key => $value) {
                  $checklist['return'][] = [
                   'name'   => $value,
                   'status' => isset($status[$key])?1:0];
            }
            $checklist['getPost'] = $this->request->getPost();
            // $this->Model->insertBatch($checklist);
        }
        return view('test',$checklist);
    }
    

    The final result image