I’m trying to send my validation errors to another method by using redirect
public function save()
{
//validasi input
if (!$this->validate([
'judul' => 'required|is_unique[komik.judul]'
])) {
return redirect()->to('/komik/create')->withInput();
}
this is the create() method
public function create()
{
session();
$data = [
'title' => 'Form Tambah Data Komik',
'validation' => ConfigServices::validation()
];
return view('komik/create', $data);
}
This is a snippet of my create.php
view form where I’m trying to validate
<form action="/komik/save" method="post" enctype="multipart/form-data">
<?php d($validation) ?>
<?= $validation->listErrors();; ?>
The problem is that the validation errors in save()
is not sent to the create()
method. But the validation errors exist in the save()
method which I can prove by adding
$validation = ConfigServices::validation(); dd($validation);
in save()
. This is what happens when I click "Tambah Data" button after I add the code
as you can see there is a validation error, it’s just not sent to the create()
method
I tried using return view()
, this works but it creates another problem. I would like to use return redirect()
instead.
This is my routes
$routes->get('/', 'Pages::index');
$routes->get('/komik/create', 'Komik::create');
$routes->get('/komik/edit/(:segment)', 'Komik::edit/$1');
$routes->post('/komik/save', 'Komik::save');
$routes->delete('/komik/(:num)', 'Komik::delete/$1');
$routes->get('/komik/(:any)', 'Komik::detail/$1');
What can I do to solve this problem? Thanks
2
Answers
I found the solution, apparently there's a bug with
redirect()->withInput()
in CI. You need to usevalidation_errors()
,validation_list_errors()
andvalidation_show_error()
to display validation error. Also you don't need to write$validation = ConfigServices::validation();
. Read https://codeigniter4.github.io/CodeIgniter4/installation/upgrade_430.html#redirect-withinput-and-validation-errorsA. Use Flashdata instead.
I.e:
save()
method.with()
B. Then, modify the
create()
method to pass on the flashed data to the View.create()
method.C. Lastly, in your View file (
create.php
), you may access the passed-on data normally.create.php
View file.