A custom block with multiple checkboxes

Permalink
I'm new to concrete5 and i wanted to know how to retrieve value of multiple checkboxes having the same name!
As in , if all are checked store and retrieve all three values

<input type="checkbox" name="test[]" value="1"/>
<input type="checkbox" name="test[]" value="2"/>
<input type="checkbox" name="test[]" value="3"/>

 
JohntheFish replied on at Permalink Reply
JohntheFish
It will be an array in the $_POST or $_GET data. If it is a custom block, it will be in the $data parameter of the save method. It will have the same name and because it has [] php will convert it to an array for you.

e.g.
$test = $_POST['test'];


For general debugging, see
http://www.concrete5.org/documentation/how-tos/developers/concrete5...

You can see what parameters c5 sees by doing a dump of $_POST.
rgd1990 replied on at Permalink Reply
Could you please help me out by tellin me what my controller save() should be?
JohntheFish replied on at Permalink Reply
JohntheFish
That all depends on what your database table looks like. Can you post the relevant declarations of the db.xml.
rgd1990 replied on at Permalink Reply
<?xml version="1.0"?>
<schema version="0.3">
    <table name="simpleTest">
        <field name="bID" type="I">
            <key ></key>
            <unsigned ></unsigned>
        </field>
        <field name="test" type="X2">
        </field>
    </table>
</schema>
JohntheFish replied on at Permalink Best Answer Reply
JohntheFish
Here is the sort of code I tend to use in a save() method.
public function save ($data) {
  if (is_array($data['test'])){  
    $data['test'] = implode(',',array_values($data['test']));
  }else{
    $data['test'] = implode(',',array());
  }
  parent::save($data);
}

If all your test[] checkboxes were checked, it would save the string "1,2,3"

When using in edit/view, you can then do something like:
$unpacked_test = explode(',',$this->test);
foreach (array(1,2,3) as $test_value){
  if (in_array($test_value, $unpacked_test )){
    // stuff to do if $test_value is set
  }
}

(I obviously need to communicate between controller and view somewhere in the middle of that)

Depending on the options, I have also used a similar trick with serialize/unserialize and to/from json.
rgd1990 replied on at Permalink Reply
Thank you!! It worked well :)