Search code examples
phpcodeignitercodeigniter-4

Redirect with error input validation on CodeIgniter didnt works


Iam currently using CodeIgniter version 4.3.3

Im building blog site with CRUD. and create Posting feature...

When i try to create a form on purpose to create posting (insert to database), it works fine... but when trying to add validation features (create error message), it didnt works... can you help me which part is missing/is there any problems?

routes config:

$routes->get('/', 'Pages::index');
$routes->get('/blogs', 'Blogs::index');
$routes->get('/blogs/create', 'Blogs::create');
$routes->post('/blogs/post', 'Blogs::post');
$routes->get('/blogs/(:segment)', 'Blogs::detail/$1');

controller:

// method create (here is form)
public function create()
{
    session();
    $data = [
        'title' => 'Post Blog',
        'validation' => \Config\Services::validation()
    ];

    return view('blogs/create', $data);
}

// method post for insert to db
public function post()
{
    // validasi input
    if (!$this->validate([
        'judul' => 'required|is_unique[blogs.judul]',
        'konten' => 'required',
    ])) {
        $validation = \Config\Services::validation();

// this line is my problem, validation didnt works. (only redirect works)
        return redirect()->to('blogs/create')->withInput()->with('validation', $validation);
    }

    $slug = url_title($this->request->getVar('judul'), '-', true);
    $this->blogsModel->save([
        'judul' => $this->request->getVar('judul'),
        'konten' => $this->request->getVar('konten'),
        'slug' => $slug,
        'gambar' => 'post.png',
    ]);

    session()->setFlashdata('post', 'Artikel berhasil diposting.');

    return redirect()->to('blogs');
}

view for error message:

<?= $validation->listErrors(); ?>
<form action="<?= site_url('blogs/post') ?>" method="post">
<?= csrf_field(); ?>
...
<div class="invalid-feedback">
<?= $validation->getError('judul'); ?>
</div>

I want to make my form input validation works. if there is alternate way to use another method, please enlighten me... thanks!


Solution

  • Thanks for your helps... Im already solved it... turns out in CodeIgniter 4.3.3 cannot use

    $validation = \Config\Services::validation();
    $validation->listErrors();
    

    instead using this :

    validation_list_errors();
    
    // or
    
    validation_show('inputField');
    

    but u need form helper to execute this function... so use it!

    // controler method:
    
    helper('form');
    
    // view form
    
    <?= form_open('action/link'); =>
    ...
    <?= form_close(); =>