Question

I'd like some help please. I have this form group: This is the view:

<?php echo form_open('admin/posts/post/'.$post->id); ?>
// other fields here...
<div class="form-group">
                <label for="" class="col-sm-2">Visible</label>

                <div class="col-sm-10">
                    <div class="onoffswitch">
                        <?php  
                            $visible = ($post->visible) ? $post->visible : $this->input->post('visible');
                            $visible_data = array(
                                'class' => 'onoffswitch-checkbox', 
                                'id' => 'visible',
                                'checked' => ($visible == '1') ? true : false,
                                'name' => 'visible',
                                'value' => ($post->visible) ? $post->visible : $this->input->post('visible'),
                                );
                        ?>
                        <?php echo form_checkbox($visible_data); ?>
                        <label class="onoffswitch-label" for="visible">
                            <div class="onoffswitch-inner"></div>
                            <div class="onoffswitch-switch"></div>
                        </label>
                    </div> 
                </div>
            </div>

// more fields ...
<?php echo form_close(); ?>

This is the controller

public function post($id){
        $this->data['post'] = $this->post_model->get($id);

        $this->form_validation->set_rules($this->post_model->rules);
        if ($this->form_validation->run() === true) {

              var_dump($this->input->post('visible')); //not getting anything from the visible field

             // store data in database and redirect
             $this->post_model->save($id);
        }

        // load the view
        $this->load->view('admin/post/edit');
    }

Basicly this works as an on/off switch button. The problem is that when I click the submit button it's not sending the $_POST data of the field ( $this->input->post('visible') ) to my model in order to store it in the database.

Any ideas what wrong and how should fix it??

Était-ce utile?

La solution

This has nothing to do with Codeigniter, it's just how browsers work, if a checkbox is unchecked no POST data is sent to the server.

So you can either check in the controller for $this->input->post('visible') (it will return false if the checkbox is unchecheck and whatever you have in value.

Or you can do a small hack and put an hidden input with the same name and the value as false before you checkbox.

In your example you should put value="1" on the checkbox and have a <?=form_hidden('visible', 0)?> before the checkbox.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top