Codeigniter, not echoing validation_error(); - php

I created a new controller questions.php which is not the default controller. I have already loaded the form_validation library but it did not echo out the validation errors when I submitted empty fields from my form. Other questions in SO seems to be completely unrelated to my situation.
Below is my questions.php controller. BTW I have only posted the necessary bits of the class controller.
<?php
class Questions extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper(array('form'));
$this->load->library("form_validation");
}
public function user_logged_in(){
$this->load->library('../controllers/main');
$obj = new $this->main();
$status = $obj->logged_in();
if($status){
return true;
}else{
return false;
}
}
public function question_validation(){
if($this->user_logged_in() == false){
redirect('main/index');
} else{
$this->load->library('form_validation');
$this->form_validation->set_rules('input_title','Title','required');
$this->form_validation->set_rules('message','Question Details','required');
$this->form_validation->set_rules('vidya','Tags','required');
if($this->form_validation->run() == false){
$this->load->library('../controllers/main');
$obj = new $this->main();
$getUserData = $obj->getLogged_userData();
$userdata = array(
'uservalues' => $getUserData
);
$this->load->view('view_header');
$this->load->view('view_nav',$userdata);
$this->load->view('log_user/user_second_nav');
$this->load->view('question_posts/post_questions');
$this->load->view('view_footer');
} else{
echo "form has been submitted";
}
}
}
?>
The form page in view called post_questions.php which is shown below,
<?php
$this->load->helper("form");
echo validation_errors();
echo form_open('questions/question_validation');
?>
<p><h2>Question title</h2></p>
<p><input type="text" name="input_title" id="input_title"
placeholder="what is your question please be specific and clear"></p>
<p><h3>Now Describe in detail!</h3>
<p><textarea id="message" name="message" rows="10px" cols="86px"></textarea></p>
<p><h3>Tags</h3></p><p><input type="text" id="vidyagames" name="vidya"></p>
<p><input type="submit" name="post" value="Submit"></p>
</form>
Before this, the questions controller was giving me error like undefined property Questions::$form_validation so I added a __construct() and now it wont echo out the form validation errors.
Can you help me because probably the form isn't being submitted at all.
Thank You in Advance.

Related

Why i am getting previous session data for current session in codeiginitor even after destroying previous session

I am facing problem in function profile(). In this method I am fetching data from email using session.
When I login, displaying current data. But when I click on profile it displays previous session data and after refresh it become current session data.
last session data
after refresh display current session
my controller file is admin.php.
admin.php
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
// Load form helper library
$this->load->helper('form');
//Load foam valodation library
$this->load->library('form_validation');
// Load the model
$this->load->model('adminmodel');
}
public function index(){
// Load our view to be displayed
$this->load->view('admin/login');
}
// Check for Admin login process
public function dashboard(){
// Validate the user can login
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) //checking validation
{
if(isset($this->session->userdata['logged_in']))
{
$this->load->view('admin/dashboard');
}
else
{
$this->load->view('admin/login');
}
}
else
{ //validation are true
if (isset($_POST['login']))
{
$email = $this->input->post('email');
$password =$this->input->post('password');
// Validate the admin can login
$result = $this->adminmodel->validate($email,$password);
if ($result) {//if the user credidential is validated
$data = array(
'email' => $this->input->post('email'),
'is_logged_in' => true
);
print_r($data);
}
// Add user data in session
$this->session->set_userdata($data);
//load dashboard and passing value
$this->load->view('admin/dashboard',$result);
}
}
} //end of dashboard
public function profile(){
if($this->session->userdata('is_logged_in')){
$email = $this->session->userdata('email');
$result = $this->adminmodel->fetchdata($email);
print_r($result);
$this->load->view('admin/profile',$result);
}
else
{
echo "failed profile";
}
} // end of profile
// Logout from admin page
public function logout() {
// Removing session data
$sess_array = array(
'email' => '',
'is_logged_in'=>false
);
$this->session->unset_userdata($sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('admin/login', $data);
}
}
?>
model file
adminmodel.php
<?php
class Adminmodel extends CI_Model{
public function validate($email,$password)
{
$query = $this->db->where(['email'=>$email,'password'=>$password])
->from('login')
->get();
$result = $query->row();
return $result;
}
public function fetchdata($email)
{
$query = $this->db->where(['email'=>$email])
->from('login')
->get();
$result = $query->row();
return $result;
}
}
profile.php
<?php
echo " I am in Profile " . $email;
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile</title>
</head>
<body>
<p>Name : <input type = "text" value="<?php echo $name; ?>" /><p>
<p>Mobile : <input type = "text" value="<?php echo $mobile; ?>" /> </p>
<p>Address : <input type = "text" value="<?php echo $address; ?>" /> </p>
<p>Email : <input type = "text" value=" <?php echo $email;?>" /> </p>
</body>
</html>
Try the following, after logount instead of unset data, destroy the session entirely
$this->session->sess_destroy();

codeigniter3 form validation callback function calls unnecessarily

I am using codeigniter 3.I have a email field in form and using required|callback_is_email_exist rules on email.When I leave email field blank,it shows callback message instead of required message.
I had worked on codeigniter 2 ,it perefctly shows "required" message, CI3 form validation not executing rules in the sequence when callbacks are used.
Following is my code
View : welcome_message
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('Welcome'); ?>
<h5>Username</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Controller:welcome.php
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|callback_is_email_exist');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_message');
}
else
{
echo 'success';
}
}
public function is_email_exist($str)
{
// code to check email exist in databse here
if (is_email_exist($str)
{
return TRUE;
}
else
{
$this->form_validation->set_message('is_email_exist', 'Email Does not exist');
return FALSE;
}
}
Expected Output
email filed is required
Codeingiter 3 expects to execute rule in sequence.If one succeeds then next one executes.In this case if I leave email field blank it executes callback unnecessarily.Thus it shows wrong message.It should display email field is required instead of email does not exist.
Appreciate your feedback.
I do it so:
Create file: /application/libraries/MY_form_validation.php
<?php if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class MY_Form_validation extends CI_Form_validation
{
public function __construct()
{
parent::__construct();
}
/**
* Your custom validation
*/
public function is_email_exist($str)
{
$CI =& get_instance();
// code to check email exist in databse here
if ($str=='test') {
return true;
}else {
$this->form_validation->set_message('is_email_exist', 'Email Does not exist');
return FALSE;
}
}
}
/* End of file MY_form_validation.php */
/* Location: ./application/libraries/MY_form_validation.php */
In controller (remove callback):
...
$this->form_validation->set_rules('email', 'Email', 'required|is_email_exist');
...
In controller remove function: callback_is_email_exist.
But If you want to check if the email is unique to do so:
In controller:
...
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]',['is_unique'=>'Email exist!']);
...

Issues in Codeigniter

I have been trying to learn CI and implement a blog content management system following a lightweight tutorial I found online today, but I'm currently experiencing some problems in the view.
Adding new entries "works", but I get the following errors on top of the add_new page:
http://pastebin.com/4UhMTqLj
CONTROLLER
function new_entry()
{
$this->load->helper('form');
$this->load->library(array('form_validation','session'));
//set validation rules
$this->form_validation->set_rules('entry_name', 'Title', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('entry_body', 'Body', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header', $data);
$this->load->view('admin/new_entry', $data);
$this->load->view('footer', $data);
}
else
{
//if valid
$name = $this->input->post('entry_name');
$body = $this->input->post('entry_body');
$this->articles_model->new_entry($name,$body);
$this->session->set_flashdata('message', '1 new entry added!');
redirect('articles/new_entry');
}
}
VIEW
<h2>Add new entry</h2>
<?php echo validation_errors(); ?>
<?php if($this->session->flashdata('message')){echo $this->session->flashdata('message');}?>
<?php echo form_open('articles/new_entry');?>
<p>Title:<br />
<input type="text" name="entry_name" />
</p>
<p>Body:<br />
<textarea name="entry_body" rows="5" cols="50" style="resize:none;"></textarea>
</p>
<input type="submit" value="Submit" />
<?php echo form_close();?>
MODEL
function new_entry($name,$body)
{
$data = array(
'entry_name' => $name,
'entry_body' => $body
);
$this->db->insert('entry',$data);
}
What can be the cause?
Edit: I'm using Codeigniter 3.
You must initiate the $data variable before passing in to the views.
eg.
$data = array();
put it on the new entry class
I completely agree with the answer from Cha Hernandez, however, another possibility would be:
To remove the $data variable altogether:
$this->load->view('header');
$this->load->view('admin/new_entry');
$this->load->view('footer');
This is mainly because you're not actually passing any information to the view, so there is no point in having it in the instance.
Hope this helps!
Change your CONTROLLER TO file below code where i removed variable $data since it is not assigned to any values and passing undefined variable $data is not necessary.
function new_entry()
{
$this->load->helper('form');
$this->load->library(array('form_validation','session'));
//set validation rules
$this->form_validation->set_rules('entry_name', 'Title', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('entry_body', 'Body', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header');
$this->load->view('admin/new_entry');
$this->load->view('footer');
}
else
{
//if valid
$name = $this->input->post('entry_name');
$body = $this->input->post('entry_body');
$this->articles_model->new_entry($name,$body);
$this->session->set_flashdata('message', '1 new entry added!');
redirect('articles/new_entry');
}
}

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.

Codeigniter form showing validation error of a view within another view

I have a form for user to input some feedbacks, and this form has to be resided in a product detail page. I am required to print out some error validation on the detail page instead of having the form redirected to the feedback form page with the validation message.
The product detail page is located at 'index.php/product/view/1', while the feedback form is at 'index.php/product/add_feedback'.
How can I print out the error form validation message so that it shows on the product detail page, instead of redirection to the add_feedback. Thank you.
My controller:
class Product extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('mproduct');
$this->load->model('mfeedback');
}
public function index()
{
//get product details
$data['content'] = $this->mproduct->get_details();
$this->load->view('listing', $data);
}
public function add_feedback()
{
// feedback form
$this->form_validation->set_rules('name', 'Name', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('feedback', 'Feedback', 'required|xss_clean|max_length[200]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('feedback');
}
else
{
$pid = $this->input->post('pid');
$name = $this->input->post('name');
$feedback = $this->input->post('feedback');
$this->MFeedback->add($pid, $name, $feedback);
redirect('product/view/'.$pid);
}
}
}
Model:
class MFeedback extends CI_Model {
function add_feedback($name, $pid, $feedback)
{
$data = array(
'name' => $name,
'feedback' => $feedback,
'pid' => $pid,
);
$this->db->insert('feedback', $data);
}
}
view - feedback.php
<h1>Add Feedback</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('product/add_feedback'); ?>
<p>Name</p>
<input type="text" name="name" size="50" value="<?php echo set_value('name'); ?>" />
<p>Feedback</p>
<textarea type="text" name="feedback"><?php echo set_value('feedback'); ?></textarea>
<?php echo form_hidden('pid', $this->uri->segment(3, 0)); ?>
<div><input type="submit" value="Add Feedback" /></div>
</form>
Simple! Just add the validation to Product/index-method, like this:
class Product extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('mproduct');
$this->load->model('mfeedback');
}
public function index()
{
// feedback form validation
$this->form_validation->set_rules('name', 'Name', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('feedback', 'Feedback', 'required|xss_clean|max_length[200]');
if ($this->form_validation->run() == TRUE)
{
// the validation passed, lets use the form data!
$pid = $this->input->post('pid');
$name = $this->input->post('name');
$feedback = $this->input->post('feedback');
$this->MFeedback->add($pid, $name, $feedback);
redirect('form/success'); // redirect to a page, where the user gets a "thanks" message - or redirect to the product page, and show a thanks there (but be sure to use redirect and nocht $this->load->view(..), because then the form data would be still in the header and a reload of the page would send another mail :)
}
// form did not pass the validation, lets get and show the product details
$data['content'] = $this->mproduct->get_details();
$this->load->view('listing', $data);
}
}
And in the file feedback.php you'll have to change the form target to something like this:
<?php echo form_open('product/'.$this->uri->segment(3, 0)); ?>
... or even better:
<?php echo form_open('product/'.$content->id); ?>
... depends on your product view.

Categories