Can't display Codeigniter validation error - php

Don't get this.
I have to validate basic form. Im using CI form_validation library, form validation rules are set just to "required"...if form validation fails it just need to echo validation error in login form. Im using by default <?php echo validation_errors(); ?> Helper is autoloaded. Form functionality is OK it works how it should, only problem is that framework dont display error messagges if dont fill required fields?
login_form.php - VIEW
<?php echo validation_errors(); ?>
<?php echo form_input('email' , 'email'); ?> <br>
<?php echo form_input('password' , 'password'); ?> <br>
<?php echo form_submit('submit' , 'submit'); ?>
login.php - CONTROLLER
<?php
Class Login extends CI_Controller {
function index () {
$data ['content'] = "login_form";
$this->load->view("template", $data);
}
function validate() {
$this->load->library("form_validation");
$this->form_validation->set_rules('email' , 'email' , 'trim|xss_clean|required');
$this->form_validation->set_rules('password' , 'password' , 'md5|trim|required');
if( $this->form_validation->run() == FALSE) {
redirect('login/index');
}
else {
redirect("user/profile");
}
}
}
?>

Why don't you use code in controller like this hope will help you just set form action to login.php
login.php - CONTROLLER
function index () {
$data ['content'] = "login_form";
$this->load->library("form_validation");
$this->form_validation->set_rules('email' , 'email' , 'trim|xss_clean|required');
$this->form_validation->set_rules('password' , 'password' , 'md5|trim|required');
if( $this->form_validation->run() == FALSE) {
$this->load->view("template", $data);
}
else {
redirect("user/profile");
}
}
login_form.php - VIEW
<?php echo validation_errors(); ?>
<?php echo form_input('email' , 'email'); ?> <br>
<?php echo form_input('password' , 'password'); ?> <br>
<?php echo form_submit('submit' , 'submit'); ?>

if( $this->form_validation->run() == FALSE) {
redirect('login/index');
}
Don't redirect, else error will not be available. Instead of that keep
if( $this->form_validation->run() == FALSE) {
$data ['content'] = "login_form";
$this->load->view("template", $data);
}
Check the following link for more details:
Form Validation : CodeIgniter User Guide

Related

How to compare form input data to database data in a custom codeigniter form validator?

Edit: Some naming had been mixed up in my attempts to solve it myself. I've fixed the callback etc naming and the same error persists.
I am attempting to create a login page for my codeigniter website. I already have a registration page that correctly inputs usernames and passwords in to a "users" table. I am having issues understanding the syntax of creating the functions needed for custom form validators.
My error is "Unable to access an error message corresponding to your field name" for the password and username custom validators.
Here is the relevant part of the controller "login_ctrl"
class login_ctrl extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('login_mdl');
}
function index() {
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_userCorrect');
//Validating Password Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_passwordCorrect');
//variables to pass form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//reload login page if validation fails
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
//functions for custom validation
function userCorrect($username) {
$this->load->library('form_validation');
//the loads the model that contains the function to compare input to database data
$userExists = $this->login_mdl->userExists($username);
if ($userExists) {
$this->form_validation->set_message(
'userCorrect', 'correct user.'
);
return true;
} else {
$this->form_validation->set_message(
'userCorrect', 'not a valid user name.'
);
return false;
}
}
function passwordCorrect($password) {
$this->load->library('form_validation');
$passwordExists = $this->login_mdl->passwordCorrect($password);
if ($passwordExists) {
$this->form_validation->set_message('passwordCorrect', 'correct password.');
return true;
} else {
$this->form_validation->set_message('passwordCorrect', 'invalid password.');
return false;
}
}
This is the corresponding view "login"
<?php echo form_open('login_ctrl'); ?>
<h1>Login</h1><hr/>
<?php if (isset($message)) { ?>
<?php } ?>
<?php echo form_label('User Name :'); ?> <?php echo form_error('username'); ?><br />
<?php echo form_input(array('id' => 'username', 'name' => 'username')); ?><br />
<?php echo form_label('Password :'); ?> <?php echo form_error('password'); ?><br />
<?php echo form_input(array('id' => 'password', 'name' => 'password')); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
Finally, this is the corresponding model "login_mdl" (I think the issue might be in this guy).
<?php
class login_mdl extends CI_Model{
function __construct() {
parent::__construct();
}
function userExists($username) {
$this->db->select('id');
$this->db->where('username', $username);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
function passwordCorrect($password) {
$this->db->select('password');
$this->db->where('username', $username);
$query = $this->db->get('users');
$result = $query->row();
return $result->password;
if ('password' == $password) {
return true;
} else {
return false;
}
}
}
?>
I think my issue is related to the db calls and if statements but I've been reading documentation and failing at fixing this for hours so a new pair of eyes would be greatly appreciated.
You need to make your fieldname on your costume rules function is same as your function callback. So, it’s should be like this :
$this->form_validation->set_message(
'userCorrect', 'correct user.'
Do same thing on your other function.

Validation flashdata error is not displaying in CodeIgniter

Here is my login method inside the controller, Here I am setting a flash message for the validation errors -
public function login(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[3]');
if($this->form_validation->run() == FALSE){
$data = array(
'errors' => validation_errors()
);
$this->session->set_flashdata($data);
redirect('home');
}
}
Here id the code to display those errors -
<?php if($this->session->flashdata('errors')): ?>
<?php echo $this->session->flashdata('errors');?>
<?php endif; ?>
I don't know what is wrong, Error message is not displaying.
I hope work this process
if($this->form_validation->run() == FALSE){
$this->session->set_flashdata('name','Your message');
redirect('home');
}
<?php if($this->session->flashdata('name')): ?>
<?php echo $this->session->flashdata('name');?>
<?php endif; ?>
Its placed in controller
if ($this->form_validation->run() == FALSE) {
$errors = validation_errors();
$this->session->set_flashdata('form_error', $errors);
$this->load->view('Your View page');
}
Its placed in your view page
<?php if($this->session->flashdata('form_error')): ?>
<?php echo $this->session->flashdata('form_error');?>
<?php endif; ?>
I hope this it will help to you..!

Yii - How To Save Two Models in a Same Form?

I am working on a project. I want to save 2 models in a same form. I've tried like this:
actionCreate in QController.php
public function actionCreate()
{
$model=new Question;
$test=new Answer;
if(isset($_POST['Question']) && ($_POST['Answer']))
{
$model->attributes=$_POST['Question'];
$model->question=CUploadedFile::getInstance($model,'question');
$test->attributes=$_POST['Answer'];
$valid=$model->validate();
$valid=$test->validate() && $valid;
if($valid){
$model->save(false);
$test->save(false);
$model->question->saveAs(Yii::app()->basePath . '/../images/questions/' . $model->question.'');
$this->redirect(array('view','id'=>$model->id_question));
}
}
$this->render('create',array(
'model'=>$model,
'test'=>$test,
));
}
Then, in my Q/_form.php
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'question-form',
'enableAjaxValidation'=>false,
)); ?>
<?php $answerModel = new Answer; ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model, $answerModel); ?>
<?php echo $form->fileFieldRow($model,'question',array('class'=>'span5','maxlength'=>50)); ?>
<?php echo $form->textFieldRow($answerModel,'optionA',array('class'=>'span5','maxlength'=>100)); ?>
//rest of codes
<?php $this->endWidget(); ?>
I've tried this but still not save the data. How can I do to fix it? Thanks for your answer
You should validate first and then save data:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
// use false parameter to disable validation
$model->save(false);
$test->save(false);
// redirect
}
And with transactions:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
$dbTransaction = Yii::app()->db->beginTransaction();
try {
// use false parameter to disable validation
$model->save(false);
$test->save(false);
$dbTransaction->commit();
// redirect here
} catch (Exception $e) {
$dbTransaction->rollBack();
// save/process error
}
}

Codeigniter validation errors

I have a site develop in codeigniter.
I want to validate a form and display some message.
With my code I don't see any error if my input "name_it" is blank. Why?
This is my controller:
public function nation_create()
{
if($_POST)
{
//salvo i dati
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<p class="error">Errore: ', '</p>');
$this->form_validation->set_rules('name_it', 'name_it', 'required');
if ($this->form_validation->run() !== FALSE){
$this->Nation_model->createNation();
redirect('backend/nation/nation_list/');
}
else{
$data['errors'] = validation_errors();
$this->load->view('backend/include/header_view_logged');
$this->load->view('backend/nation_create_view',$data);
$this->load->view('backend/include/footer_view');
}
}
else{
$this->load->view('backend/include/header_view_logged');
$this->load->view('backend/nation_create_view');
$this->load->view('backend/include/footer_view');
}
}
And this is my view (I have cut more code to read well)
<form action='' method='POST'>
<?php echo validation_errors();
if (isset($errors))
echo $errors;
?>
<?php echo form_error('name_it'); ?>
<input type="text" name="name_it" />
<span id="errorsDiv_name_it"></span>
</form>
Try this:
change:
if ($_POST)
for:
if ($this-input->post())
Info: http://ellislab.com/codeigniter/user-guide/libraries/input.html
You can use the form_validation()->run() to complete this kind of task. It checks if a POST have been sent and if validation_rules returns true.
if($this->form_validation()->run() == false)
{
//load the view
// other stuff you do while POST is not yet sent or if Input from the user returns false
}else{
// post has been sent and validiation is TRUE
// Input is good. . do something
}
The problem was in the class error with attribute display:none

codeigniter displaying error message on same page

another question again regarding codeigniter, here a few details:
view page:
<?php if (isset($error)){echo $error; } ?>
<form action="<?php echo site_url('mem_posting/post');>" method="post">
<input type="text" name="fname">
some fields goes here...
</form>
controller page(mem_posting):
public function post_form()
{
$this->load->view('header');
$this->load->view(form_page);
}
public function post()
{
$post_data=array(
'mem_id'=>$this->input->post('mem_id'),
//other inputs...
)
$this->load->model('member_model');
if ($this->member_model->check_member($post_data)===true)
{
//row exist
// **i would like to load the same page but
// **with error message "like already exist".
}else{
$this->member_model->inset_member($post_data);
}
}
model page:
public function insert_member($post_data=array())
{
extract($post_data);
$this->db->where('member_id', $member_id);
$this->db->insert('membership', $post_data);
}
public function check_member($post_data=array())
{
extract($post_data);
$this->db->select('mem_id');
$this->db->where('mem_id', $mem_id);
$query = $this->db->get('membership');
if ($query->num_rows() > 0){
return true;
}else{
return false;
}
}
as you can see the view page contains the form, now what i would like to achieve is to echo an error like 'already exist' so i dont have to code another $this->load->view('post_form') inside the if statement.
thank you in advance..
Do you mean just sending a variable to the view?
$data['error'] = "error message";
$this->load->view('some/view', $data);
Well! you shoul run validation when your form is submited. So, imagine you have 2 fields submited. It would be like this:
$this->form_validation->set_rules('name', 'Name', 'required|trim|xss_clean');
$this->form_validation->set_rules('mem_id', 'ID Member', 'required|trim|is_unique[yourtable.mem_id]|xss_clean');
if ($this->form_validation->run()){
// Do your cool stuff now because validation passed
}else{
// Whatever...validation fails, load your view.
}
So in your view you shoul have somethin like this at top of the form:
<?php echo validation_errors(); ?>
is_unique[yourtable.mem_id] will validate if the input is unique in your DB. So if is really unique, OK.

Categories