在Codeigniter中显示flashdata的成功/失败消息

时间:2013-08-31 01:17:28

标签: php codeigniter

我正在尝试学习如何向用户显示消息,告知他们尝试从数据库中删除内容页面的错误或成功消息。我想知道我到目前为止是否做得对。如果我在视图中做的是什么?

控制器

/**
 * Content_pages::delete_content_page()
 * 
 * Deletes a content page from the list of content pages.
 * 
 * @param string $content_page_id The id of the content page being deleted.
 * @return void
 */
public function delete_content_page($content_page_id)
{
    $status = 'unprocessed';
    $title = 'Action Unprocessed';
    $message = 'The last action was rendered unprocessed. Please try again.';
    if (isset($content_page_id) && is_numeric($content_page_id))
    {
        $content_page_data = $this->content_page->get($content_page_id);
        if (!empty($content_page_data))
        {
            $this->content_page->update($content_page_id, array('status_id' => 3));
            if ($this->db->affected_rows() > 0)
            {
                $status = 'success';
                $message = 'The content page has been successfully deleted.';
                $title = 'Content Page Deleted';   
            }
            else
            {
                $status = 'error';
                $message = 'The content page was not deleted successfully.';
                $title = 'Content Page Not Deleted';   
            }
        }
    }
    $output = array('status' => $status, 'message' => $message, 'title' => $title);
    $this->session->set_flashdata('output', $output); 
    redirect('content-pages/list');
}

/**
 * Content_pages::list_content_pages()
 * 
 * List all of the content pages found in the database.
 * 
 * @return void
 */
public function list_content_pages()
{   
    $content_pages = $this->content_page->get_all();

    $data['output'] = $this->session->flashdata('output');

    $this->template
        ->title('Content Pages')
        ->set('content_pages', $content_pages)
        ->build('content_pages_view', $data);    
}

我的问题是在视图中,因为它显示为默认的空消息,所以我试图弄清楚在视图首次渲染时如何不显示它,并且只有在有消息显示时才会显示。

if (isset($output))
{
    if ($output['status'] == 'success')
    {
        echo '<div class="alert alert-success">';
    }
    elseif ($output['status'] == 'error')
    {
        echo '<div class="alert alert-error">';
    }
    else
    {
        echo '<div class="alert alert-error">';
    }

    echo '<button type="button" class="close" data-dismiss="alert">&times;</button>';
    echo '<strong>' . $output['title'] . '</strong>' . $output['message'];
    echo '</div>';
}
?>

2 个答案:

答案 0 :(得分:1)

我不确定您的自定义模板类对->title()->set()->build()的影响。但看起来您仍然会将$data传递到您的视图中。

因此,您只需在视图中执行echo $output;即可。

编辑:

我认为$output仍然出现的原因是因为这些代码行不在if语句中:

echo '<button type="button" class="close" data-dismiss="alert">&times;</button>';
echo '<strong>' . $output['title'] . '</strong>' . $output['message'];
echo '</div>';

尝试在if语句中移动它们,只有在设置$output时才会打印出来。

答案 1 :(得分:0)

我已将默认设置为会话闪存数据值,在这种情况下,首次加载时该值将为false,因为如果未设置数据,它将返回。所以我需要添加一个条件来检查值是否为假。