Codelgniter Form Validation Showed double repeated form after validate - php

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');
}
}
}

Related

codeigniter pass data from view to controller

I encountered problem with codeigniter. I want to update my profile page. I have problem when passing data from textbox in view to controller. In controller Profile.php, i have print_r $data that show no data get from view. Hope you guys can help me. Thank you.
View profile.php
if(isset($profile)){
?>
<?php echo validation_errors();?>
<?php echo form_open('profile/update_profile'); ?>
<div class="field half first"><input type="password" name="pass" placeholder="Password" value="<?php echo $profile['password']; ?>" /></div>
<div class="field half"><input type="password" name="con_pass" placeholder="Confirm Password" value="<?php echo $profile['con_password']; ?>" /></div>
<div class="field half"><input type="text" name="phone_no" placeholder="Phone Number" value="<?php echo $profile['phone_no']; ?>" /></div>
<li><?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?></li>
</ul>
<?php echo validation_errors();?>
<?php echo form_close(); ?>
<?php
}
?>
Controller Profile.php
public function update_profile(){
$email = $_SESSION['email'];
// $data['profile'] = $this->profile_model->getprofile($email);
$data = array(
'password' => $this->input->post('pass'),
'con_password' => $this->input->post('con_pass'),
'phone_no' => $this->input->post('phone_no')
);
print_r($data);
if($this->profile_model->updateprofile($email,$data))
{
$this->load->view('provider/profile', $data);
}
}
Model profile_model.php
public function updateprofile($email, $data){
$this->db->where('email', $email);
return $this->db->update('user', $data);
}
}
Try like below with form validation
https://www.codeigniter.com/user_guide/libraries/form_validation.html
https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
EXAMPLE
public function update_profile() {
$this->load->library('form_validation');
// You can change what you want set for the rules your self this just example:
$this->form_validation->set_rules('pass', 'pass', 'trim|required');
$this->form_validation->set_rules('con_pass', 'con_pass', 'trim|required|matches[pass]');
$this->form_validation->set_rules('phone_no', 'phone_no', 'trim|required');
if ($this->form_validation->run() == TRUE) {
// Update model stuff
}
$email = $_SESSION['email']; // User id instead of email.
$profile_data = $this->users_model->getprofile($email);
if ($this->input->post('pass')) {
$data['pass'] = $this->input->post('pass');
} elseif (!empty($profile_data)) {
$data['pass'] = $profile_data['pass'];
} else {
$data['pass'] = '';
}
if ($this->input->post('con_pass')) {
$data['con_pass'] = $this->input->post('con_pass');
} elseif (!empty($profile_data)) {
$data['con_pass'] = $profile_data['con_pass'];
} else {
$data['con_pass'] = '';
}
if ($this->input->post('phone_no')) {
$data['phone_no'] = $this->input->post('phone_no');
} elseif (!empty($profile_data)) {
$data['phone_no'] = $profile_data['phone_no'];
} else {
$data['phone_no'] = '';
}
$this->load->view('provider/profile', $data);
}
Model function
public function getprofile($email) {
$this->db->where('email', $email);
$query = $this->db->get('users');
return $query->row_array();
}
View Example
<?php echo form_open('profile/update_profile'); ?>
<?php echo validation_errors();?>
<input type="password" name="pass" value="<?php echo set_value('pass', $pass);?>"/>
<input type="password" name="con_pass" value="<?php echo set_value('con_pass', $con_pass);?>"/>
<input type="text" name="phone_no" value="<?php echo set_value('phone_no', $phone_no);?>" />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?>
<?php echo form_close();?>

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.

Codeigniter validation errors are not displaying

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.

Cant return error message in CodeIgniter 3 callback

I have a problem in my code. I am creating a simple login using CI3 for my small project. My problem is I have an error message in callback validation.
Here's the error I received whenever I try to validate my form.
Unable to access an error message corresponding to your field name Password.(check_database)
Here's mo code in controller:
public function index() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
$this->form_validation->set_error_delimiters('<div class="error text-red">', '</div>');
if($this->form_validation->run() == FALSE) {
$data = array();
$data['modules'] = $this->flx_lib->moduler($data);
$this->load->view('login', $data);
} else {
//ok
}
}
public function check_database($password) {
$username = $this->input->post($username);
$result = $this->flx_users->validate_user($username, $password);
if($result) {
//ok
return TRUE;
} else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return FALSE;
}
}
Here's my view:
<div class="form-group has-feedback <?php error_exists('username'); ?>">
<input type="text" class="form-control" name="username" placeholder="Username" />
<span class="fa fa-user form-control-feedback "></span>
<?php echo form_error('username'); ?>
</div>
<div class="form-group has-feedback <?php error_exists('password'); ?>">
<input type="password" class="form-control" name="password" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
<?php echo form_error('password'); ?>
</div>
Can you help me with this? I am using CI3 with HMVC
Ok I found the error in my code. Actually its an issue with HMVC form validation.
Here's the link for the correct answer:
CodeIgniter - Unable to access an error message corresponding to your field name Password.(pword_check)
Solution:
1. Create MY_Form_validation.php file in libraries folder and paste following code in it.
if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function run($module = '', $group = '')
{
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
And change if ($this->form_validation->run() == FALSE) to if ($this->form_validation->run($this) == FALSE) thats all folks..
public function index() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database',
array('check_database' => 'Invalid username or password.')
);
$this->form_validation->set_error_delimiters('<div class="error text-red">', '</div>');
if($this->form_validation->run() == FALSE) {
$data = array();
$data['modules'] = $this->flx_lib->moduler($data);
$this->load->view('login', $data);
} else {
//ok
}
}
public function check_database($password) {
$username = $this->input->post($username);
$result = $this->flx_users->validate_user($username, $password);
if($result) {
//ok
return TRUE;
} else {
return FALSE;
}
}
I recoded this one. Something was mixed up.
This is from docs:
$this->form_validation->set_rules('field_name', 'Field Label', 'rule1|rule2|rule3',
array('rule2' => 'Error Message on rule2 for this field_name')
);

Not outputting form error messages

I have a form that is not outputting any error messages have I missed something?
Model:
function createUser($username = NULL ,$passwordHash = NULL ,$firstname = NULL ,$lastname = NULL ,$email = NULL,$group = NULL ,$active = NULL)
{
$data = array('userName' => $username, 'userFirstName' => $firstname, 'userLastName' => $lastname, 'userEmail' => $email, 'userPassword' => sha1($passwordHash), 'userGroup' => $group, 'userActive' => $active);
$this->db->insert('users',$data);
return TRUE;
}
View:
<h1><?php echo $companyName; echo nbs(1);?> - <?php echo $pageTitle; ?></h1>
<?php
if($success == TRUE) {
echo '<section id = "validation">Page Updated</section>';
}
?>
<p>Error: <?php echo validation_errors();?> </p>
<div class="formContent">
<form action="createUser" method="post">
<fieldset class="control-group">
<label for="userName">User Name: <input type="text" name="userName" value="<?php echo set_value('userName'); ?>" placeholder="User Name"></label>
<label for="userPassword">User Password: <input type="password" name="userPassword" value="<?php echo set_value('userPassword'); ?>" placeholder="User Password"></label>
<label for="userFirstName">First Name: <input type="text" name="userFirstName" value="<?php echo set_value('userFirstName'); ?>" placeholder="First Name"></label>
<label for="userLastName">Last Name: <input type="text" name="userLastName" value="<?php echo set_value('userLastName'); ?>" placeholder="Last Name"></label>
<label for="userEmail">E-Mail: <input type="text" name="userEmail" value="<?php echo set_value('userEmail'); ?>" placeholder="Admin E-mail"></label>
<label for="userGroup"> User Group:
<select name="userGroup" value="<?php echo set_value('userGroup'); ?>">
<option value="select">Please Select</option>
<option value="admin">Admin Group</option>
<option value="user">User Group</option>
</select>
</label>
<label for="userActive"> User Active:
<select name="userActive" value="<?php echo set_value('userActive'); ?>">
<option value="select">Please Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</label>
<button type="submit" class="btn-primary">Create</button>
</fieldset>
</form>
</div>
Controller:
public function index()
{
$data['companyName'] = $this->core_model->companyName();
$data['success'] ="";
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
if($this->input->post('submit'))
{
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['companyName'] = $this->core_model->companyName();
$data['success'] ="";
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}else{
$username = $this->input->post('userName',TRUE);
$password = $this->input->post('userPassword', TRUE);
$firstname = $this->input->post('userFirstName', TRUE);
$lastname = $this->input->post('userLastName',TRUE);
$email = $this->input->post('userEmail',TRUE);
$group = $this->input->post('userGroup',TRUE);
$active = $this->input->post('userActive', TRUE);
$this->db->escape($username);
$this->db->escape($password);
$this->db->escape($firstname);
$this->db->escape($lastname);
$this->db->escape($email);
$this->db->escape($group);
$this->db->escape($active);
$passwordHash = $this->encrypt->sha1($password);
if ($this->core_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}else{
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
}
}
}
function __username_check($userName){
{
if ($userName == $user->$userName) {
$this->form_validation->set_message('username_check','Sorry the chosen username %s is taken!');
return false;
}else{
return true;
}
}
}
}
/* End of file login.php */
/* Location: ./application/controllers/admin/createUser.php */
You need to place the <input>s outside the <label> </label> tags! This is the main issue.
Also:
there's no input named "submit": your submit button, in fact, has no name attribute. And, btw, since you're already using form_validation class, that check (if input->post('submit')) is redundant;
Another redundant thing I see is passing TRUE (i.e., having it xss_cleaned) to the input->post method: you already have plenty of xss_clean validation rules, so why passing it again in that expensive extra processing, when already passed through it during validation check?
Sidenote, if you're using Active Record, or query bindings, you don't have to escape variables, so I'd remove that part too :)
And I believe your call to __username_check() will fail: the function, as for what concern the "callback_" validation rule, is "username_check"; and besides the double underscore is usually used for "magic methods" in PHP; you can safely remove both, or if you really want an underscore on the function name (just one) you might want to call "callback__check_username".
And you're loading the same views three times, why? I believe you can rewrite the whole index method like this:
function index()
{
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['success'] ="";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$group = $this->input->post('userGroup');
$active = $this->input->post('userActive');
$passwordHash = $this->encrypt->sha1($password);
if ($this->core_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
}
}
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
UPDATE:
as for the username check, since v.2.0 of CodeIgniter you have that ability featured among the validation rules: if you place the is_unique rule, in fact, it will automatically query the database to check for that. The syntax is:
is_unique[table.field]
In your case, might be
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|is_unique[users.userName]|xss_clean');

Categories