codeigniter validate login error - codeigniter

i have a login method but it doesn't seems to work correctly. For example if i try to login with a username that exists in the database and the password of another user, i can successfully login. Can someone spot the error in my code?
Controller:
public function login(){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('name_login', 'Utilizator', 'required|callback_validate_login|xss_clean|trim');
$this->form_validation->set_rules('password_login', 'Password', 'required|xss_clean|trim');
$this->form_validation->set_message('validate_login','login esuat');
$this->form_validation->set_message('required', '*');
if ($this->form_validation->run() === FALSE){
$this->render('login');
}
else {
// user successful login
$data = array(
'username' => $this->input->post('name_login'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
$this->load->view('homeview',$data);
}
}
public function validate_login(){
$username = $this->input->post('user_login');
$pass = $this->input->post('password_login');
if ($this->homemodel->login($username,$pass)){
return true;// form validation passed, u are now logged in
}
else {
return false;
}
}
Model:
public function login($user, $pass)
{
$query = $this->db->get_where('login', array('username' => $user, 'password' => $pass));
echo '<pre>';
print_r($query->result());
echo '</pre>';
if ($query->num_rows() === 1) {
return true;
} else {
return false;
}
View
<?php echo form_open('home/login') ?>
<label for="user">Username</label>
<input type="text" class="createform" name="user_login" value="<?php echo set_value('name_login'); ?> " />
<?php echo form_error('name_login') . '<br>'; ?>
<label for="pass">Password</label>
<input type="text" class="createform" name="password_login" value="<?php echo set_value('password_login'); ?> " />
<?php echo form_error('password_login') . '<br>'; ?>
<input type="submit" name="submit" value="Login" />
</form>

Oh,my bad, found the error : the username input name in the view file is "user_login" and in the controller i wrote 'name_login':
$this->form_validation->set_rules('name_login',...)

It looks like you are setting the session data to is_logged_in just on successful form submission:
if ($this->form_validation->run() === FALSE){
$this->render('login');
}
else {
// user successful login
$data = array(
'username' => $this->input->post('name_login'),
'is_logged_in' => 1
);
You need to validate the user first.
I would try something like:
if ($this->form_validation->run() === FALSE){
$this->render('login');
}
else {
$results = $this->validate_login();
// user successful login
if ($results){
$data = array(
'username' => $this->input->post('name_login'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
$this->load->view('homeview',$data);
}
else {
redirect('login');
}
}
Does that make sense? It doesn't look like you were actually checking or calling the validate_login() method.

Related

Group of checkbox always return empty values

i have a strange problem with laravel and checkbox.
I have a group of checkbox and I'm not able to have value to save on database.
My migration:
$table->json('send_reminder')->nullable();
My model:
protected $fillable = [
.....
'send_reminder',
....
];
my index.php
class Index extends Component{
public
....
$send_reminder,
....
My form index.blade.php
<div class="input-group input-group-static my-3">
<div class="form-control #error('reminder') is-invalid #enderror">
Notification interval: <br>
#foreach(\App\Enums\ReminderInterval::options() as $option => $reminder)
<label>
<input name="send_reminder[]" value="{{(str_replace('_','',$option))}}"
type="checkbox">
{{(str_replace('_',' ',$option))}}
</label><br>
#endforeach
</div>
When I try to save data to variable and DD the data, the field is always null.
$data = [
....other data...
'send_reminder' => $this->send_reminder
];
dd($data);
Can you help me?
thanks!
---- complete code of function path: app/Http/Livewire/User/Dashboard/Deadlines/Add/Index.php
public function Add(){
$msg = [
'check_reminder' => 'Select Reminder',
'check_reminder.in' => 'Select Reminder',
'note.required' => 'Please add a public note.',
];
$validated = $this->validate([
'customer_id' => 'required|numeric',
'name' => 'required|string',
'date' => 'required|date',
'amount' => array('required','regex:/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)*$/'),
], $msg);
// max customers with current subscription
$customer_of_user = count(DB::table("customers")->where("user_id", Auth::user()->id)->get());
$allowed_customers = Admin::ProductAllowedCustomers($this->active_subscription->name);
if (!$allowed_customers) {
$this->allowed_deadlines = "unlimited";
}
try {
//MAX Deadlines created about this user
$deadline_of_customer = DB::table('deadlines')
->where('customer_id', $validated['customer_id'])
->where('user_id',Auth::user()->id)
->get();
$deadline_of_customer = count($deadline_of_customer);
//Allowed Deadlines
$allowed_deadlines = Admin::ProductAllowedDeadlines($this->active_subscription->name);
//If allowed customers are unlimited
if ($this->allowed_deadlines == "unlimited" OR $deadline_of_customer < $allowed_deadlines) {
$data = [
'subscription_id' => $this->active_subscription->id,
'user_id' => Auth::user()->id,
'slug' => strtoupper(Str::random(20)),
'renew_state' => $this->renew_state,
'type_of_renew' => $this->type_of_renew,
'send_reminder' => $this->send_reminder
];
dd($data);
//Create Deadline
Deadline::create(array_merge($data, $validated));
//Get Reminder Values
// switch($this->reminder) {
// case('1_day_before'):$this->reminder = 1; break;
// case('7_days_before'):$this->reminder = 7; break;
// case('30_days_before'):$this->reminder = 30; break;
// case('60_days_before'):$this->reminder = 60; break;
// default: $this->reminder = 0;
// }
//Send Email
/*if($this->reminder):
dispatch(function () {
//Get Renew State Values
switch ($this->renew_state){
case($this->renew_state == "to_renew"): $this->renew_state = "To Renew"; break;
case($this->renew_state == "waiting_cash"): $this->renew_state = "Waiting for Cash"; break;
case($this->renew_state == "renewed"): $this->renew_state = "Renewed"; break;
default:$this->renew_state = "Deleted";
}
//Get Type of Renew Values
switch ($this->type_of_renew){
case($this->type_of_renew == "domain"): $this->type_of_renew = "Domain"; break;
case($this->type_of_renew == "hosting"): $this->type_of_renew = "Hosting"; break;
case($this->type_of_renew == "privacy_cookie"): $this->type_of_renew = "Privacy Cookie"; break;
default:$this->type_of_renew = "Other";
}
//Find Customer
$customer = Customer::find($this->customer_id);
//Data to send
$data = [
'name' => $customer->name,
'type_of_renew' => $this->type_of_renew,
'renew_state' => $this->renew_state,
'date' => date('d-M-Y'),
'note' => $this->note,
'amount' => $this->amount . ' ' . strtoupper(Admin::Currency()),
];
//Mail To
Mail::to($customer->email)->send(new Reminder($data,Auth::user()->id));
//Delay
})->delay(now()->addDays($this->reminder));
endif;*/
session()->flash('success', 'Added Successfully');
return redirect(route('UserDeadlines'));
}
else {
session()->flash('error', 'Your subscription allows you to create only ' . $allowed_deadlines .
' Deadlines for each Customer.Please upgrade your Subscription');
// return redirect(route('UserDeadlines'));
}
} catch (Exception $e) {
return session()->flash('error', $e->getMessage());
}
}
Not sure about the rest of your code, if you posted it all you would be able to get more help. That being said, livewire will not just look for inputs on your page, you need to let it know by using wire:model="send_reminder":
Working example: Example
test-field.blade.php
<div>
<input wire:model="send_reminder" name="send_reminder[]" value="1" type="checkbox">
<input wire:model="send_reminder" name="send_reminder[]" value="2" type="checkbox">
<input wire:model="send_reminder" name="send_reminder[]" value="3" type="checkbox">
<input wire:model="send_reminder" name="send_reminder[]" value="4" type="checkbox">
<div>{{ print_r($send_reminder) }}</div>
</div>
TestField.php
class TestField extends Component
{
public $send_reminder = array();
public function render()
{
return view('livewire.test-field');
}
}

Showing undefined variable while updating image in laravel

I am totally new in laravel and i have a small error in my code. Whenever I am updating the image it is showing the error
Undefined variable: company_image
Here is my code in Controller :
if(isset($request->company_image) && $request->company_image->getClientOriginalName()) {
$ext = $request->company_image->getClientOriginalExtension();
$file = date('YmdHis').rand(1,99999).'.'.$ext;
$request->company_image->storeAs('public/company-logo',$file);
}
else
{
if(!$company_image){
$file='';
}
else
{
$file = $company_image;
}
}
Here is my code in resource :
<div class="form-group">
<div class="row">
<div class="col-md-3">
<label>Company Image</label>
</div>
<div class="col-md-9">
<input type="file" name="company_image" id="imageUpload" class="hide">
<label for="imageUpload" class="upload-poster mr-5">Select file</label> Max Size 2 MB<br>
#if($company_image)
<img src="{{ asset('storage/company-logo/'.$company_image)}}" class="organisation-logo">
#else
<img src="{{ asset('assets/admin/images/dummy-logo.jpg')}}" id="imagePreview" class="organisation-logo" alt="Your image will appear here.">
#endif
</div>
</div>
</div>
Please help me out, Thanks in advance.
Here is my code from where I am updating the data and the image. Please check this
public function update(Request $request, $jobId)
{
try
{
if(isset($request->company_image) && $request->company_image->getClientOriginalName()){
$ext = $request->company_image->getClientOriginalExtension();
$file = date('YmdHis').rand(1,99999).'.'.$ext;
$request->company_image->storeAs('public/company-logo',$file);
}
else
{
if(!$company_image){
$file='';
}
else{
$file = $company_image;
}
}
$data = [
'job_title' => $request->input('job_title'),
'job_description' => $request->input('job_description'),
'publish_date' => Carbon::parse($request->input('publish_date'))->format('Y-m-d'),
'closing_date' => Carbon::parse($request->input('closing_date'))->format('Y-m-d'),
'company_image' => $file,
'organisation_type' => $request->input('organisation_type'),
'organisation' => $request->input('organisation'),
'country' => $request->input('country'),
'state' => $request->input('state'),
'city' => $request->input('city'),
'posted_by' => $userId
];
$rs = null;
if($request->input('temp_job') == 1){
$rs = Job::updateOrCreate(['temp_job_id'=> $jobId], $data);
}
else{
$rs = Job::where(['id'=> $jobId])->update($data);
}
if($rs){
$message = array('flag'=>'alert-success', 'message'=>'Job Updated Successfully');
return redirect()->route('auth.job.index')->with(['message'=>$message]);
}
$message = array('flag'=>'alert-danger', 'message'=>'Unable to update new job, Please try again');
return redirect()->route('auth.job.index')->with(['message'=>$message]);
}
catch (Exception $e)
{
$message = array('flag'=>'alert-danger', 'message'=>$e->getMessage());
return back()->with(['message'=>$message]);
}
}
Make sure , you are passing company_image variable in view.
if(!$company_image){
$file='';
}else{
$file = $company_image;
}
problem is here, you need to make sure $company_image is declared, before you can use it in if statement inside controller.
Example:
//declare company_image
$company_image = ''; //or $company_image = null;
//here logic to change $company_image if needed
//check if not empty/false
if(!$company_image){
$file='';
}else{
$file = $company_image;
}
Also you can check if variable exist with isset():
if(isset($company_image) && !$company_image){
$file='';
}else{
$file = $company_image;
}
Also make sure you pass this varaible in view. view('myView', compact('company_image'))
Updated Answer:
//Declare file as empty
$filePath = '';
//check if file uploaded and is valid
if($request->hasFile('company_image') && $request->file('company_image')->isValid()){
//get file extension
$ext = $request->company_image->extension();
//Generate File name
$file = date('YmdHis').rand(1,99999).'.'.$ext;
//Save file, storeAs() will return stored file path
$filePath = $request->company_image->storeAs('public/company-logo',$file);
}
Use $filePath to update the path in DB
$data = [
...
'company_image' => $filePath,
...
];
In view you can simply use {{ asset($company_image) }} check Laravel docs
Complete update function
public function update(Request $request, $jobId) {
try{
//Declare file as empty
$filePath = '';
//check if file uploaded and is valid
if($request->hasFile('company_image') && $request->file('company_image')->isValid()){
//get file extension
$ext = $request->company_image->extension();
//Generate File name
$file = date('YmdHis').rand(1,99999).'.'.$ext;
//Save file, storeAs() will return stored file path
$filePath = $request->company_image->storeAs('public/company-logo', $file);
}
$data = [
'job_title' => $request->input('job_title'),
'job_description' => $request->input('job_description'),
'publish_date' => Carbon::parse($request->input('publish_date'))->format('Y-m-d'),
'closing_date' => Carbon::parse($request->input('closing_date'))->format('Y-m-d'),
'company_image' => $filePath,
'organisation_type' => $request->input('organisation_type'),
'organisation' => $request->input('organisation'),
'country' => $request->input('country'),
'state' => $request->input('state'),
'city' => $request->input('city'),
'posted_by' => $userId
];
$rs = null;
if($request->input('temp_job') == 1){
$rs = Job::updateOrCreate([
'temp_job_id'=> $jobId
], $data);
} else{
$rs = Job::where([
'id' => $jobId
])->update($data);
}
if($rs){
return redirect()->route('auth.job.index')->with([
'message' => [
'flag' => 'alert-success',
'message' => 'Job Updated Successfully'
]
]);
}
return redirect()->route('auth.job.index')->with([
'message'=> [
'flag' => 'alert-danger',
'message' => 'Unable to update new job, Please try again'
]
]);
}catch (Exception $e){
return back()->with([
'message'=> [
'flag' => 'alert-danger',
'message' => $e->getMessage()
]
]);
}
}

CodeIgniter: Passing fields to user_profiles database with Tank_auth

I'm wracking my brain on what is probably a simple issue. Relatively new to MVC and codeigniter. I'm using tank_auth for user registration, and it comes with a db table user_profiles which I've altered slightly to add things like 'firstname', 'lastname', 'homephone', etc.
I've added the appropriate fields to my register_form.php view and following advice from this question: Tank Auth Adding Fields and others, tried to update all necessary stuff. Unfortunately, while the users table gets populated properly, the user_profiles table does not. I've double checked with firebug that the view is posting properly, but the model is not picking up the data, and I keep getting the error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: firstname
Filename: tank_auth/users.php
Line Number: 382
Using var_dump, I can see that the controller function is not receiving 'firstname' or anything else and they are NULL, but the data going into users is being sent properly.
Here's the relevant code:
Model:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Controller:
function register()
{
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} elseif (!$this->config->item('allow_registration', 'tank_auth')) { // registration is off
$this->_show_message($this->lang->line('auth_message_registration_disabled'));
} else {
$use_username = $this->config->item('use_username', 'tank_auth');
if ($use_username) {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|alpha_dash');
}
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('firstname', 'Firstname', 'trim|xss_clean');
$this->form_validation->set_rules('lastname', 'Lastname', 'trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
$captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
$use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
if ($captcha_registration) {
if ($use_recaptcha) {
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
} else {
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
}
$data['errors'] = array();
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run()) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('homephone'),
$this->form_validation->set_value('cellphone'),
$email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
if ($email_activation) { // send "activate" email
$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
$this->_send_email('activate', $data['email'], $data);
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_1'));
} else {
if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
$this->_send_email('welcome', $data['email'], $data);
}
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
}
} else {
$errors = $this->tank_auth->get_error_message();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
if ($captcha_registration) {
if ($use_recaptcha) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$data['use_username'] = $use_username;
$data['captcha_registration'] = $captcha_registration;
$data['use_recaptcha'] = $use_recaptcha;
$this->load->view('auth/register_form', $data);
}
}
View:
$firstname = array(
'name' => 'firstname',
'id' => 'firstname',
'value' => set_value('firstname'),
'maxlength' => 40,
'size' => 30,
);
...
<tr>
<td><?php echo form_label('First Name', $firstname['id']); ?></td>
<td><?php echo form_input($firstname); ?></td>
<td style="color: red;"><?php echo form_error($firstname['name']); ?><?php echo isset($errors[$firstname['name']])?$errors[$firstname['name']]:''; ?></td>
</tr>
I have been working on this far too long, am hoping that a fresh (and knowledgeable) pair of eyes can see what I cannot.
The data to be recorded in user_profile is passed along the folllowing chain:
view -> controller -> library/tank_auth/create_user() -> model/users/users/create_user() -> model/create_profile
Therefore you need to make sure that the variable is passed along every time.
Here is my working solution, building up on the modifications that you mentioned in the question:
VIEW + CONTROLER:
Your solution is good
LIBRARY
function create_user($username, $email, $password, $firstname, $lastname, $company='', $email_activation)
{
if ((strlen($username) > 0) AND !$this->ci->users->is_username_available($username)) {
$this->error = array('username' => 'auth_username_in_use');
} elseif (!$this->ci->users->is_email_available($email)) {
$this->error = array('email' => 'auth_email_in_use');
} else {
// Hash password using phpass
$hasher = new PasswordHash(
$this->ci->config->item('phpass_hash_strength', 'tank_auth'),
$this->ci->config->item('phpass_hash_portable', 'tank_auth'));
$hashed_password = $hasher->HashPassword($password);
$data = array(
'username' => $username,
'password' => $hashed_password,
'email' => $email,
'last_ip' => $this->ci->input->ip_address(),
);
$data_profile = array(
'firstname' => $firstname,
'lastname' => $lastname,
'company' => $company,
);
if ($email_activation) {
$data['new_email_key'] = md5(rand().microtime());
}
if (!is_null($res = $this->ci->users->create_user($data, $data_profile, !$email_activation))) {
$data['user_id'] = $res['user_id'];
$data['password'] = $password;
unset($data['last_ip']);
return $data;
}
}
return NULL;
}
MODEL:
function create_user($data, $data_profile, $activated = TRUE)
{
$data['created'] = date('Y-m-d H:i:s');
$data['activated'] = $activated ? 1 : 0;
var_dump($data);
if ($this->AuthDb->insert($this->table_name, $data)) {
$user_id = $this->AuthDb->insert_id();
$this->create_profile($user_id, $data_profile);
return array('user_id' => $user_id);
}
return NULL;
}
[...]
private function create_profile($user_id, $data_profile)
{
$this->AuthDb->set('user_id', $user_id);
$this->AuthDb->set('firstname', $data_profile['firstname']);
$this->AuthDb->set('lastname', $data_profile['lastname']);
$this->AuthDb->set('company', $data_profile['company']);
return $this->AuthDb->insert($this->profile_table_name);
}
You need to pass $firstname as a parameter to the function...
private function create_profile($user_id, $firstname)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Ok so I figured it out, in case anyone googles this answer down the line. I'm not sure if this is the 'proper' or most elegant solution, but does fine for my purposes. I edited the create_profile function like so:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$data = array(
'firstname' => $this->input->post('firstname'),
);
$this->db->insert($this->profile_table_name, $data);
}

CodeIgniter flashdata delay

I'm tring to validate a login form and sending error messages using flashdata. Flashdata seems to have a delay, it's only affected a second submit (no error message is shown after first submit, ok after second), whereas userdata works correctly.
View>
<?php if ($this->session->flashdata('error_messages')): ?>
<?php echo $this->session->flashdata('error_messages'); ?>
<?php endif; ?>
<?php echo form_open('user/login', array('name' => 'login_form', 'id' => 'login_form')); ?>
<fieldset>
<p>
<?php echo form_label('Username: ', 'username'); ?>
<?php echo form_input('username', set_value('username', ''), array('id' => 'username', 'placeholder' => 'username')); ?>
</p>
<p>
<?php echo form_label('Password: ', 'password'); ?>
<?php echo form_password('password', set_value('password', ''), array('id' => 'password', 'placeholder' => '********')); ?>
</p>
<p>
<?php echo form_submit('login', 'Login', array('id' => 'login')); ?>
</p>
Controller action>
public function login() {
//user is not logged in, carry on
if (!user_is_logged_in()) {
//check if form was already submitted, if yes validate
if ($this->input->post('login')) {
$this->load->library('chronos_user');
//gather data from form
$username = $this->input->post('username');
$password = $this->input->post('password');
//validate form, show error messages if not valid
if (
!($this->chronos_user->valid_username($username)) ||
!($this->chronos_user->unique_username($username))
)
{
$this->chronos_template->set_data('header', array('controller' => 'users', 'action' => 'login', 'title' => 'Login'));
$this->chronos_template->set_view('content', 'user/login_view');
$this->chronos_template->view();
}
//redirect if ok
else {
header("Location http://c4studio.ro");
}
}
//if no form was submitted, just display it
else {
$this->chronos_template->set_data('header', array('controller' => 'users', 'action' => 'login', 'title' => 'Login'));
$this->chronos_template->set_view('content', 'user/login_view');
$this->chronos_template->view();
}
}
//user is already logged in, redirect to profile page
else {
$profile_url = "Location: ";
$profile_url .= site_url();
$profile_url .= "user/profile/";
header($profile_url);
}
}
Valid_username method>
public function valid_username($username) {
if (empty($username)) {
$this->CI->session->set_flashdata('error_messages', 'Value.');
return FALSE;
}
if (strlen($username) < 3) {
$this->CI->session->set_flashdata('error_messages', 'Value11.');
return FALSE;
}
return TRUE;
}
Any ideas? Also if somebody knows a better way to do all this please let me know! Thanks
According to the documentation flashdata exists at the next server request.
But in your case you actually set the flashdata in the same server request as you show the login view which was unsuccesful. Thats the reason it doesn't work.
A better way wuld to just allow your model method to return true or false and use that value instead. The flashdata should only be considered if you redirect the user to an error page or something like that.
As #Repox mentioned, it only works on the 'next refresh'. You are assuming that flashdata works RIGHT AWAY when you set it, but it doesn't you need an new actual page reload / refresh before that is available.
You have the right idea, but you are just using flashdata to implement your message, stick to form messages as a return result, or just a custom variable.
This is really a case of developers designing flashdata for one thing, and users using it for another.
You need to use form_error to return all form errors, don't use flashdata, it will not work as you expect it to.
Examples:
http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors
You can also override any error message found in the language file.
For example, to change the message for the "required" rule you will do
this:
$this->form_validation->set_message('required', 'Your custom message here');

Why aren't validation errors being displayed in CakePHP?

I'm trying to perform validation in the login page for the name,email and password fields. If the input fails validation,the error message should be displayed.
But here,when I fill in the details and submit, it is redirected to the next page. Only the value is not saved in the database.
Why is the message not displayed?
This is my model:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
'email_id' => 'email'
);
function loginUser($data) {
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
$login = $this->find('all');
foreach ($login as $form):
if ($this->data['User']['email_id'] == $form['User']['email_id'] && $this->data['User']['password'] == $form['User']['password']) {
$this->data['User']['id'] = $this->find('all',
array(
'fields' => array('User.id'),
'conditions' => array(
'User.email_id' => $this->data['User']['email_id'],
'User.password'=>$this->data['User']['password']
)
)
);
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
function registerUser($data) {
if (!empty($data)) {
$this->data['User']['name'] = $data['User']['name'];
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
if($this->save($this->data)) {
$this->data['User']['id']= $this->find('all', array(
'fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
}
This is my controller:
class UsersController extends AppController {
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function login() {
$userId = $this->User->loginUser($this->data);
if($userId>0) {
$this->Session->setFlash('Login Successful.');
$this->redirect('/forms/homepage/'.$userId);
break;
} else {
$this->flash('Login Unsuccessful.','/forms');
}
}
function register() {
$userId=$this->User->registerUser($this->data);
$this->Session->setFlash('You have been registered.');
$this->redirect('/forms/homepage/'.$userId);
}
}
EDIT
Why is the message,example,"Minimum 8 characters long", is not being displayed when give less than 8 characters in the password field?
<!--My view file File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="appTitle">
<h2> formBuildr </h2>
</div>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->error('User.name','Name not found');
echo $form->input('User.email_id');
echo $form->error('User.email_id','Email does not match');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Your validation seems correct
How about trying the following:
Make sure set your $form->create to the appropriate function
Make sure there is no $this->Model->read() before issuing Model->save();
Edit
Did you have the following?:
function register()
{
//do not put any $this->User->read or find() here or before saving pls.
if ($this->User->save($this->data))
{
//...
}
}
Edit2
IF you're doing a read() or find() before saving the Model then that will reset the fields. You should be passing the variable as type=hidden in the form. I hope i am making sense.
Edit3
I think you need to move your registerUser() into your controller because having that function in the model doesn't provide you a false return. it's always going to be true even if it has validation errors.
Comment out the redirect line and set the debug to 2 in config/core.php. Then look at the sql that is being generated to see if your insert is working. If the errors are not being displayed, maybe in the view, you are using $form->text or $form->select instead of the $form->input functions. Only the $form->input functions will automatically display the error messages.

Resources