codeigniter4 / CodeIgniter4

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
5.3k stars 1.89k forks source link

validation form_error() #911

Closed catwithredhat closed 6 years ago

catwithredhat commented 6 years ago

Why theres no helper form_error() like ci3?

https://bcit-ci.github.io/CodeIgniter4/helpers/form_helper.html

The doc describe abt form_error But theres no function form_error

https://github.com/bcit-ci/CodeIgniter4/blob/develop/system/Helpers/form_helper.php

lonnieezell commented 6 years ago

You are correct, form_error no longer exists. This is because validation was separated from the form to make it more flexible. The fact that it still exists in the docs is an artifact of porting the docs over from CI3.

See the Validation docs for a (hopefully) up to date explanation.

akrindev commented 6 years ago

so sad heard dat the form_error helper is removed on ci4, it is very helpful

lonnieezell commented 6 years ago

@akrindev It's not needed. use session() and it's just as simple:

In controller:

if (! $this->validate($rules))
{
    return redirect()->back()->withInput()->with('errors', $userModel->errors());
}

In view:

<div class="invalid-feedback">
    <?= session('errors.pass_confirm') ?>
</div>
akrindev commented 6 years ago

Controller

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class UserController extends Controller
{  
  public function login()
  {
    helper('form');

    echo view('header');
    echo view('login');
    echo view('footer');
  }

  public function loginPost()
  {
    if(! $this->validate([
        'email' => 'required|valid_email',
        'password' => 'required'
    ]))
    {
        return $this->login(); 
    }

    // everything is fine

  }

}

view

<div class="form-group form-group-sm">
    <label>email or username</label>
    <input type="text" name="email" class="form-control">
    <?= form_error('email');   ?>
</div>

if we want helper

if( ! function_exists('form_error'))
{  
    function form_error(string $field = '', string $template = 'single')
    {
      return Services::validation()->showError($field, $template);
    }   
}

but redirecting with input is fine ;)