开发者

Passing data from DB to update form using CI CRUD

I'm trying to write a compact update controller for CRUD activity. Here is the basic code:

Controller:

function update($id)
    {           
        $this->form_validation->set_rules('name'开发者_开发百科,'Name','required');            
        $this->form_validation->set_rules('age','Age','required|is_numeric');           
        $this->form_validation->set_rules('country','Country','');

        $this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');

        if ($this->form_validation->run() == FALSE) {

            //Failed validation or first run
            $data = $this->my_model->get_record($id);

            $this->load->view('myform_view', $data);

        } else {

            //Validation success, update DB

        }
    }

View:

<?php  

$attributes = array('class' => '', 'id' => '');
echo form_open('my_form', $attributes); ?>

<p>
        <label for="name">Name</label>
        <?php echo form_error('name'); ?>
        <br /><input id="name" type="text" name="name"  value="<?php echo set_value('name'); ?>"  />
</p>

<p>
        <label for="age">Age</label>
        <?php echo form_error('age'); ?>
        <br /><input id="age" type="text" name="age"  value="<?php echo set_value('age'); ?>"  />
</p>

<p>
        <label for="country">Country</label>
        <?php echo form_error('country'); ?>
        <br /><input id="country" type="text" name="country"  value="<?php echo set_value('country'); ?>"  />
</p>


<p>
        <?php echo form_submit( 'submit', 'Submit'); ?>
</p>

<?php echo form_close(); ?>

This is the basic structure, however the first time the form is run there is no validated data. Therefore I have to grab this from the DB. Whats the best way to pass this to the view on the first run? And then once the form has been submitted, if validation fails then I want the failed data to show not to reload from the DB again. Whats the best way to do this?


You should have another method for the viewing aspect. Then submit your form against the "update" method. In there, you define the the form_validation as you have now.

I asked a similar question. See this link


grab the data in update controller first for edit such as

$query = $this->db->where('id',$id)->get('table_name');
$data['edit'] = $query->result_array();

and then check it in view file

  value="<?php if(isset($edit[0]['age'])){echo $edit[0]['age'];}else{echo set_value('age');}?>"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜