i am new to codeigniter 4, i am currently building a registration form. when i submit reg form it give error of required fields even if i fill all fields with correct data.
here is my code snippet
function register() {
$data = [];
helper(['form']);
if($this->request->getMethod() == "post"){
$validation = \Config\Services::validation();
$validation->setRules([
"firstname" => ["label" => "First Name", "rules" => "required|min_length[3]|max_length[20]"],
"lastname" => ["label" => "Last Name", "rules" => "required|min_length[3]|max_length[20]"],
"email" => ["label" => "Email", "rules" => "required|min_length[3]|max_length[20]|valid_email|is_unique[users.email]"],
"password" => ["label" => "Password", "rules" => "required|min_length[8]|max_length[20]"],
"password_confirm" => ["label" => "Confirm Password", "rules" => "matches[password]"],
]);
if($validation->run()){
$user = new UserModel();
$userdata = [
"firstname" => $this->request->getVar("firstname"),
"lastname" => $this->request->getVar("lastname"),
"email" => $this->request->getVar("email"),
"password_confirm" => $this->request->getVar("password_confirm"),
];
$user->save($userdata);
$session = session();
$session->setFlashData("success", "Successful Registration");
return redirect()->to('/');
}else{
$data["validation"] = $validation->getErrors();
}
}
echo view('templates/header', $data);
echo view('register');
echo view('templates/footer');
}
this is the registration form i am trying to validate.
<form class="" action="/register" method="post">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="firstname">First Name</label>
<input type="text" class="form-control" name="firstname" id="firstname" value="<?= set_value('firstname') ?>">
<small class="text-danger"><?= isset($validation) ? $validation['firstname'] : null; ?></small>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="lastname">Last Name</label>
<input type="text" class="form-control" name="lastname" id="lastname" value="<?= set_value('lastname'); ?>">
<small class="text-danger"><?= isset($validation) ? $validation['lastname'] : null ; ?></small>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" name="email" id="email" value="<?= set_value('email') ?>">
<small class="text-danger"><?= isset($validation) ? $validation['email'] : null ; ?></small>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" value="">
<small class="text-danger"><?= isset($validation) ? $validation['password'] :null ; ?></small>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="password_confirm">Confirm Password</label>
<input type="password" class="form-control" name="password_confirm" id="password_confirm" value="">
<small class="text-danger"><?= isset($validation) ? $validation['password_confirm'] :null ; ?></small>
</div>
</div>
</div>
<div class="row">
<div class="col-12 col-sm-4">
<button type="submit" class="btn btn-primary">Register</button>
</div>
<div class="col-12 col-sm-8 text-right">
Already have an account
</div>
</div>
</form>
and here is the output i am getting even if i fill all fields.
If you want to always validate data going into that model, you might want to consider doing the validation inside the model:
https://codeigniter.com/user_guide/models/model.html#validating-data
In case you want to validate the data outside the model you have to tell the validation service on where the data is, because it can be POST, GET or even just an array that you have from something else.
In your case you need to validate the data with your request.
https://codeigniter.com/user_guide/libraries/validation.html?highlight=validation#withrequest
So your validation code should be something like:
if($validation->withRequest($this->request)->run()){ }
This will look for the data in both GET and POST.
If you want to specify and only use POST
if($validation->withRequest($this->request->getPost())->run()){ }
try this style
function register()
{
$data = [];
helper(['form']);
if ($this->request->getMethod() == "post") {
$validation = \Config\Services::validation();
$rules = [
"firstname" => [
"label" => "First Name",
"rules" => "required|min_length[3]|max_length[20]"
],
"lastname" => [
"label" => "Last Name",
"rules" => "required|min_length[3]|max_length[20]"
],
"email" => [
"label" => "Email",
"rules" => "required|min_length[3]|max_length[20]|valid_email|is_unique[users.email]"
],
"password" => [
"label" => "Password",
"rules" => "required|min_length[8]|max_length[20]"
],
"password_confirm" => [
"label" => "Confirm Password",
"rules" => "matches[password]"
]
];
if ($this->validate($rules)) {
$user = new UserModel();
$userdata = [
"firstname" => $this->request->getVar("firstname"),
"lastname" => $this->request->getVar("lastname"),
"email" => $this->request->getVar("email"),
"password_confirm" => $this->request->getVar("password_confirm"),
];
$user->save($userdata);
$session = session();
$session->setFlashData("success", "Successful Registration");
return redirect()->to('/');
} else {
$data["validation"] = $validation->getErrors();
}
}
echo view('templates/header', $data);
echo view('register');
echo view('templates/footer');
}
just put your rules inside an array and pass it to controller validate function..
i hope it's work
Related
When I do post form in laravel and then validate it from the controller I get this response :
302 found
nothing useful, I`ve tried everything but nothing worked with me.
My Form blade :
<form action="{{route('newitem')}}" method="post">
#csrf
<div class="mb-3">
<label for="item name" class="form-label">Email address</label>
<input type="text" class="form-control" id="item name" name="item_name" >
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" class="form-control" id="price" name="item_price">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
my controller :
public function new_item(Request $rq){
$validated = $rq->validate(
[
'item_name' => 'required|string|min:4|max:90',
'item_desc' => 'string|min:4|max:90',
'item_price' => 'required|integer|min:4'
]
);
UsrsItem::create([
'item_name' => $validated->item_title,
'item_price' => $validated->item_price,
]);
}
I hope someone can help me with that :<
Contrroller Code
public function new_item(Request $rq){
$validated = $rq->validate(
[
'item_name' => 'required|string|min:4|max:90',
'item_desc' => 'string|min:4|max:90',
'item_price' => 'required|integer|min:4'
]
);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
UsrsItem::create([
'item_name' => $validated->item_title,
'item_price' => $validated->item_price,
]);
return response()->json(['success'=>'Record is successfully added']);
}
Put This In Blade File
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
I'm running codeigniter 4.1.5 and php 8.1.0 and when i try to input data this is the error i got
Uncaught ErrorException: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in C:\xampp\htdocs\cikaryawan\system\Validation\FormatRules.php:253
Stack trace:
#0 [internal function]: CodeIgniter\Debug\Exceptions->errorHandler()
#1 C:\xampp\htdocs\cikaryawan\system\Validation\FormatRules.php(253):
strtolower()
#2 C:\xampp\htdocs\cikaryawan\system\HTTP\RequestTrait.php(151): CodeIgniter\Validation\FormatRules->valid_ip()
#3 C:\xampp\htdocs\cikaryawan\app\Views\errors\html\error_exception.php(206):
CodeIgniter\HTTP\Request->getIPAddress()
#4 C:\xampp\htdocs\cikaryawan\system\Debug\Exceptions.php(229): include('...')
#5 C:\xampp\htdocs\cikaryawan\system\Debug\Exceptions.php(232): CodeIgniter\Debug\Exceptions->CodeIgniter\Debug{closure}()
#6 C:\xampp\htdocs\cikaryawan\system\Debug\Exceptions.php(116): CodeIgniter\Debug\Exceptions->render()
#7 [internal function]: CodeIgniter\Debug\Exceptions->exceptionHandler()
#8 {main}
in my .env folder
CI_ENVIRONMENT = development
database.default.hostname = localhost
database.default.database = cikaryawanauth
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
database.default.DBPrefix =
this is my register.php
<body>
<div class="container">
<div class="row" style="margin-top:45px">
<div class="col-md-4 col-md-offset-4">
<h4>Sign Up</h4>
<hr>
<form action="<?= base_url('auth/save') ?>" method="post">
<?= csrf_field(); ?>
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter your name" value="<?= set_value('name'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'name') : '' ?></span>
</div>
<div class="form-group">
<label for="">Email</label>
<input type="email" class="form-control" name="email" placeholder="Enter your email" value="<?= set_value('email'); ?>">
<span class=" text-danger"><?= isset($validation) ? display_error($validation, 'email') : '' ?></span>
</div>
<div class="form-group">
<label for="">Password</label>
<input type="password" class="form-control" name="password" placeholder="Enter password">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'password') : '' ?></span>
</div>
<div class="form-group">
<label for="">Confirm Password</label>
<input type="password" class="form-control" name="cpassword" placeholder="Confirm password">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'cpassword') : '' ?></span>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">Sign Up</button>
</div>
I already have account, login now
</form>
</div>
</div>
</div>
</body>
this is my auth.php as controller
<?php
namespace App\Controllers;
class Auth extends BaseController
{
public function __construct()
{
helper(['url', 'form']);
}
public function index()
{
return view('auth/login');
}
public function register()
{
return view('auth/register');
}
public function save()
{
$validation = $this->validate([
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Your name is required'
]
],
'email' => [
'rules' => 'required|valid_emails|is_unique[users.email]',
'errors' => [
'required' => 'Email is required',
'valid_email' => 'You must enter a valid email',
'is_unique' => 'Email already taken'
]
],
'password' => [
'rules' => 'required|min_length[5]|max_length[12]',
'errors' => [
'required' => 'Password is required',
'min_lenght' => 'Password must have atleast 5 character',
'max_lenght' => 'Password must not exceed 12 character'
]
],
'cpassword' => [
'rules' => 'required|min_length[5]|max_length[12]|matches[password]',
'errors' => [
'required' => 'Password is required',
'min_lenght' => 'Password must have atleast 5 character',
'max_lenght' => 'Password must not exceed 12 character',
'matches' => 'Confirms password not matches to password'
]
]
]);
if (!$validation) {
return view('auth/register', ['validation' => $this->validator]);
} else {
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$values = [
'name' => $name,
'email' => $email,
'password' => $password,
];
$userModels = new \App\Models\UsersModel();
$query = $userModels->insert($values);
if (!$query) {
return redirect()->back()->with('fail', 'something went wrong');
} else {
return redirect()->to('register')->with('success', 'You are now registered');
}
}
}
}
this is what i put in form_helper.php in helpers folder
<?php
function display_error($validation, $field)
{
if ($validation->hasError($field)) {
return $validation->getError($field);
} else {
return false;
}
}
what did i do wrong?
CodeIgniter 4.1.5 does not support PHP 8.1 yet.
Please Use 8.0
or Use develop branch of CI4
https://github.com/codeigniter4/CodeIgniter4/pull/4883
https://github.com/codeigniter4/CodeIgniter4/issues/5436
https://forum.codeigniter.com/thread-80490-post-391352.html#pid391352
https://forum.codeigniter.com/thread-80413.html
You can add the null coalescing operator to this line of code:
$method = strtolower($method);
Replace it with:
$method = strtolower($method ?? '');
This change should be made in the library/RestController file line no 835
I'm working on a contact form with Codeigniter 4 and SQL Database. The form will submit through the button, so whenever it is clicked, it is validating, and if all of the fields are filled out, it has no trouble displaying the message and save the information to the database, but when the fields are empty, it does not display the error message, and it continues to state that the file does not exist.
Well, I'm stuck with the error message now. I'm not sure what wrong with the code. Am I missing something?
Can anybody help me with this? I appreciate all the help I can get.
Below are my codes:
App/config/Routes.php
$routes->get('contact', 'Contact::contact');
$routes->post('contact/save', 'Contact::save');
App/Controller/Contact.php
<?php
namespace App\Controllers;
use App\Models\ContactModel;
class Contact extends BaseController
{
public function __construct()
{
helper(['url', 'form']);
}
//CONTACT PAGE
public function contact()
{
$data = [
'meta_title' => 'Contact | MFD',
];
return view('page_templates/contact', $data);
}
//SAVE
public function save()
{
$validation = $this->validate([
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Your full name is required'
]
],
'email' => [
'rules' => 'required|valid_email|is_unique[users.email]',
'errors' => [
'required' => 'Email is required',
'valid_email' => 'You must enter a valid email',
]
],
'title' => [
'rules' => 'required',
'errors' => [
'required' => 'Title is required',
]
],
'content' => [
'rules' => 'required',
'errors' => [
'required' => 'Content is required',
]
],
]);
if (!$validation) {
return view('contact', ['validation' => $this->validator]);
} else {
// Let's Register user into db
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$title = $this->request->getPost('title');
$content = $this->request->getPost('content');
$values = [
'name' => $name,
'email' => $email,
'title' => $title,
'content' => $content,
];
$contactModel = new ContactModel();
$query = $contactModel->insert($values);
if ($query) {
return redirect()->to('contact')->with('success', 'Your message are successful sent');
} else {
return redirect()->to('contact')->with('fail', 'Something went wrong');
}
}
}
}
App/Views/page_templates/contact.php
<form action="<?= base_url('contact/save'); ?>" method="post" role="form" class="php-email-form">
<?= csrf_field(); ?>
<?php if (!empty(session()->getFlashdata('error'))) : ?>
<div class="alert alert-danger"><?= session()->getFlashdata('error'); ?></div>
<?php endif ?>
<?php if (!empty(session()->getFlashdata('success'))) : ?>
<div class="alert alert-success"><?= session()->getFlashdata('success'); ?></div>
<?php endif ?>
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" value="<?= set_value('name'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'name') : '' ?></span>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" value="<?= set_value('email'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'email') : '' ?></span>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'title') : '' ?></span>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="content" rows="5" wrap="hard" placeholder="Message"></textarea>
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'content') : '' ?></span>
</div>
<div style="height: 10px;"></div>
<div class="text-left button">
<button type="submit" name="submit">Send Message</button>
</div>
<div style="height: 10px;"></div>
</form>
Okay, I have fixed the problem with my code. It's really is a small mistake or I could say careless mistake haha feel so dumb right now but all that I need to change and make it work.
Is this part: return view('contact', ['validation' => $this->validator]);
Instead of doing it like that I actually miss placing the file to call the view page properly so the code I only added my the folder name that is
page_templates
and if I include it in the code it should look like this:-
return view('page_template/contact', ['validation' => $this->validator]);
and it works after that haha.
Am having a "The 0 field is required." error while trying save data into database when I have no field called 0. without validation from the Controller, the data saves but if I validate even just one field out of the six field I want to validate, I still get the error. How do I solve the issue. Please help out here is my view
<form method="post" action="{{ url('agent/add_tenantProperty') }}" data-toggle="validator">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtMovieTitle">Tenant</label>
<select id="ddlGenge" class="form-control" name="tenant_id" required="">
#foreach($tenants as $tenant)
<option value="{{ $tenant->id }}">
{{ $tenant->designation }} {{ $tenant->firstname }} {{ $tenant->lastname }}
</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="ddlGenge">Asset Category</label>
<select id="ddlGenge" class="form-control" name="asset_id" required="">
<option>Choose a Property</option>
#foreach($assets as $asset)
<option value="{{ $asset->id }}">{{ $asset->category }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtDirector">Asset description</label>
<select id="ddlGenge" class="form-control" name="description" required="">
<option>Choose a Description</option>
#foreach($assets as $asset)
<option value="{{ $asset->description }}">{{ $asset->description }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtProducer">Location</label>
<select id="ddlGenge" class="form-control" name="address" required="">
<option>Choose an Address</option>
#foreach($assets as $asset)
<option value="{{ $asset->address }}">{{ $asset->address }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtWebsite">Standard price</label>
<input id="txtWebsite" type="text" class="form-control" name="price" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtWriter">Date</label>
<input id="txtWriter" type="date" class="datepicker form-control" name="occupation_date"
required="">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" class="btn btn-outline btn-primary pull-right">Submit</button>
<br/>
</form>
and my controller
public function store(Request $request)
{
//validation
$this->validate($request, array([
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]));
//create and save new data
$tenantProperty = New TenantProperty();
$tenantProperty->tenant_id = $request->tenant_id;
$tenantProperty->asset_id = $request->asset_id;
$tenantProperty->description = $request->description;
$tenantProperty->address = $request->address;
$tenantProperty->price = $request->price;
$tenantProperty->occupation_date = $request->occupation_date;
$tenantProperty->save();
//redirect
return redirect('agent/tenantProperty_list');
}
with the route as follows
Route::get('add_tenantProperty', 'TenantPropertyController#create')->name('/add_tenantProperty');
Route::post('add_tenantProperty', 'TenantPropertyController#store');
When you just write $request, it passes the entire request object but the validate function expect both the arguments to be arrays.
So make a little change and you will be good to go:
$this->validate($request, array( // Removed `[]` from the array.
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
));
The above answer is correct, this is another way to solve the validation problem on laravel 5.5 I asked
$validation = validator::make($request->all(), [
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]);
For more information visit https://laravel.com/docs/5.5/validation#manually-creating-validators
$request->validate([
'0'=>'',
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',]);
I am working on yii2 bootstrap active form and I need to keep multiple inputs in one form group .
like
<div class="form-group field-phn required">
<label class="control-label" >Home Phone</label>
<select id="dialCode" class="form-control" name="AddPatientForm[home_dial_code]">
<option value="2">355,ALB</option>
<option value="3">213,DZA</option>
<option value="6">244,AGO</option>
<option value="224">971,ARE</option>
</select>
<input type="text" id="home_phn" class="form-control" name="AddPatientForm[home_phn]">
<p class="help-block help-block-error"></p>
</div>
php code I am trying is
<?php echo \yii\bootstrap\Html::activeLabel($objAddPatientFrm, 'home_phn') ?>
<?php echo $objActiveForm->field($objAddPatientFrm, 'home_dial_code', [ 'inputOptions' => [ 'id' => 'dialCode']])->dropDownList($dialCodeArray)->label(false); ?>
<?php echo $objActiveForm->field($objAddPatientFrm, 'home_phn', [ 'inputOptions' => [ 'id' => 'home_phn']]); ?>
But the output is
<label for="addpatientform-home_phn">Home Phn</label> <div class="form-group field-dialCode required">
<select id="dialCode" class="form-control" name="AddPatientForm[home_dial_code]">
<option value="2">355,ALB</option>
<option value="3">213,DZA</option>
<option value="6">244,AGO</option>
<option value="224">971,ARE</option>
</select>
<p class="help-block help-block-error"></p>
</div>
<div class="form-group field-home_phn required">
<input type="text" id="home_phn" class="form-control" name="AddPatientForm[home_phn]">
<p class="help-block help-block-error"></p>
</div>
keeping both inputs and label in seperate form group .
Please suggest what can I do ?
Use following way to display forms:
// With 'default' layout you would use 'template' to size a specific field:
echo $form->field($model, 'demo', [
'template' => '{label} <div class="row"><div class="col-sm-4">{input}{error}{hint}</div></div>'
]);
// Input group
echo $form->field($model, 'demo', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">#</span>{input}</div>',
]);
Hope it will help..
My solution to this is to prevent the $form->field() from rendering its own form-group class. This is achieved by using the options property and setting options.class to an empty string (or to include any classes other than form-group). Then wrap the fields in a <div class="form-group">.
Here's the code:
<div class="form-group">
<?= $form->field($Model, 'attribute1', ['options' => ['class' => '']]); ?>
<?= $form->field($Model, 'attribute2', ['options' => ['class' => '']]); ?>
</div>
For the OP's example:
<div class="form-group field-phn required">
<?php echo \yii\bootstrap\Html::activeLabel($objAddPatientFrm, 'home_phn') ?>
<?php echo $objActiveForm->field($objAddPatientFrm, 'home_dial_code', [ 'inputOptions' => [ 'id' => 'dialCode'], 'options' => ['class' => '']])->dropDownList($dialCodeArray)->label(false); ?>
<?php echo $objActiveForm->field($objAddPatientFrm, 'home_phn', [ 'inputOptions' => [ 'id' => 'home_phn'], 'options' => ['class' => '']]); ?>
</div>