CodeIgniter 4 - How to display Flashdata inside a View? - php

I'm upgrading my project from CodeIgniter 3 to CodeIgniter 4,
I'm trying to display a flashdata message inside a view but unfortunately I get differents error for each method I try.
In CodeIgniter 3, I used to call something like:
<?php if ($this->session->flashdata('message')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?php echo $this->session->flashdata('message'); ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php endif; ?>
I try the same in CodeIgniter 4 but I get this error:
ErrorException
Undefined property: CodeIgniter\View\View::$session
Can any one show me how to achieve this ?
Thanks in advance.

You can use session() function directly:
<?php if (session()->getFlashdata('message') !== NULL) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?php echo session()->getFlashdata('message'); ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php endif; ?>

The context ($this) is an instance of the View class --> you don't have access to the Session instance directly
You can create new instance below
$session = \Config\Services::session();

In CodeIgniter 4 the new way to set Flash data $session->setFlashdata('item', 'value'); and to view $session->getFlashdata('item');
You can check it out here : Set Flash data in session in CodeIgniter

I just use another way to display a flashdata and it works fine.
In my controller, I added a new index to the data passed to the view:
$data['message'] = "Sorry, you must login first";
return view('login', $data);
Then in the view login.php I call it like this:
<?php if (isset($message)) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?php echo $message; ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php endif; ?>
UPDATE:
I just use the markAsFlashdata() method and It works perfectly. Here's what I did in the controller just before the return method:
$_SESSION['error'] = 'Sorry, you must login first';
$session = session();
$session->markAsFlashdata('error');
Then in the view I access the flashdata using $_SESSION['error']:
<?php if (isset($_SESSION['error'])): ?>
<div class="alert alert-warning" role="alert">
<?= $_SESSION['error']; ?>
</div>
<?php endif;?>

Add this line just after echo $this->section('content');
$session = \Config\Services::session();
<?php if (isset($message)) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?php echo $message; ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php endif; ?>

For now my solution has been to create a view method in BaseController.php.
The idea is to add more "common" info into the $data array.
/* In BaseController.php */
/**
* view function replaced
*/
public function view(string $name, array $data = [], array $options = []): string
{
// Inject global data
$data = array_merge($data,["controller" => $this]);
return view($name,$data,$options);
}
/**
* Temporary message
*/
public function flash($message, $type = 'info') {
$this->session->setFlashdata('flash_message',
["message" => $message, "type" => $type]);
}
public function getFlash() {
return $this->session->getFlashdata('flash_message');
}
/* In the descendant controller */
return $this->view('products/list',['products' => $products]);
/* In the view */
<div id="messages">
<?php if($flash = $controller->getFlash()) : ?>
<?= view_cell('Base::alert', $flash); ?>
<?php endif ?>
</div>

Related

How to Display redirect()->to()->with() in view (CI4)

I am trying to set a flashdata in redirect but it's not getting picked up so I turn to redirect()->to()->with() function. However, I don't know how to call it in my view. I tried copying how it's done in Laravel but it's not working.
Here's my redirect code:
return redirect()->to(base_url('categories'))->with('msg', 'You are not allowed to access that category.');
What I try in my view:
if(session()->has('msg')){ echo session()->get('msg'); }
I've been looking for it for hours but can't find any in the documentation. Appreciate any help.
I'm not sure if this is just a cache thing or something else but I removed, updated something, then put back my old code and it worked.
In my controller:
$session->setFlashdata('success', false);
$session->setFlashdata('msg', 'You are not allowed to access that category.');
$session->setFlashdata('alert', 'alert-warning');
return redirect()->to(base_url('courses'));
In my view:
<?php
if($session->getFlashdata('msg') != ''){
?>
<div class="alert <?= $session->getFlashdata('alert') ?> alert-dismissible fade show" role="alert">
<span class="text-start mb-0"><?= $session->getFlashdata('msg') ?></span>
<button type="button" class="btn-close login-btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php
}
?>
I also discovered that using with() is the same as calling getFlashdata in view:
return redirect()->to(base_url('courses'))->with('msg', 'You are not allowed to access that category.');

Cannot get Session message from Handler class laravel

What I try to do is to get a message in the session when redirecting back to the page from exception handler class, When I get 'PostTooLargeException' It should back to page with a message.
If statement in Handler class
public function render($request, Exception $exception)
{
//...
if ($exception instanceof PostTooLargeException) {
$test = redirect()->route('clientbank.create')->with('message', 'File too large!'); //Cannot get message
return $test;
//dump($gg);
dump(session('message'));
dd('stop');
}
// this will still show the error if there is any in your code.
return parent::render($request, $exception);
}
}
In dump(session('message')); I can see the message .
In blade page
#elseif(session('message'))
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{ session('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
In controller
public function create()
{
dump(session('message')); <-- getting null !!!
return view('clinetbank.bank.cratebank');
}
What I try to do is use empyt(session('message') I always get an empty session.
Also, I try this questions but not work for me.
I use laravel 5.8
Any ideas, please ?.

Redirect url with Variable in Laravel 5

How to Redirect Url in following format:
My code:
return Redirect::to('home/viewcustomer/$cusid')
->with('status','success')
->with('message','success');
Example :
home/viewcustomer/8
You need to take care about your string quotes while using variables within string quotes. Just update your code
Redirect::to('home/viewcustomer/$cusid')
into
Redirect::to("home/viewcustomer/$cusid")
^^ ^^
Well i usually use
Session and Redirect so you have to define it in your controller
Use Session;
Use Redirect;
Then
public function example(){
Session::flash('status','Your message');
return Redirect::to('/yourRoute');
}
If you want to show your message in your view you have to do this...
#if(Session::has('status'))
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<p><strong>Success!!</strong> </p>
<ul>
<li>{{ Session::get('status') }}</li>
</ul>
</div>
#endif
Hope this helps!!
Ps: Sorry for the bad english :)

Yii2: How to use events to set flash messages when new records get created in MySQL (event listeners)

How do I notify user on dashboard(index.php) as soon as new records get created in database or any changes made in database
Iknow I need to query like
CREATE TRIGGER notifyMe
ON table1
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DB AutoMailer',
#recipients = 'user#example.com',
#body = 'The DB has changed',
#subject = 'DB Change';
GO
but dont know how to do it by using Yii2 Events
In controller:
Yii::$app->session->setFlash('success', "Your message to display");
In view
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Saved!</h4>
<?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>

Confirmation alert box with Laravel contact form

I am new to Laravel but have managed to get a contact form working and showing validation errors when there are some.
However I do have one problem and have no idea how to handle it in Laravel. When a message is sent (validation rules pass) I would like to display an alert box (Bootstrap style) saying 'Thanks, message has been sent'.
CODE
public function postContact()
{
$formData = Input::all();
// input validator with its rules
$validator = Validator::make(
array(
'name' => $formData['name'],
'email' => $formData['email'],
'subject' => $formData['subject'],
'message' => $formData['message']
),
array(
'name' => 'required|min:3',
'email' => 'required|email',
'subject' => 'required|min:6',
'message' => 'required|min:5'
)
);
if ($validator -> passes()) {
// data is valid
Mail::send('emails.message', $formData, function($message) use ($formData) {
$message -> from($formData['email'], $formData['name']);
$message -> to('info#company.com', 'John Doe') -> subject($formData['subject']);
});
return View::make('contact');
} else {
// data is invalid
return Redirect::to('/contact') -> withErrors($validator);
}
}
How can I achieve this in Laravel 4?
You could use the with method of the Redirect class:
if ($validator -> passes()) {
// data is valid
Mail::send('emails.message', $formData, function($message) use ($formData) {
$message -> from($formData['email'], $formData['name']);
$message -> to('info#company.com', 'John Doe') -> subject($formData['subject']);
});
//Redirect to contact page
return Redirect::to('/contact')->with('success', true)->with('message','That was great!');
} else {
// data is invalid
return Redirect::to('/contact') -> withErrors($validator);
}
You will be redirected to the contact page with the session variables success and message set.
Use them for an alert in your view, e.g. in a Bootstrap Alert:
with Blade
#if(Session::has('success'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Success!</strong> {{ Session::get('message', '') }}
</div>
#endif
without Blade
<?php if(Session::has('success')): ?>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Success!</strong> <?php echo Session::get('message', ''); ?>
</div>
<?php endif; ?>
If you are using them like this you can even provide success alerts, info alerts, or any alert you want to.
When your data is INVALID you use the withErrors() method to pass some data (erros) to your route.
You can use the same process with any kind of data.
For example:
return View::make('contact')->withMessage("Thanks, message has been sent");
This method withMessage() will create a new variable message and store it in the Session for one request cycle.
So, in your view you can access it like this:
#if(Session::has('message'))
<div class="alert-box success">
{{ Session::get('message') }}
</div>
#endif
I assume you are using Bootstrap so this answer will show the message in pop up window (I test it on Laravel 5)
return View::make('contact')->with('message', "Thanks, message has been sent");
Make sure this code will be added in footer
<!-- Show Pop up Window if there is message called back -->
<?php
if(session('message'))
{
echo '<script>
document.getElementById("popup_message").click();
</script>';
}
?>
Add this function in helper.php so you can use it anywhere in your code
function message_pop_up_window($message)
{
$display = '
<a class="popup_message" id="popup_message" data-toggle="modal" data-target="#message" href="#"></a>
<div class="modal fade" id="message" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messsage </h4>
</div>
<div class="modal-body">
<p>'.$message.'</p>
</div>
</div>
</div>
</div>
</div>';
return $display;
}
Then call the function in you page
{!! message_pop_up_window($message) !!}

Categories