I am using form validation of CodeIgniter, it works fine but when, form validation fails, it does not display the validation errors, by using
<?php echo validation_errors();?>
I am using
function insertProduct(){
$this->load->library('form_validation');
$this->form_validation->set_rules('pname','ProductName','trimirequired');
if($this->form_validation->run()){
$this->addProduct();
}
else{
$this->load->model('inventory/stock');
}
In your view you should have something like (this example shows errors individually);
<?php echo form_error('p_name'); ?>
<label for="p_name">Product Name</label>
<input type="text" id="p_name" name="p_name" value="<?php echo set_value('p_name'); ?>" />
You need to tell the method in your controller to render a view on success/failure of the form validation.
If you change your insertProduct method to the following, it 'should' solve your issue.
function insertProduct(){
$this->load->library('form_validation');
$this->form_validation->set_rules('pname','ProductName','trimirequired');
if($this->form_validation->run()){
$this->addProduct();
$this->load->view('{name_of_your_view}');
} else{
$this->load->model('inventory/stock');
$this->load->view('{name_of_your_view}');
}
}
Where 'name_of_your_view' is the view that you've placed the validation_errors() code in.
This example from the CodeIgniter tutorial pages explains how to validated submitted data to display validation errors at the header of the form like you might expect:
http://codeigniter.com/user_guide/tutorial/create_news_items.html
The example code for the creation function looks like this:
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
As others have said, though, you need to add a view to handle success and return them to the form to display errors on failure.
We can change the line containing following code:
$this->form_validation->set_rules('pname','ProductName','trimirequired');
to:
$this->form_validation->set_rules('pname','ProductName','trim|required');
if($this->form_validation->run($this) == false)
{
$this->addProduct();
}
Related
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');
}
}
This is my first time using CodeIgniter and I am trying to create a Log In form. Whenever I click on the submit button that I have created, it brings me to a 404 Page Not Found Error.
I have made a view_login.php in the view folder with this code:
<?php echo form_open('user/login') ?>
<ul>
<li>
<label> username </label>
<div>
<?php echo form_input(array('id' => 'username', 'name' => 'username')); ?>
</div>
</li>
<li>
<label> password </label>
<div>
<?php echo form_password(array('id' => 'password', 'name' => 'password')); ?>
</div>
</li>
<li><?php echo validation_errors(); ?></li>
<li>
<?php echo form_submit(array('name' => 'submit'), 'login'); ?>
</li>
This is my user.php controller:
<?php
class User extends CI_controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function register()
{
$this->load->library('form_validation');
if($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('user/view_register');
$this->load->view('templates/footer');
}
else
{
echo 'this is being processed. thank you';
}
$this->load->view('user/view_register');
}
public function login()
{
$this->load->library('form_validation');
$data['title'] = 'Log In';
$this->load->view('user/view_login');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('user/view_login');
$this->load->view('templates/footer');
{
else
{
$user_id = $this->User_model->check_login($this->input->post('username',
$this->input->post('password');
Here is my User_model:
class User_model extends Model {
function User_model()
{
parent::Model();
}
function check_login($username, $password)
{
$sha1_password = sha1($password);
$query_str = "SELECT user_id FROM users WHERE username = ? and password = ?";
$result = $this->db->query($query_str, array($username, $sha1_password));
if ($result->num_rows() ==1)
{
return $result->row(0)->user_id;
}
else
{
return false;
}
Any help would be immensely appreciated :)
I know you're going to delete your question eventually, as you did with your previous three (that I know of), but hey.
You're doing a lot of things wrong. Let's do some cleanup:
<?php
class User extends CI_controller
{
// constructor is useless here, let's remove it.
function index()
{
redirect('login','refresh');
// this is useless too, but just in case someone navigates to the url 'user'
}
function login()
{
// you are calling form_validation methods, and loading the library _after_.
// It's the other way around.
// Also, no need to load the form helper, it's already loaded
// by the form_validation library
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|max_length[200]|xss_clean');
$this->load->view('pages/view_login');
if ($this->form_validation->run() == FALSE) {
$this->load->view('view_login');
{
else {
//extract($_POST);
// this is quite bad practice imho (it's like goring back to register_globals).
// You should fetch the post content directly:
$user_id = $this->user_model->check_login($this->input->post('username',
$this->input->post('password');
}
}
?>
Now, as I said in your previous questions, which all dealt with the SAME EXACT 404 ERROR, I'm going to tell you again: FOLLOW THE MANUAL. Don't invent new ways of using the built-in framework functions. They're there for a purpose.
You should open the form like this:
<?php echo form_open('user/login'); ?>
It will build the correct url by itself. And don't tell "I already did that" again, because you didn't, in fact every question of yours still shows the same mistakes in url building all over again.
I'm sorry to be harsh, I hope something will get grasped eventually.
function user()
{
parent::Controller();
}
should be
function user()
{
parent::__construct();
}
also you are loading
$this->load->view('pages/view_login');
and
$this->load->view('view_login');
check your code, sure these views exists both?
also i really think you can remove all this part:
function index()
{
$this->login();
}
also, you are using index.php in form open, are you removing that from url with htacces? 404 is page not found
This is where your problem could be. I suspect you are confusing your controller name with a subdirectory inside view:
$this->load->view('user/view_login');
Currently, You are loading the view_login.php from a folder/directory known as user. You get a 404 Page Not Found Error if page is not in the referenced directory. It does not exist.
I think this is some error, because user is actually your controller and should be used only from the form as:
<?php echo form_open('user/login'); ?>
except your have view_login.php existing in a subdirectory known as user.
view/
user/
view_login.php
Try putting view_login.php directly into the view folder and use this to call it:
view/
view_login.php
$this->load->view('view_login');
In same vein,
$this->load->view('templates/header', $data);
$this->load->view('user/view_login');
$this->load->view('templates/footer');
Also means that header.php and footer.php are in subdirectories "templates". An error with any of these would give you the 404 error. You might want to try commenting out your load view and test by echoing out some string -- just to prove your codes are all fine.
Verify if you might be having interference from your htaccess file by testing if every other url works well.
[UPDATE]
If you have doubts whether your form action is correct, try using base_url() if that is configured correctly.
<?php echo form_open(base_url().'user/login') ?>
That should accurately point to site/controller/method(function)
Like I mentioned in my comment, I didn't see you use form_validation->rule() anywhere in your code. You could possible check to see if it was false.
Replace your login function with the one below and test:
public function login() {
$this->load->library('form_validation');
$data['title'] = 'Log In';
if ($this->input->post()) {
print_r(); //test if you have values
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
//You could set delimiter
if ($this->form_validation->run() == FALSE) {
//What so ever you which to do if validation fails. { else {
$username = $this->input->post('username'); //Make your code a bit readable
$password = $this->input->post('password'); //Make your code a bit readable
$user_id = $this->User_model->check_login($username, $password);
$data["user_id"] = $user_id; //you can access $user_id from your view
}
}
//Pass $data to views, you might need it in more than one view. Also change directory from user to pages to match what you stated in comment below. And please make sure these views are in the directories specified below...
$this->load->view('templates/header', $data);
$this->load->view('pages/view_login', $data);
$this->load->view('templates/footer', $data);
}
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
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.
I have function like this:
function gi_insert()
{
if(!IS_AJAX){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Naslov', 'trim|required|strip_tags');
$this->form_validation->set_rules('body', 'Tekst', 'trim|required|strip_tags');
$this->form_validation->set_rules('email', 'E-mail', 'trim|required|strip_tags|valid_email');
$this->form_validation->set_rules('tag', 'Tagovi', 'trim|required|strip_tags');
if(isset($_POST['category_new'])){
$this->form_validation->set_rules('category_new', 'Kategorija', 'trim|strip_tags');
}
$p = $this->uri->segment(3);
if ($this->form_validation->run() == FALSE)
{
$errors = validation_errors();
redirect("admin/create/$p", 'location');
}
else
{
$this->gi->gi_insert();
redirect('admin/pregled/' . $this->uri->segment(3));
}
} else
{
$this->gi->gi_insert();
}
}
How can I send validation errors to admin/create controller? At the moment, this is working, but I don't get error report (page where errors should appear is containig
<?php echo validation_errors(); ?>
)
validation_errors() only works if the $_POST data is still set, since you redirect to admin/create, $_POST is empty and the function no longer works, returning nothing.
You could send the errors with a piece of flashdata to the page.