我写了一个快速的 CI 库类来渲染我的页面,这样我就不必一直输入'$this->load->view' 并且为了 DRY。现在,当我在传递无效数据后重新呈现我的联系表单时,错误消息不会出现。
图书馆类:
class Page extends CI_Controller {
public function render($page, $data) { // $page should be path to page view
$this->load->view('fragments/header', $data);
$this->load->view('fragments/navigation');
$this->load->view($page);
$this->load->view('fragments/navigation');
$this->load->view('fragments/footer');
}
}
和控制器:
class Contact extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->library(array('form_validation', 'email', 'page'));
}
public function index() {
$this->form_validation->set_rules('sender_name', 'From', 'required');
$this->form_validation->set_rules('sender_email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->library('page');
$this->page->render('contact/contact', array('title' => 'Contact Me')); // pass in page title
/* IT WORKED THIS WAY
$this->load->view('fragments/header', array('title' => 'Contact Me')); // pass in page title
$this->load->view('fragments/navigation');
$this->load->view('contact/contact'); // TODO maintain form state
$this->load->view('fragments/navigation');
$this->load->view('fragments/footer');
*
*/
}
//SNIP
联系表格视图:
<h1>Contact Me</h1>
<?php echo form_open('contact', 'id="contact_form"'); ?>
<label for="sender_name">Name:</label>
<?php echo form_input('sender_name'); ?>
<span class="error"><?php echo form_error('sender_name'); ?></span>
<label for="sender_email">Email:</label>
<?php echo form_input('sender_email'); ?>
<span class="error"><?php echo form_error('sender_email'); ?></span>
<label for="subject">Subject:</label>
<?php echo form_input('subject'); ?>
<span class="error"><?php echo form_error('subject'); ?></span>
<label for="message">Message:</label>
<?php echo form_textarea('message'); ?>
<span class="error"><?php echo form_error('message'); ?></span>
<?php echo form_submit('submit', 'Send'); ?>
如何使用此帮助程序呈现页面并仍然从 form_validation 库中检索错误消息?