phptwigsymfony-2.6

symfony2: unchecked checkbox's value is not taken into account


Environment:

I am new to symfony. I am trying adding new column to existing table. The column has checkboxes in each row. So far, I could check or uncheck the checkboxes by StoreController.php when rendering them. Then, I check or uncheck some checkboxes to change state. And submit the form. But I get strange result in array format. Looks like unchecked checkbox's value is not taken into account. How should I fix this to get check states of all the checkboxes.

There is similar question. But this form is submitted by using Post request, so it is different.

json_edit.html.twig

<form method="post" action="/store/json_edit?{% if (1 != isStore) %}id={{ id | e }}&{% endif %}json={{ jsonFileName | e }}&type={{ type | e }}">

...(ellipsis)

<td><div style="text-align: center;"><input type="checkbox" name="tv_shipping[]" {% if (1 == jsonDataTv.shipping) %}checked value="1"{% else %}value="0"{% endif %} /></div></td>

It displays as this. The table has three rows.

then, click button to submit the form, and trying get result, from the checkboxes.

StoreController.php

var_dump($request->get("tv_shipping"));//array(2) { [0]=> string(1) "1" [1]=> string(1) "1" }

The result array has only two objects. I think it is supposed to have three objects as follows.

//array(2) { [0]=> string(1) "1" [1]=> string(1) "0" [2]=> string(1) "1" }

Solution

  • Thanks for the advises in comment area. I came up with a solution by myself.

    I added index number to each checkbox element as value="{{key}}". The key is index that starts from 0 increasing by 1 as row index increases.

    json_edit.html.twig

    <td><div style="text-align: center;"><input type="checkbox" name="tv_shipping[]" {% if (1 == jsonDataTv.shipping) %}checked{% endif %} value="{{key}}"/></div></td>
    

    In php controller, I loop by row index and check if there is checkbox where checkbox value equals to the row index. If it mataches, the checkbox is checked. If there is no matched pair, it means that the checkbox is unchecked.

    StoreController.php

        //get state if checkbox is checked or not as boolean.
        $checked = false;
        if(0 < count($request->get("tv_shipping"))){
            foreach($request->get("tv_shipping") as 
               $key_arrayResult=>$value_arrayResult){
               if((int)$value_arrayResult === $count+1){
                 $checked = true;
                 break;
               }
             }
         }