Search code examples
phpformshttp-redirectnotificationsflash-message

Display flash messages after submiting a php form


I want to display some notifications after submiting a form in php. I don't know if I'm doing the right way... I want to submit my form, refresh my datas inside the form and display the notification.

For example, this is my add function :

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();
        }
    }
}

In my case, nothing is displayed, I don't know how to do.

My session class is like this :

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']);
        }
    }

}

Can you explain to me the way to do this ?

Thanks a lot !

EDIT

This is my 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;
}

My view is like this

{% 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 %}

Solution

  • For checking that session started, can you change your code?

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

    I think $_SESSION global variable always will set by default.

    UPD.

    And as I noticed, You first flash the messages and then redirect the page

    UPD2

    After quick rewiew I think your addNewPost() method must be like this

    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();
        }
    }
    

    Notice that you must call $session = new Session(); $session->flash(); when you process your success request(index.php?p=blog)