0

Here's a bit of code from a codeigniter View:

   <li>
      <label>Assign volunteer to event:</label><br />
      <? foreach ($all_vols as $vol) :?>
        <?=form_checkbox('volunteers', $vol) ?>
        <?=$vol['username']?>
        <br />
      <? endforeach ?>  
    </li>

I'm expecting there to be an array named volunteers in the $_POST variable. Instead, what I'm getting is 'volunteers' => string('array'). Any thoughts what is happening here?

3 Answers 3

4

You cannot use an array as a second argument of form_checkbox() when used in this way, and $vol is likely to be an array as you use $vol['username'] later on. You're confounding the form helper, which takes the first parameter to be used as the 'name' attribute and the second as its 'value'.

Try:

<? foreach ($all_vols as $vol) :?>
        <?=form_checkbox('volunteers[]', $vol['username']) ?>
        <?=$vol['username']?>
        <br />
<? endforeach ?>  
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed! My problem was that I was passing an array as the second parameter to the form helper. Consequently, the form-helper gave each checkbox the value of "array". I fixed that problem as per your suggestions (and confirmed in the source that the values are correct). Now, however, I just get the last checkbox value in $_POST['volunteers']. Shouldn't there be an array of all the selected values? Why do I only get the last value?
@sarsinmypockets yeah sorry I forgot, you need to add brackets to volunteer, so that it becomes an array of values (print_r to see the result). Updated my answer to reflect this.
3

From CI's userguide

$data = array(
    'name'        => 'newsletter',
    'id'          => 'newsletter',
    'value'       => 'accept',
    'checked'     => TRUE,
    'style'       => 'margin:10px',
    );

echo form_checkbox($data);

// Would produce:

<input type="checkbox" name="newsletter" id="newsletter" value="accept" checked="checked" style="margin:10px" />

Your array should contain the data need it to populate the checkbox. So you might wanna change your checkbox to <?=form_checkbox($vol) ?> if you're sure it contains what is needed to populate the field.

Comments

1

The docs at http://codeigniter.com/user_guide/helpers/form_helper.html suggest using a string as the first argument (in your case "volunteers") will produce an <input type="checkbox" /> of that name while using $vol for the attribute-value pairs inside the input tag. Is this what you want? If so, you will apparently end up with a "username" attribute.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.