2

I have array of Krajee SwitchInputs, when everyone of SwitchInput is off, it returns nothing.

SwitchInput::widget([
    'name' => 'work_time[]',
    'value' => 1,
}
Farshid
  • 497
  • 1
  • 6
  • 20

2 Answers2

1

The reason you won't receive the values

This should be expected behavior (empty checkboxes are not considered "successful") and has nothing to do with the actual kartik-widget. In the background the widget uses a regular checkbox.

To save overhead, empty checkboxes won't transmit "0". So when you have more than one and all are off, nothing will be transmitted. However this is no problem as you know when all are missing, all are off!

You can find a lot of similar questions here, like this one for example, explaining the same thing. Don't worry too much, as it is quite simple:

  • value missing or 0: individual checkbox is off
  • all values missing: all are off

If you still want a workaround, you can find one here

Checking the right way

The following code will respect the types when comparing. Normally you would use either a boolean value or 1 and 0 as integers. Both work perfectly, but the boolean-way is better, as you are then not only able to use the equal-operator == but also the identical-operator ===.

$myCheckboxVal = isset(Yii::$app->request->post('my_checkbox')) ? true : false;
Community
  • 1
  • 1
PLM57
  • 1,256
  • 12
  • 27
-1

Thanks, I solved.

$value=isset($_POST['day_check']) ? '1' : '0';
Farshid
  • 497
  • 1
  • 6
  • 20
  • Hey farshid! Yes, this code works...but this answer doesn't describe the problem. If other users find this page, they might find that one snippet of code solving that exact problem, but they won't know why. I extended my answer below with the code how it should look like (respoecting types and not using 1 and 0 as string). – PLM57 Mar 16 '16 at 21:33