【问题标题】:Display flash messages after submiting a php form提交 php 表单后显示 flash 消息
【发布时间】:2024-01-10 12:17:01
【问题描述】:

我想在 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 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 %}

【问题讨论】:

  • 你在处理别人的代码库吗?还是基于某些框架?
  • 不,这是我的工作,我只是用树枝做模板。
  • 好吧,你有点尝试做一个单例(用于会话)。你可能想一直坚持下去。
  • 这将很难提供帮助,因为代码是不公开的,但它的大部分没有显示(任何类的其余部分都有方法addNewPostPostsManagerPost ,整个路由机制等。我可以说有很多奇怪之处。例如,您似乎有一个session 类,但偶尔也访问$_SESSION。您尝试显示一条消息并执行重定向以相同的方法(只会发生一种情况)等。
  • 向会话添加内容而不是在同一页面加载期间运行它有什么意义?

标签: php forms redirect notifications flash-message


【解决方案1】:

为了检查会话是否开始,你能改变你的代码吗?

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)

【讨论】:

  • 我在我的构造中替换了它,它仍然没有显示我的通知
  • 是的,谢谢,我已经更改了顺序(设置通知,然后重定向),但它不起作用。
  • 在任何键中,您必须调用您的 Session 类,您是在您的视图中还是在任何地方做的?像这样 if(isset($_POST['publish'])){ .....} else {$session = new Session(); $session->flash();}
  • 不,我不是,我在我的控制器中直接使用我的 2 种方法 setFlash() 和 flash() ...
  • 是的,我确定这对于一个 SO 答案来说实在是太深入了,但不知何故,我总是试图回答这类问题!