0

I have a list of sectors that I have retrieved from a database and I am trying to populate only the selected sectors depending on the user. There are 7 sectors (shown below).

HTML:

<p class="sector"><span>North East</span><input type="checkbox" class="sector-list" name="sector[]" value="1" /></p>
<p class="sector"><span>City of Sunderland</span><input type="checkbox" class="sector-list" name="sector[]" value="2" /></p>
<p class="sector"><span>Sunderland East</span><input type="checkbox" class="sector-list" name="sector[]" value="3" /></p>
<p class="sector"><span>Sunderland North</span><input type="checkbox" class="sector-list" name="sector[]" value="4" /></p>
<p class="sector"><span>Sunderland West</span><input type="checkbox" class="sector-list" name="sector[]" value="5" /></p>
<p class="sector"><span>Coalfield</span><input type="checkbox" class="sector-list" name="sector[]" value="6" /></p>
<p class="sector"><span>Washington</span><input type="checkbox" class="sector-list" name="sector[]" value="7" /></p>

CONTROLLER:

foreach($data['all_sectors'] as $sectors):
    echo"<p class='service'><span>$sectors->sector</span><input type='checkbox' class='sector-list' name='sector[]' value='$sectors->ID' /></p>";
endforeach;

Now when the user goes to edit their profile I am trying to pre populate the checkboxes that the user has selected previously.

I am confused as to how I can repopulate the sectors when they created an account. I have tried the following.

CONTROLLER:

$data['assigned_sectors'] = $this->info_model->getAssignedSectors();

foreach($data['assigned_sectors'] as $sector) 
    {
        $id_str = array(
            'ID' => $sector->sector_ID
        );
    }
    print_r($id_str);

Below is the result for '$data['assigned_sectors']'

Array ( [0] => stdClass Object ( [agency_ID] => 2 [sector_ID] => 3 [ID] => 3 [sector] => Sunderland East ) [1] => stdClass Object ( [agency_ID] => 2 [sector_ID] => 4 [ID] => 4 [sector] => Sunderland North ) )

I have tried adding both to the foreach checkbox html but no luck

set_checkbox('sector[]', $data['assigned_sectors']->sector_ID) //not working
set_checkbox('sector[]', $id_str->ID) //not working

I am probably overlooking something simple but any help would be greatly appreciated. Thanks!

UPDATE:

$this->load->model('admin/info_model');
    $data['agency_sectors'] = $this->info_model->getAgencySectors($agency);

    $this->load->model('admin/agencies_model');
    $data['all_sectors'] = $this->agencies_model->getAgencySectors($agency);

    echo"<p id='sectors'><label for='sectors'>Sector</label></p>";
    echo"<div id='sector_list' style='float: left;width: 70%;'>";
    foreach($data['agency_sectors'] as $sector):
        foreach($data['all_sectors'] as $sectors):
        $selected_text = ($sector->sector_ID === $sectors->ID) 
           ? " checked='checked'" 
             : '' ;
    echo"<p class='service'><span>$sectors->sector</span><input type='checkbox' class='sector-list' name='sector[]' value='$sectors->ID' " . $selected_text . "/></p>";
        endforeach;
    endforeach;
    echo"</div>";

If there are 2 agency sectors selected out of the 7 it duplicates the list twice, same for 3 results and so forth

4
  • are you using that inside the input tag? Commented May 7, 2013 at 15:44
  • The set_checkbox? Yeah I am Commented May 7, 2013 at 15:45
  • Can you post that line and state what the expected and actuals are? Commented May 7, 2013 at 15:47
  • <p class='sector'><span>$sectors->sector</span><input type='checkbox' class='sector-list' name='sector[]' value='$sectors->ID' " . set_checkbox('sector', '1') . " /></p> even if I add a hard-coded value of 1 the checkbox doesn't check Commented May 7, 2013 at 15:51

2 Answers 2

3

The name attribute should match the first parameter to set_checkbox:

change:

set_checkbox('sector', '1') 

to:

set_checkbox('sector[]', '1')

******UPDATE****

My previous answer was incorrect. You cannot set the checkbox selected state with set_checkbox from a value in the database. See @Raidenace's answer.

You'll have to set it by checking if the value is the same within a loop:

Instead of this code:

<p class='sector'><span>$sectors->sector</span>
  <input type='checkbox' class='sector-list' name='sector[]' 
    value='1' " 
      . set_checkbox('sector', $data['assigned_sectors']->sector_ID) . " />
</p>

Try this code:

$selected_text = ($data['assigned_sectors']->sector_ID === $sectors->ID) 
                   ? " checked='checked'" 
                     : '' ;
<p class='sector'><span>$sectors->sector</span>
  <input type='checkbox' class='sector-list' name='sector[]' 
    value='$sectors->ID' " . $selected_text . " />
</p>
Sign up to request clarification or add additional context in comments.

9 Comments

Even with the name changed it still doesn't even check one checkbox, regardless of the value
Right, I just tested it too. I just read @Raidenace's answer and after looking at the docs (Permits you to display a checkbox in the state it was submitted.) - it seems that is the correct answer. set_checkbox is not designed to decide to select a checkbox based on a value, but by the $_POST value of that particular checkbox item.
I am pulling the results from a database, how would I get the correct checkboxes selected?
just check to see if the values match, then set the checked state on the checkbox - I've updated my answer with that solution.
I didn't realize that you needed to loop both. I'm not a big fan of "loops within loops" - so I would probably create an array of agency sector ids (maybe with array_map), then check if the $sectors->ID is in the new array with in_array
|
3

Ok, this seems unintuitive but the set_checkbox() function "lets you set the selected value of a checkbox via the value in the POST array that is passed. So this is meant to revert a checkbox to the value that the user had selected during a form submission, in the use case of the form getting validated and the user is returned back to the same form due to, say, validation errors. I do not think that is what you are trying to get done in your case.

I had to figure it out from their function definition

/**
 * Set Checkbox
 *
 * Let's you set the selected value of a checkbox via the value in the POST array.
 * If Form Validation is active it retrieves the info from the validation class
 *
 * @access  public
 * @param   string
 * @param   string
 * @param   bool
 * @return  string
 */
if ( ! function_exists('set_checkbox'))
{
    function set_checkbox($field = '', $value = '', $default = FALSE)
    {
        $OBJ =& _get_validation_object();

        if ($OBJ === FALSE)
        {
            if ( ! isset($_POST[$field]))
            {
                if (count($_POST) === 0 AND $default == TRUE)
                {
                    return ' checked="checked"';
                }
                return '';
            }

            $field = $_POST[$field];

            if (is_array($field))
            {
                if ( ! in_array($value, $field))
                {
                    return '';
                }
            }
            else
            {
                if (($field == '' OR $value == '') OR ($field != $value))
                {
                    return '';
                }
            }

            return ' checked="checked"';
        }

        return $OBJ->set_checkbox($field, $value, $default);
    }
}

1 Comment

+1 for exploring the code which helped me extend it with this small FYI:: Manipulating the $_POST variable by setting it will result in CI checking that particular option. i.e $_POST['checkbox_name'] = $value;

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.