提交 php 表单后显示即时消息

Display flash messages after submiting a php form

我想在 php 中提交表单后显示一些通知。 我不知道我的做法是否正确... 我想提交我的表单,刷新表单内的数据并显示通知。

例如,这是我的添加函数:

public function addNewPost(){
    $manager = new PostsManager($this->db);
    if(isset($_POST['publish'])){
        if (empty($_POST['title']) || empty($_POST['header']) || empty($_POST['author']) || empty($_POST['content']))
        {
            $_SESSION['addPostDatas'] = $_POST;
            $session = new Session();
            $session->setFlash('"Title", "Header", "Author" and "Content are required and cannot be empty"');
            $session->flash();
            header('Location: '.$_SERVER['REQUEST_URI']);
        }
        else
        { 
            $newpost = new Post([
                        'title' => $_POST['title'],
                        'header' => $_POST['header'],
                        'author' => $_POST['author'],
                        'date' => date("Y-m-d H:i:s"),
                        'content' => $_POST['content'],
                        'featuredImg' => $this->uploadImg()
                        ]); 
            $manager->add($newpost); // Create a new post
            unset($_SESSION['addPostDatas']);
            header('Location: index.php?p=blog');
            $session = new Session();
            $session->setFlash('The post was published !', 'success');
            $session->flash();
        }
    }
}

在我的情况下,没有任何显示,我不知道该怎么做。

我的会话 class 是这样的:

Class Session{

    public function __construct(){
        if(!isset($_SESSION)){ 
            session_start(); 
        } 
    }

    public function setFlash($message, $type = 'danger'){
        $_SESSION['flash'] = array(
            'message' => $message,
            'type'    => $type
        );
    }

    public function flash(){
        if(isset($_SESSION['flash'])){
            ?>
            <div id="alert" class="alert alert-<?php echo $_SESSION['flash']['type'] ?>" role="alert">
                 <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                <strong><?php print_r($_SESSION['flash']['message']); ?></strong>
            </div>
            <?php
            unset($_SESSION['flash']);
        }
    }

}

你能告诉我怎么做吗?

非常感谢!

编辑

这是我的index.php

require 'vendor/autoload.php';
use natinho68\Models\SPDO as SPDO;

use natinho68\Controllers\Session as Session;
use natinho68\Models\PostsManager as PostsManager;
use natinho68\Controllers\MailController as MailController;
use natinho68\Controllers\Controller as Controller;


$db = new SPDO();
$session = new Session();
$posts = new PostsManager($db);
$contact = new MailController();

// Routing
$page = "home";
if(isset($_GET['p'])){
    $page = $_GET['p'];
}

// Rendu du template

// Chargement des templates dans le dossier templates
$loader = new Twig_Loader_Filesystem(__DIR__ . '/Views');
$twig = new Twig_Environment($loader, [
    'cache' => false, // __DIR__ . '/tmp'
        'debug' => true
    ]);
$twig->addExtension(new Twig_Extension_Debug());

if(!empty($_SESSION['addPostDatas'])){
$twig->addGlobal('addPostDatas', $_SESSION['addPostDatas']);    
}



$controller = new Controller($twig, $db);

switch ($page){

    case 'home' :
    $controller->home('home.twig');
        $contact->mailer();
    break;

    case 'contact' :
    echo $twig->render('contact.twig');
        $contact->mailer();
    break;

    case 'blog':
    echo $twig->render('allPosts.twig', ['allPosts' => $posts->getAllPosts()]);
    break;

    case 'singlepost' :
        $controller->showPost($_GET['id'], 'singlePost.twig');
        break;

        case 'editpost' :
        $controller->showPost($_GET['id'],'editpost.twig');
        $controller->updatePost();
        $controller->deletePost();
    break;

        case 'add-post' :
        $controller->addPostView('addPost.twig');
        $controller->addNewPost();
    break;

    default: 
    header('HTTP/1.0 404 Not Found');
    echo $twig->render('404.twig');
    break;
}

我的看法是这样的

{% extends 'layout.twig' %}
{% import 'form.twig' as form %}
{% block head %}
    <title>Add a post</title>
{% endblock %}

{% block content %}
<div class='page-header'>
  <div class='btn-toolbar pull-right'>
    <div class='btn-group'>
      <a href="?p=blog" type="button" class="btn btn-default">View all blog posts</a>
    </div>
  </div>
    <h1>Add post</h1>
</div>
<form action="index.php?p=add-post" method="post" id="add" name="add" enctype="multipart/form-data">
    {{ form.input('title', 'Title', addPostDatas.title)  }}
        {{ form.textarea('header', 'Header', 03, addPostDatas.header) }}
    {{ form.textareacontent('content', 'Content', 30, addPostDatas.content) }}
        {{ form.input('author', 'Author', addPostDatas.author) }}
        {{ form.file('image', 'Optional - Select a featured image (max size 4Mo)')}}
        <div class="form-group"><br>
        <button type="submit" class="btn btn-success" name="publish">Publish the post</button>
    </div>

</form>


{% endblock %}

为了检查会话是否已启动,您可以更改代码吗?

public function __construct(){
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
}

我认为 $_SESSION 全局变量总是默认设置。

UPD.

正如我所注意到的,您首先闪烁消息然后重定向页面

UPD2

快速回顾后,我认为您的 addNewPost() 方法必须是这样的

public function addNewPost()
{
    $session = new Session();
    $manager = new PostsManager($this->db);
    if (isset($_POST['publish'])) {
        if (empty($_POST['title']) || empty($_POST['header']) || empty($_POST['author']) || empty($_POST['content'])) {
            $_SESSION['addPostDatas'] = $_POST;
            $session->setFlash('"Title", "Header", "Author" and "Content are required and cannot be empty"');
            header('Location: ' . $_SERVER['REQUEST_URI']);
            exit();

        } else {
            $newpost = new Post([
                'title' => $_POST['title'],
                'header' => $_POST['header'],
                'author' => $_POST['author'],
                'date' => date("Y-m-d H:i:s"),
                'content' => $_POST['content'],
                'featuredImg' => $this->uploadImg()
            ]);
            $manager->add($newpost); // Create a new post
            unset($_SESSION['addPostDatas']);
            $session->setFlash('The post was published !', 'success');
            header('Location: index.php?p=blog');
            exit();

        }
    } else {
        $session->flash();
    }
}

注意你必须调用$session = new Session(); $session->flash();当您处理成功请求时(index.php?p=blog)