Codeigniter validation errors are not displaying - php

My codeigniter validation errors are not displaying someone can help?
my code is
public function addProduct(){
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
if (!$this->form_validation->run() == FALSE)
{
// some stuff on validation success
}
else{
$this->load->view('product/addProduct');
}
}
and i have added
echo validation_errors(); in my view and action of the form is product/addProduct.

Try this it's work for you.
form_error() function return your form error.
$post_fields = $this->input->post();
$data['msg'] = '<ul>';
foreach ($post_fields as $k => $v) {
if (form_error($k))
$data['msg'] .= "<li>" . strip_tags(form_error($k)) . "</li>\n";
}
$data['msg'].='</ul>';
$this->load->view('product/addProduct',$data);
OR
echo validation_errors();//this function also return form error.

On view example
<?php echo validation_errors('<div class="error">', '</div>'); ?>
<!-- lower case for the controller name on form open -->
<?php echo form_open_multipart('product/addProduct');?>
<h5>productName</h5>
<input type="text" name="productName" value="<?php echo set_value('productName'); ?>" size="50" />
<h5>productPrice</h5>
<input type="text" name="productPrice" value="<?php echo set_value('productPrice'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close();?>
Controller
Make sure your file name and class name is something like this below where first letter only upper case
Guide
Filename: Product.php
<?php
class Product extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->helper('url');
}
public function addProduct(){
// You can get data from here also
$this->data['some'] = 'Blah';
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
// remove your !
if ($this->form_validation->run() == FALSE){
// You can just display view in this area you do not have to load it multiple times
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
} else {
// some stuff on validation success
}
}
}
Also check you have set your base url in config.php is required now in CI3 versions.

Related

Feedback page not responding in codeigniter

I am trying to submit a feedback after logging in the user. The Data in not being inserted in the database nor is it displaying any message if the form is left empty.
This is my controller:
function dashboard(){
$this->load->model('stud_model');
$this->form_validation->set_rules('name','Name', 'required');
$this->form_validation->set_rules('email', 'Email Id', 'required');
$this->form_validation->set_rules('feedback', 'Feedback', 'required');
$data['username'] = $this->session->userdata('username');
if ($this->form_validation->run()) {
$data = array(
'Name' => $this->input->post('name'),
'Email' => $this->input->post('email'),
'Feedback' => $this->input->post('feedback'),
);
$submit = $this->stud_model->insert_feedback($data);
if($submit) {
$this->session->set_flashdata('message', 'Feedback Successfully Submitted !');
redirect('Students/enter');
}else{
$this->session->set_flashdata('message', 'Feedback could not be Submitted !');
redirect('Students/enter');
}
}else{$this->load->View('dashboard', $data);}
}
function enter(){
if ($this->session->userdata('username') != '') {
$data['username'] = $this->session->userdata('username');
$this->load->View('dashboard', $data);
}else{
redirect('Students/log');
}
}
function logout(){
$this->session->unset_userdata('username');
redirect('Students/index');
}
This is my view:
<body>
<h1 align="center">My Dashboard</h1><br><br>
<h3 align="left">Welcome <?php echo $username ?> !</h3>
<form action="http://localhost/ci/index.php/Students/dashboard" align="center">
<?php echo validation_errors(); ?>
<br>
<input type="hidden" name="name" value="<?php echo $username ?>"><br>
Email Id : <br><input type="text" name="email"><br><br>
Feedback:<br><br>
<textarea name="feedback" rows="10" cols="50"></textarea><br><br>
<input type="submit" value="Submit"><br><br>
<?php echo $this->session->flashdata("message"); ?>
Logout
</form>
</body>
This is my Model:
function insert_feedback($data){
$this->load->database();
$this->db->insert("feedback", $data);
return $this->db->insert_id();
}
I think you use
$this->load->library('database');
Instead
$this->load->database();
Change setting on config folder in autoload.php
$autoload['libraries'] = array('database','form_validation', 'session');
$autoload['helper'] = array('url','form');
Got the Error myself.
I had forgot to add 'method="post"' to my form.

Codelgniter Form Validation Showed double repeated form after validate

Tried to read though all the webpages and docs in google and stack flow but still could not solve the problem.
I tried to do a simple data validation for registration form and it turns out showing another form below the original one after I press submit to show the error messages with a new form.
I am a newbie in this language so please let me know if I attache not enough codes or information.
Controller account:
<?php
class Account extends MY_Controller {
public function __construct() {
parent::__construct();
session_start();
$this->load->model('user');
$this->load->helper(array('form','url','html'));
$this->load->library('session');
$this->load->library('form_validation');
}
public function registration() {
$data = $this->user->users_info();
$this->load->view('account/registration',$data);
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password ', 'required|matches[passconf]|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if($this->input->post('submit')) {
$username= $this->input->post('username');
$email= $this->input->post('email');
$query_u= $this->user->retrieve_by_username($username);
$query_e= $this->user->retrieve_by_email($email);
if ($this->form_validation->run() == FALSE){
$this->load->view('account/registration',$data); ←---------------- (I think this is wrong, it makes load the second form out.)
}
else{
if(!empty($query_u) or !empty($query_e)) {
redirect('account/registrat');
}
else {
$data = array(
'username'=>$this->input->post('username'),
'email'=>$this->input->post('email'),
'password'=>$this->input->post('password'),
'is_admin'=>0,
);
$this->user->create_user($data);
redirect('/account/login');
}
}
}
}
View Registration.php
<center>
<?php echo form_open_multipart('account/registration'); ?>
<h5><?php echo $b_username;?> (Minimum 5 characters)</h5>
<input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" size="50" /><?php echo form_error('username'); ?>
<h5><?php echo $b_email;?></h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<?php echo form_error('email'); ?>
<h5><?php echo $b_password;?> (Minimum 5 characters)</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<?php echo form_error('password'); ?>
<h5><?php echo $b_passconf;?></h5>
<input type="text" name="passconf" value="" size="50" />
<?php echo form_error('passconf'); ?>
<h5></h5>
<div><?php echo form_submit('submit', 'Submit') ?></div>
</center>
Model user.php
<?php
class User extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function users_info() {
$data['b_id'] = 'id';
$data['b_username'] = 'Username';
$data['b_email'] = 'Email';
$data['b_password'] = 'Password';
$data['b_passconf'] = 'Enter Password Again';
$data['b_is_admin'] = 'Is_admin';
$data['b_default_privacy'] = 'Default_privacy';
$data['b_first_name'] = 'First_Name';
$data['b_last_name'] = 'Last_Name';
$data['b_gender'] = 'Gender';
$data['b_birthday'] = 'Birthday';
$data['b_friend_id'] = 'Friend_id';
$data['b_weight'] = 'Weight';
$data['b_height'] = 'Height';
$data['b_daily_cal_intake'] = 'Daily_calorie_intake';
$data['b_target_weight'] = 'Target_weight';
$data['b_regional_id'] = 'Region';
$data['b_profile_pic'] = 'Profile Picture';
return $data;
}
function retrieve_by_username($username) {
$query = $this->db->get_where('001_users',array('username'=>$username));
return $query->row_array();
}
function retrieve_by_email($email) {
$query = $this->db->get_where('001_users', array('email'=>$email));
return $query->row_array();
}
Change your function to this and try..
public function registration()
{
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password ', 'required|matches[passconf]|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if ($this->form_validation->run() == false) // if validation fails for first time and every time when ever condtion is not satisified
{
$data = $this->user->users_info();
$this->load->view('account/registration',$data);
}
else
{
$username= $this->input->post('username');
$email= $this->input->post('email');
$query_u= $this->user->retrieve_by_username($username);
$query_e= $this->user->retrieve_by_email($email);
if(!empty($query_u) or !empty($query_e)) {
redirect('account/registrat');
}
else {
$data = array(
'username'=>$this->input->post('username'),
'email'=>$this->input->post('email'),
'password'=>$this->input->post('password'),
'is_admin'=>0
);
$this->user->create_user($data);
// send sucess msg here
redirect('/account/login');
}
}
}

Codeigniter form validation is not showing errors

I'm new to Codegniter so go easy on me. I'm building a simple login form and I have successfully redirected to a page when the login credentials are correct. However, if I submit an empty form I get no error messages. I'm also using set_value in the form field and codeigniter does not refill what the user inputted once the form is submitted. Somehow that data is being cleared. Here are a few things i've done for clarity sake.
Auto-loaded the form_validation library
Auto-loaded form helper
Echoed validation_errors above form
account.php (controller)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('User_model', 'user');
}
public function index() {
$this->load->view('home');
}
public function validate() {
$this->form_validation->set_rules('username', 'username', 'xss_clean|required');
$this->form_validation->set_rules('password', 'password', 'xss_clean|required|md5');
$user_data = array(
'username' => $this->input->post('username'),
'password' => MD5($this->input->post('password'))
);
if ($this->form_validation->run() == FALSE)
{
$data['title'] = "Login Fool";
$this->load->view('templates/header', $data);
$data['contents'] = $this->load->view('login_view', $data, TRUE);
$this->load->view('page', $data);
$this->load->view('templates/footer');
}
else
{
$validated = $this->user->validate($user_data['username'], $user_data['password']);
if($validated){
redirect(base_url() . 'account');
}
else{
$this->session->set_flashdata('LoginError', 'Sorry, your credentials are incorrect.');
redirect(base_url() . 'account/login');
}
}
}
public function login() {
$data['title'] = "Login Fool";
$this->load->view('templates/header', $data);
$data['contents'] = $this->load->view('login_view', NULL, TRUE);
$this->load->view('page', $data);
$this->load->view('templates/footer');
}
}
login_view.php (view)
<h1>Login Now</h1>
<?php
if(validation_errors() != false) {
echo "<div id='errors'>" . validation_errors() . "</div>" ;
}
?>
<?= ($this->session->flashdata('LoginError')) ? '<p class="LoginError">' . $this->session->flashdata('LoginError') . '</p>' : NULL ?>
<?php echo form_open('account/validate'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username" value="<?php echo set_value('username'); ?>"/>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="passowrd" name="password" value="<?php echo set_value('password'); ?>"/>
<br/>
<input type="submit" value="Login"/>
</form>
Any ideas why the errors won't show above the form?
Turns out my model was the culprit. It was extending CI_Controller not CI_Model. Thanks to everyone who took a look at this. This code works.

Error 500 after submitting the form in codeigniter

Using these MVC, I get Error 500. Any ideas?
Controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Download extends CI_Controller {
function __construct()
{
parent::__construct();
parent::__construct();
$this->load->library('form_validation');
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('upload_model');
//$this->output->enable_profiler(TRUE);
}
function index()
{
$this->form_validation->set_rules('enter_product_name',
'Enter Product Name',
'required|max_length[200]');
$this->form_validation->set_rules('test_type',
'Test Type',
'required|max_length[200]');
$this->form_validation->set_rules('test_unit',
'Test Unit',
'required|max_length[200]');
$this->form_validation->set_rules('project_code',
'Project Code',
'required|max_length[200]');
$this->form_validation->set_error_delimiters('<br /><span class="error">',
'</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$data->page = 'download_form_view';
$this->load->view('container', $data);
// $this->load->view('upload_form_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$file_name_info = $this->input->post('enter_product_name')
.'_'. $this->input->post('test_type')
.'_'. $this->input->post('test_unit')
.'_'. $this->input->post('project_code');
$filename_data = array(
'download_name' => $file_name_info
);
// run insert model to write data to db
if ($this->download_model->DownloadName($filename_data) == TRUE)
{
//redirect('download/download');
$this->download();
}
else
{
echo 'An error occurred while saving your filename to database. Please contact Admin with Issue No.[1]';
// Or whatever error handling is necessary
}
}
}
function download()
{
$this->load->helper('download');
$this->db->select('download_name');
$this->db->where("id", "0");
$this->db->limit(1);
$query = $this->db->get('downloadname');
$download_save_name = $query->row()->download_name;
$data = file_get_contents("./uploads/$download_save_name.xlsx");
force_download("$download_save_name.xlsx", $data);
}
}
?>
View
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => ''); echo
form_open('download', $attributes); ?>
<p>
<label for="enter_product_name">Enter Product Name <span class="required">*</span></label>
<?php echo form_error('enter_product_name'); ?>
<br /><input id="enter_product_name" type="text" name="enter_product_name" value="<?php echo
set_value('enter_product_name'); ?>" /> </p>
<p>
<label for="test_type">Test Type <span class="required">*</span></label>
<?php echo form_error('test_type'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'LongTerm' => 'Long Term Study',
'ShortTerm' => 'Short Term Study',
'Experimental' => 'Experimental Study',
); ?>
<br /><?php echo form_dropdown('test_type', $options, set_value('test_type'))?> </p>
<p>
<label for="test_unit">Test Unit <span class="required">*</span></label>
<?php echo form_error('test_unit'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Hyd' => 'Hyd Unit',
'Viz1' => 'Viz Unit-1',
'Viz2' => 'Viz Unit-2',
); ?>
<br /><?php echo form_dropdown('test_unit', $options, set_value('test_unit'))?> </p>
<p>
<label for="project_code">Project Code <span class="required">*</span></label>
<?php echo form_error('project_code'); ?>
<br /><input id="project_code" type="text" name="project_code" value="<?php echo set_value('project_code'); ?>" /> </p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?> </p>
<?php echo form_close(); ?>
Model
<?php
class Download_model extends CI_Model {
function __construct() { parent::__construct(); }
function DownloadName($filename_data)
{
$this->db->update('downloadname', $filename_data, "id = 0");
if ($this->db->affected_rows() == '1') { return TRUE; }
return FALSE; } } ?>
I think the problem is:
you loaded
$this->load->model('upload_model');
and in your model code you have given
class Download_model extends CI_Model {
change this to
class Upload_model extends CI_Model {

Code Igniter form not posting

I have made a site in CodeIgniter2, but I can't get the forms to work, as I can't seem to even work out how to get it to post! Any help? Here is my code and the forms are only on the recommend, contact-us and support pages:
Form:
<div id="mainWhiteBox">
<h3>Tell people about us...</h3>
<p>If you know of a company or individual who need a really great design agency to help them with a project, let them know about us and benefit too. <br /><br />
<span class="customColour">We will give you £50 of Marks & Spencer vouchers for every client you recommend to us who goes on to become a client of xxxxx, it's that simple & there is no limit to the amount of vouchers you can earn!</span></p>
<div id="recommendSomeone">
<?php echo validation_errors(); print_r($_POST);?>
<?php echo form_open('recommend', array('id' => 'recommendForm')); ?>
<label for="friendName">Your Friend's Name</label>
<input type="text" id="friendName" value="<?php echo set_value('friendName'); ?>" />
<label for="friendEmail">Your Friend's Email Address</label>
<input type="email" id="friendEmail" value="<?php echo set_value('friendEmail'); ?>" placeholder="someone#youknow.com" />
<label for="customerName">Your Name</label>
<input type="text" id="customerName" value="<?php echo set_value('customerName'); ?>" />
<label for="customerEmail">Your Email Address</label>
<input type="email" id="customerEmail" value="<?php echo set_value('customerEmail'); ?>" placeholder="you#youremailaddress.com" />
<label for="friendConfirm"><input type="checkbox" id="friendConfirm" value="1" <?php echo set_checkbox('friendConfirm', '1'); ?> />I confirm that I know the person I am recommending above.</label>
<input type="submit" value="Submit Recommendation" />
</form>
<img src="<?=base_url(); ?>images/uploads/<?php echo $images[0]["image_filename"]; ?>" alt="<?php echo $images[0]["image_alt"]; ?>" width="180px" height="300px" class="floatRight" />
</div>
<p class="elevenFont">* Get £50 of Marks & Spencer vouchers per company or person recommended who goes on to open an account with xxxxx.</p>
</div>
<?php include("/home/xxxxx/libraries/application/views/widgets/newsWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/twitterWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/quickViewWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/fbLikePageWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/getQuoteBarWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/newsletterSubscribeWidget.php"); ?>
Controller:
<?php
class Pages extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('pages_model');
}
public function view($page = 'home')
{
if ( ! file_exists('/home/urbanfea/libraries/application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = $this->pages_model->getTitle($page);
$data['showcase'] = $this->pages_model->getShowcase();
$data['news'] = $this->pages_model->getNewsWidgetContent();
$data['quote'] = $this->pages_model->getQuoteFromBank();
$data['images'] = $this->pages_model->getPageImageArray($page);
$data['PageStraplines'] = $this->pages_model->getStraplines($page);
$data['serverStatus'] = $this->pages_model->getIssue("1");
if($page == "support")
{
$this->load->view('templates/supportHead', $data);
}
else
{
$this->load->view('templates/head', $data);
}
if($page == "recommend" || $page == "contact-us" || $page == "support")
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('friendName', 'Friend\'s Name', 'required');
$this->form_validation->set_rules('friendEmail', 'Friend\'s Email Address', 'required');
$this->form_validation->set_rules('customerName', 'Customer\'s Name', 'required');
$this->form_validation->set_rules('customerEmail', 'Customer\'s Email Address', 'required');
//$this->form_validation->set_rules(FriendConfirm', 'Confirm you know the person', 'required');
if ($this->form_validation->run() === true)
{
$this->load->view('templates/formSuccess', $data); echo "a";
}
elseif($this->form_validation->run() === false && validation_errors() != "")
{
$this->load->view('templates/formError', $data); echo "b";
}
elseif($this->form_validation->run() === false)
{
echo "c";
}
}
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
}
?>
Edit
Here are the routes in my router:
$route['404_override'] = '';
$route['user/(:any)'] = 'user/view/$1';
$route['user'] = 'user/login';
$route['our-work/(:any)'] = 'our_work/view/$1';
$route['our-work'] = 'our_work';
$route['what-we-do/(:any)'] = 'what_we_do/view/$1';
$route['what-we-do'] = 'what_we_do';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
Your form_open function echo form_open('recommend', array('id' => 'recommendForm')); will create the following output: <form method="post" accept-charset="utf-8" action="http:/example.com/index.php/recommend" />
This is looking for a controller called recommend, which I don't think is what you want. Change the form_open function so it directs your form to the proper controller/action.
Also, it doesn't look like your code is taking full advantage of the MVC framework. Instead of handling passing everything through the same controller/function and having all those if statements to load different views based on what $page is, you should have separate functions for each of those views.
EDIT:
Your form input elements are missing the name attribute. They must have the name attribute to be accessible through $_POST. Take a look at this page in the Codeigniter help. Maybe make use of the form_input function to generate the input fields?

Categories