我想检查一个表格并显示任何错误。我不明白 Code Igniter 4 如何让我检查$validation
变量是否存在以显示警报。
当我用create()
函数显示表单时,我收到一条错误消息,告诉我变量不存在,这是正常的。
我的问题如下,如何检查视图中是否存在错误以显示警报?
我的控制器
<?php namespace App\Controllers;
use CodeIgniter\Model\Site_model;
class Site extends BaseController
{
public function __construct()
{
helper('html', 'url');
}
public function create()
{
helper(['form']);
echo view('createSite');
}
public function store()
{
helper(['form']);
$validation = \Config\Services::validation();
$validation->setRules([
'siteName' => 'required',
'password' => 'required',
'passwordConfirmation' => 'required|matches[password]'
],
[ // Errors
'siteName' => [
'required' => 'Merci de fournir un nom de site'
],
'password' => [
'required' => 'Merci de fournir un mot de passe'
],
'passwordConfirmation' => [
'required' => 'Merci de confirmer le mot de passe',
'matches' => 'Les mots de passe ne correspondent pas.'
]
]
);
$validation->withRequest($this->request)
->run();
if (! $this->validate([]))
{
echo view('createSite', [
'validation' => $validation
]);
}
else
{
echo view('Success');
}
}
}
我的观点
...
<main role="main" class="container vertical-center">
<div class="col">
<div class="alert alert-danger" role="alert">
<?= $validation->listErrors(); ?>
</div>
<?= form_open('site/store') ?>
<div class="form-group">
<label for="siteName" class="text-white">Nom du site</label>
<input type="text" class="form-control" id="siteName" name="siteName" value="" placeholder="Bordeaux" required>
<div class="invalid-feedback">
Merci de renseigner un nom de site.
</div>
</div>
<div class="form-group">
<label for="password">Mot de passe d'administration</label>
<input type="password" class="form-control" id="password" name="password" required>
<div class="invalid-feedback">
Merci de renseigner un mot de passe.
</div>
</div>
<div class="form-group">
<label for="passwordConfirmation">Confirmation du mot de passe d'administration</label>
<input type="password" class="form-control" id="passwordConfirmation" name="passwordConfirmation" required>
<div class="invalid-feedback">
Merci de confirmer le mot de passe.
</div>
</div>
<button class="btn btn-block btn-success" type="submit" name="submit-form">Envoyer</button>
</form>
</div>
...
我<?= $validation->listErrors(); ?>
用来显示错误,但在第一次显示表单时,在验证它之前,没有错误,所以我得到 Undefined variable: validation