无法在表单验证后保留输入值Codeigniter 4



这是我以前看到过的一个问题,但我一直无法找到新版本Codeigniter的答案。

控制器

<?php

namespace AppControllers;

class SendEmail extends BaseController
{
public function index($validation = NULL){
// Load form helper
helper('form');
// Instantiate session
$session = ConfigServices::session();
// Set css, javascript, and flashdata
$data = [
'css' => array('contact.css'),
'js' => array('contact.js'),
'validation' => $validation,
'success' => $session->get('success')
];
// Show views
echo view('templates/header', $data);
echo view('contact', $data);
echo view('templates/footer', $data);
}
public function sendEmail(){
// Instantiate request
$request = $this->request;
// Captcha API
$captchaUser = $request->getPost('g-recaptcha-response');
// Captcha Key loaded from a file left out of the repo
$captchaConfig = config('Config\Credentials');
$captchaKey = $captchaConfig->captchaKey;
$captchaOptions = [
'secret' => $captchaKey,
'response' => $captchaUser
];
$client = ConfigServices::curlrequest();
$captchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', ['form_params' => $captchaOptions]);
$captchaObj = json_decode($captchaResponse->getBody());
// Load validation library
$validation = ConfigServices::validation();
// Set validation rules
$validation->setRules([
'name' => 'required|alpha_dash|alpha_space',
'email' => 'required|valid_email',
'subject' => 'required|alpha_numeric_punct',
'message' => 'required|alpha_numeric_punct'
]);
// Validate inputs
if (!$this->validate($validation->getRules())){
// Run index function to show the contact page again
$this->index($this->validator);
}
// Validate captcha
elseif(!$validation->check($captchaObj->success, 'required')){
$validation->setError('captcha','Did not pass captcha. Please try again.');
$this->index($validation->getErrors());
}
else{
// Set variables to input
$name = $request->getPost('name');
$email = $request->getPost('email');
$subject = $request->getPost('subject');
$message = $request->getPost('message');
// Load email class
$emailC = ConfigServices::email();
// Set email settings
$emailC->setFrom('bensirpent07@benkuhman.com', $name);
$emailC->setReplyTo($email);
$emailC->setTo('benkuhman@gmail.com');
$emailC->setSubject($subject);
$emailC->setMessage($message);
// Testing section
echo '<br>'.$name.'<br>'.$email.'<br>'.$subject.'<br>'.$message;
/* Temporarily disabled for testing purposes
// Send email
if($emailC->send(false)){
// Redirect
return redirect()->to(base_url().'/contact')->with('success', true);
}else{
// Display error
throw new CodeIgniterDatabaseExceptionsDatabaseException();
};
*/
}
}
}

联系人视图

<div class="container">
<div class="row">
<div class="col">
<div class="alert alert-success align-center" id="message-alert" <?php if($success){echo 'style="display:block"';} ?>>Message successfully sent!</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<?php echo form_open('send_email', ['id'=>'contactForm'])?>
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Name" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('name')){echo $validation->getError('name');}?></p>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="email" placeholder="E-mail" required>
<small id="emailHelp" class="form-text">I'll never share your email with anyone else.</small>
<?php //echo $validation->email;?>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('email')){echo $validation->getError('email');}?></p>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="Subject" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('subject')){echo $validation->getError('subject');}?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" rows="5" class="form-control" id="message" placeholder="Type your message here." required></textarea>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('message')){echo $validation->getError('message');}?></p>
</div>
<button id="submitButton" type="submit" class="btn btn-primary g-recaptcha" data-sitekey="6Ldf07AZAAAAAAflQCaJcWgGFCWevCswpIrm0mJN" data-callback='onSubmit' data-action='submit'>Submit</button>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('captcha')){echo $validation->getError('captcha');}?></p>
<?php echo form_close()?>
</div>
</div>
</div>
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>

根据我对CodeIgniter中验证工作方式的理解,当您在表单验证后加载视图时,它会使用以前输入的值更新值。CodeIgniter 4的情况似乎并非如此。我还尝试过直接加载视图,而不是在验证失败时调用索引函数。仍然不会填写表单值。

现在我可以通过$data数组将这些值传递给index函数。这就是我现在要使用的修复方法。这更像是一次健全性检查,看看我是否缺少一些基本的东西,或者我是否错误地使用了CodeIgniter4的验证格式。

在CI4中,您可以使用old((函数在表单验证时保留输入值:

查看文件:

<input type="tel" name="phone" value="<?= old('phone'); ?>">

在控制器中,您必须在重定向((代码中使用withInput((:

$validation =  ConfigServices::validation();
$request = ConfigServices::request();
// your input validation rules
$validation->setRules(...)
if($request->getMethod() == "post" && ! $validation->withRequest($request)->run()) {
return redirect()->back()->withInput()->with('error', $this->validation->getErrors());
} else {
// form validation success
}

相关内容

  • 没有找到相关文章

最新更新