dimanche 7 juin 2020

How to validate at least one checked checkbox input in a form

I am trying to insert into DB a work schedule that contains for each day and type worker(bartender, waiter, etc) and shift (aka morning or evening) the name of the worker. Every day and the shift has the same input name="worker_name[]" because that's the DB controller function built like and it's supposed to be it. However, I can't check if at least one of the checkboxes for each day and shift is checked. I've tried the checkbox group but it didn't work.

One part of my form in the View:

<td>               
            <?php if ($mondayfreeDay === true){
            echo '<label for="holiday" style="color:MediumAquaMarine"><input type="checkbox" name="worker_name[]" id="holiday" value="free"> free</label>';
            }?>
            <?php
            foreach ($monday_morning as $shift):?>
            <?php if($shift['job'] == "bar"){?>
            <input type="hidden" value="monday" name="day[]">
            <input type="hidden" value="morning" name="time[]">
            <br><label><input type="checkbox" name="worker_name[]" value="<?php echo $shift['fullname'];?>">
            <?php echo $shift['fullname']; }?></label>  
            <?php  endforeach;  ?>               
        </td>

Controller:

public function saveFinalShifts(){  

        $data = array();

        $newDate= $this->input->post('week');
        $sunday = $this->Shifts_model->getStartDate($newDate);
        $count = count($this->input->post('worker_name[]'));
        $dates = array_fill(0,$count , $sunday);
        $days = $this->input->post('day[]');
        $times = $this->input->post('time[]');
        $worker_names = $this->input->post('worker_name[]');

        if(is_array($dates)){
        foreach ($dates as $key => $date){
            $data[] =  array (
                'date' => $date,
                'day' => $days[$key],
                'time' => $times[$key],
                'worker_name' => $worker_names[$key],
                );
            }
        }
    $this->Shifts_model->saveFinalShifts($data);
}

Aucun commentaire:

Enregistrer un commentaire