我正在使用Codeigniter框架来发展我的技能。我已经查看了数据并将其插入数据库,发现更新数据更为棘手。我看过的大多数教程都是在代码中输入值,而不是从数据库中提取选定的id并在表单字段中回显。到目前为止,我有:
news_model:
function editArticle($data) {
$data = array(
'title' => $title,
'content' => $content,
'author' => $author
);
$this->db->where('id', $id);
$this->db->update('news', $data, array('id' =>$id));
}
控制器:
public function update_entry() {
//load the upate model
$this->load->model('update_model');
//get the article from the database
$data['news'] = $this->news_model->get_article($this->uri->segment(4));
// perform validation on the updated article so no errors or blank fields
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
// If validation fails, return to the edit screen with error messages
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
//update the news article in the database
if($query = $this->update_model->update()) {
}else{
redirect('admin/edit');
}
}
}
视图:
<?php echo form_open('admin/edit/edit_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Edit Article'); ?>
<?php if (isset($error)){echo "<p class='error'>$error</div>";
}?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
1) 我不知道如何回显数据(当用户从显示的文章视图中单击编辑按钮时)以获取该id,然后在编辑页面上的文本字段中显示。
2) 然后让用户提交更新后的数据并发布到数据库中?
任何关于构建我的控制器/视图文件的指导或帮助都将不胜感激,因为我已经做了一天多了!
谢谢。
您还没有给出视图的所有代码,所以我不确定您有多少是对的,有多少是错的,但我会提到一些我能看到的东西-
您似乎不像$this->load->view('edit', $data);
那样从控制器调用视图(请参阅http://codeigniter.com/user_guide/general/views.html)其中当前字段的内容在CCD_ 2中。
要预先填充表单字段,请将当前字段值放在set_value()
的第二个参数中,例如set_value('title', $article->title)
。
您的模型还需要处理提交的表单(在$this->input->post
中),然后在模型中调用更新查询。
(我不得不说,CodeIgniter文档在这方面并不出色——你必须查看Form Helper和Form Validation Class文档,并跟踪视图(上面的链接)、控制器和模型(加上一两个其他的,我不应该怀疑))。