在CodeIgniter中显示自定义消息


Display custom messages in CodeIgniter

好吧,这可能是一个愚蠢的问题,但由于我是非常新的编码,我不知道如何做到这一点。

我想做的是,在前端(On login-form-view, write-post-view…等)显示我的自定义错误消息。

早些时候,当我只使用PHP(没有框架)时,我将这些消息存储在$_SESSION全局变量中,并在前端页面中回显它们。但在这里,我希望CodeIgniter能提供更好的解决方案。

当你使用会话flash数据时,它只适用于重定向

例如

public function index() {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('username', 'Username');
  $this->form_validation->set_rules('password', 'Password');
  if ($this->form_validation->run() == FALSE ) {
    $this->load->view('login');
  } else {
    $this->session->set_flashdata('success', 'You have logged on');
    redirect('success_controller');
  }
}

On Success Page View

<?php if ($this->session->flashdata('success')) { ?>
<?php echo $this->session->flashdata('success');?>
<?php }?>

可以在codeigniter中使用flash数据。它会自动清除。

控制器:

//syntax => $this->session->set_flashdata('name', 'your message');
$this->session->set_flashdata('success', 'Post Successfully published.');

视图:

<?php echo $this->session->flashdata('success');?>

CodeIgniter有一个叫做FlashData的东西。Flash数据将传入一个会话变量,该变量将为下一个请求存在,然后在请求结束后清除它自己。

在CodeIgniter 3中,您可以这样设置flash数据:

$this->session->mark_as_flash(array('item', 'item2'));

或:

$this->session->mark_as_flash('item');

或者,您可以使用set_flashdata,它将与以前版本的CodeIgniter一起工作:

$this->session->set_flashdata('item', 'value');

你可以这样查看flashdata:

$this->session->flashdata('item');

如果您想通过一个额外的请求来保存flash数据,您可以使用keep_flashdata:

$this->session->keep_flashdata('item');

FlashData使用会话库,所以要确保它被加载在库自动加载器中,或者在使用它的控制器中。

FlashData文档

您可以使用$this->session->set_flashdata('item', 'value');

引用http://www.codeigniter.com/userguide2/libraries/sessions.html

在你的控制器中你可以使用

$this->load->library('session');
$this->session->set_flashdata('msg', 'Your message here');
redirect('controller_name/method_name');      

在View中你可以使用

echo $this->session->flashdata('msg');