$this->form_validation->run() not executing - codeigniter

I have an issue in codeignitor form handling it does not execute $this->form_validation->run() on local server. But it does work very fine on live server. I can't find out what is the reason. Here is my controller.
class Login extends CI_Controller
{
function __construct(){
parent::__construct();
}
function removeUser($record_id){
$a = new Alumni();
$a->removeConnections($record_id);
}
function index(){
$redir = isset($_GET['redir'])?$_GET['redir']:'admin';
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('admin');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/login/send_again/');
} else {
//
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
// Get login for counting attempts to login
if ($this->config->item('login_count_attempts', 'tank_auth') AND
($login = $this->input->post('login'))) {
$login = $this->security->xss_clean($login);
//var_dump($login);
} else {
$login = '';
}
//var_dump($this->input->post("remember"));
$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
if ($data['use_recaptcha'])
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
else
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
$data['errors'] = array();
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
if ($this->form_validation->run() === false) {
}else{
echo " logged in";// validation ok
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
//echo $loginID;
if ($this->tank_auth->login(
$loginID,
$pass,
$remember,
$data['login_by_username'],
$data['login_by_email'])) { // success
echo "success";
redirect($redir);
} else {
$errors = $this->tank_auth->get_error_message();
//echo "error";
if (isset($errors['banned'])) { // banned user
$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);
} elseif (isset($errors['not_activated'])) { // not activated user
redirect('/auth/send_again/');
} else { // fail
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
}
.....
Sorry for long code please help me.

I don't see the library getting loaded in your constructor
public function __construct()
{
parent :: __construct();
$this->load->helper('url');
$this->load->helper('cookie');
//load the validation library
$this->load->library('form_validation');
$this->load->library("pagination");
}

Related

Codeigniter 3 validation error not showing along with callback function

I want to validate login form with ajax. I am using form valiation with a callback function that check username in database. When I am using callback with set_message, form validation errors are not working, only that callback error message is shown. If username is empty then form validation error like "Username is required" should be shown first and then if user enter wrong username then callback function error like "Username is not correct" should be shown
Following are the functions in my controller
public function validate_form()
{
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean|callback_password_check');
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run()) {
$data['success'] = true;
$this->session->set_userdata('admin_username', $this->input->post('username'));
} else {
foreach ($_POST as $key => $value) {
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
public function username_check()
{
$username = $this->input->post("username");
if ($this->admin_model->usernameDB()) {
return true;
} else {
$this->form_validation->set_message('username_check', 'The {field} is not correct');
return false;
}
}
public function password_check()
{
$password = $this->input->post("password");
if ($this->admin_model->passwordDB($password)) {
return true;
} else {
$this->form_validation->set_message('password_check', 'The {field} is not correct');
return false;
}
}
Following are the function in my model
public function usernameDB() {
$this->db->where('username', $this->input->post('username'));
$query = $this->db->get('adminuser');
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
public function passwordDB() {
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('adminuser');
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
Following is the ajax that i am using
$("#admin_login_form").submit(function(e) {
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax ({
url: "validate_form",
type: "post",
data: me.serialize(),
dataType: "json",
success: function(response) {
if (response.success == true) {
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
window.location = "member";
} else {
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value);
});
}
}
});
});
I want proper validation errors order like if username or password is empty then first their relevant errors should be shown like username or password is required and then wrong or correct username or password errors should be shown.
You can try below. You can use single callback function to check whether user is exists or not.
First, remove the callback functions public function username_check() and public function password_check() from your controller and replace with the updated functions below.
In addition to this created new model function login inside admin_model which will check whether user is exists or not. Also you can delete both usernameDB and passwordDB from your admin_model.
Controller function:
public function validate_form()
{
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean|is_user_exists');
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run()) {
$data['success'] = true;
$this->session->set_userdata('admin_username', $this->input->post('username'));
} else {
foreach ($_POST as $key => $value) {
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
public function is_user_exists()
{
if ($this->admin_model->login($this->input->post('username', TRUE), $this->input->post('password', TRUE))) {
return true;
} else {
$this->form_validation->set_message('is_user_exists', 'Login failed. Username or password is incorrect');
return false;
}
}
Model function:
public function login($username, $password)
{
$this->db->where('username', $username);
$this->db->where('password', md5($password));
$query = $this->db->get('adminuser');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
Note: Using md5 for encrypt password is not good. See Alex's comment for more details.

Trying to get my data to display on the view- codeigniter

From my controller, I am able to get the session date to display on my view, I however an missing something in the syntax when it comes to displaying the data from my table. i.e $data['modelData']. How do I do that?
Controller:
function validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required|md5');
if ($this->form_validation->run() == FALSE )
{
$this->load->view('login_form');
//return false;
}
else{
$this->load->model('login_model');
$email = $this->input->post('email');
$password = $this->input->post('password');
//echo $email;
// echo $password;
$result = $this->login_model->match_login($email, $password);
if ($result ==false) {
echo "Invalid Cardinals";
}
else
{
$session = array(
'id'=>$result[0]['id'],
'email'=>$this->input->post('email'),
'is_logged_in'=> 1
);
if (!$this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
else {
echo "Error in session";
}
}
}
}
Model
class Login_model extends CI_Model{
//client..model
public function match_login($email, $password){
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get('user');
$result = $query->result_array();
if (empty($result))
{
return false;
}
else
{
return $result;
}
}
}
Try this
In Controller
if (!$this->session->set_userdata($session)) { # Changed
echo "Error in session";
}
else {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
In View
// retrieving modelData
foreach ($modelData as $modelItem) {
echo "Model ID is ".$modelItem['id'];
}
// retrieving sessionData
foreach ($sessionData as $sessionitem) {
echo "Session ID is ".$sessionitem['id'];
echo "Session Email is ".$sessionitem['email'];
}
Replace:
if (!$this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
with
if ($this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
Explantion:
You could not get data from the table since the set_userdata function returned true therefore the control statement ignored the statements if block.

Show message on form submit using JForm loadform object in Joomla

I want to show success message after submitting the form. The currently message is working it is saying item successfully saved. But i also want to change this message. Is there a way or am i doing something wrong. This is my code example in model of my custom component.
class IAdonaModelPost extends JModelAdmin
{
protected function allowEdit($data = array(), $key = 'id')
{
//echo "<pre>"; print_R($data); print_r($key);die;
//return JFactory::getUser()->authorise('core.edit', 'com_events.message.'.((int) isset($data[$key]) ? $data[$key] : 0)) or parent::allowEdit($data, $key);
}
public function getTable($type = 'Eventpost', $prefix = 'iAdonaTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true)
{
$form = $this->loadForm('com_iadona.post', 'post', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
//$displaymsg = "My message text..";
// JFactory::getApplication()->enqueueMessage($displaymsg);
}
protected function loadFormData()
{
$data = JFactory::getApplication()->getUserState('com_iadona.edit.post.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}

Unset sessions after form success not working

When I deselect my check box in my modify & access permissions it does not unset it from sessions if form is submitted success full.
What I am trying to achieve is on my edit function if any check box is not checked then it will unset from sessions when form is submitted success full. Because the reason need it unset from sessions is because when user logs in the permissions modify and access are set into sessions.
How can I make this work what I am after I have tried it in my edit but not unset when check box is empty
If i use this $this->session->unset_userdata('modify'); it unset all the modify array in sessions I just need it to unset the one that matches the unchecked check box.
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
if ($this->session->userdata('user_id') == TRUE) {
if (isset($_POST['permission[access]'])) {
$this->session->unset_userdata('permission[access]');
}
if (isset($_POST['permission[modify]'])) {
$this->session->unset_userdata('permission[modify]');
}
}
redirect('admin/users_group');
}
$this->getForm();
}
public function getForm() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->uri->segment(4) == FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
if ($this->uri->segment(4) == FALSE) {
$data['user_group_id'] = $this->input->post('user_group_id');
} else {
$data['user_group_id'] = $user_group_info['user_group_id'];
}
$ignore = array(
'admin',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['permissions'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$permission = basename(strtolower($file), '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
$permission_access = $this->input->post('permission');
if (isset($permission_access)) {
if (isset($permission_access['access'])) {
$data['access'] = $permission_access['access'];
} elseif (!empty($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
}
$permission_modify = $this->input->post('permission');
if (isset($permission_modify)) {
if (isset($permission_modify['modify'])) {
$data['modify'] = $permission_modify['modify'];
} elseif (!empty($user_group_info['permission']['modify'])) {
$data['modify'] = $user_group_info['permission']['modify'];
} else {
$data['modify'] = array();
}
}
$this->load->view('template/user/users_group_form.tpl', $data);
}
I have found away to get it working I have got sessions from database then re set the sessions in form, without using unset_sessions();
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
$user_group_query = $this->db->query("SELECT permission FROM " . $this->CI->db->dbprefix . "user_group
WHERE user_group_id = '" . (int)$this->session->userdata('user_group_id') . "'");
$permissions = unserialize($user_group_query->row('permission'));
$this->session->set_userdata($permissions);
redirect('admin/users_group');
}
$this->getForm();
}

codeinighter where field = data from form

I'm trying to match up suppliers from a postcode search:
Model code:
function get_suppliers(){
$this->db->from('suppliers');
$this->db->where('postcode', $data);
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
Controller code:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
echo("postcode entered");
$data['rows'] = $this->site_model->get_suppliers($data);
print_r($data);
}
}
Obviously ignore the printers and echo thats just me bring to see whats going on I'm pretty sure i need to just change the $data in model to something just not sure what(tried heaps of things)
Model:
function get_suppliers($postcode = '*') // <-- Capture the postcode
{
$this->db->from('suppliers');
$this->db->where('postcode', $postcode); // <-- pass it in here
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Controller:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
$data['rows'] = $this->site_model->get_suppliers( $data['postcode'] ); // <-- pass the postcode
echo("postcode entered: " . $data['postcode'] . "<pre>");
print_r($data);
}
}
In your model:
function get_suppliers($data = ''){
i.e.: You haven't included $data as the argument

Resources