how to use callback in codeigniter - php

I'm using codeigniter and I want to create validation for name field if the name exists in my table. ut I'm getting blank screen, can everyone help me?
this is my controller:
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
}
public function isNameExist($name) {
$this->load->library('form_validation');
$is_exist = $this->cabang_model->isNameExist($name);
if ($is_exist) {
$this->form_validation->set_message('isNameExist', 'Name is already exist.');
return false;
} else {
return true;
}
}
and this is my model
public function isNameExist($name) {
$this->db->select('nama_cabang');
$this->db->where('nama_cabang', $name);
$query = $this->db->get('master_cabang');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
After submit I get the blank screen.
Thanks,
Martin

You can simply use is_unique to perform this action instead of using callback.
Your syntax will be
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|is_unique[master_cabang.nama_cabang]');

The problem is on your insertCabang() controller function. You run the
validation, but what should it do after? You must echo the result, or load some view.
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
if($this->form_validation->run()){
echo 'validated ok';
}else{echo validation_errors();}
}

Related

How to check if email already exists in db with CodeIgniter

I am doing application in CodeIgniter. I don't know how to compare email against db in CodeIgniter, please any one, help me.
Controller
public function signup()
{
$this->load->view('signup');
}
public function savedata(){
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'firstname', 'required');
$this->form_validation->set_rules('lastname', 'lastname', 'required');
if ($this->form_validation->run() == TRUE) // Only add new option if it is unique
{
$result = $this->account_model->insert();
if($result > 0)
{
$data['message'] = "Added successfully";
$this->load->view('signup',$data);
}
else
{
$this->index();
}
}
else
{
$this->load->view('signup');
}
}
How to check whether email already exists or not?
Suppose, you have user table and email column. So you have to add this line in form validation
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[users.email]');
Note
And need an unique index in your email column
check Documentation
Add a rule:
$this->form_validation->set_rules('email', 'Email', 'callback_rolekey_exists');
In the same Controller:
function rolekey_exists($key) {
$this->roles_model->mail_exists($key);
}
In Model,
function mail_exists($key)
{
$this->db->where('email',$key);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
Reference
Best Way
$this->form_validation->set_rules(
'email', 'Email', 'valid_email|required|is_unique[usr_user.user_email]',
array('is_unique' => 'This %s already exists.')
);
//in controller
public function usernameExist($username)
{
$user = $this->Model-> usernameExist($username);
if ($user) {
$this->form_validation->set_message(
'usernameExist',
'Username is already exist.'
);
return false;
} else {
return true;
}
}
function username_Exist($key)
{
$this->db->where('username', $key);
$query = $this->db->get('signup');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
//type this in model
$this->form_validation->set_rules('username', 'User', 'trim|required|callback_username_Exist');
//type in controller in form validation

How to write own function to check if two fields are same using form_validation in codeigniter?

I am using codeigniter and using 'form_validator' to validate posted data from a form. I am come across a situation where I need to check if 2 fields are having same values. There is already a functionality available
$this->form_validation->set_rules( 'new_password', 'New Password', 'trim|required|matches[cpassword]|md5' );
I want to know where the function is written for matches OR where I can define a new function say exactly instead of using matches?
It is defined in system/libraries/form_validation.php
but i would recommend that instead of making changes in the library, you better extend it!
You can create your own "Callbacks" functions
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks
example from user guide...
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_myown_check');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
public function myown_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('myown_check', 'The %s field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
}

Object not found on codeigniter

I have codeigniter installed on my localhost
The main.php controller is
class Main extends CI_Controller {
public function index()
{
$this -> login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
}
The login is working page is coming,but after I fill the username and password,should take me to login/main/login_validation and from there the function login_validation() should either redirect to main/members or show me the login page.But what happens is when I submit the form,the object not found error is coming.Can anyone help me out?
form is
form_open('main/login_validation');
To answer what I think your question is getting at, you're using the form_validation class wrong. You should be testing whether or not the form_validation->run() is TRUE (all fields passed validation) or FALSE (there was an error in one or more of the inputs). Structure you code like such:
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('login');
}
else
{
redirect('main/members');
}
}
This is covered in the CodeIgniter documentation here.
in your controller ..you could try this..
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login');
}
else
{
$this->check_database();
//redirect('home');
}
}
function check_database()
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
$password = $this->input->post('password');
//query the database
$query_result = $this->model_login->login($username, $password);
if($query_result)
{
$this->load->view('main/members');
}
else
{
redirect('login');
}
}
in model
function login($username,$password){
$query = $this->db->query("SELECT * FROM `login` WHERE `username`= '".$username."' AND
password='".$password."' LIMIT 1");
if ($query->num_rows() > 0)
return TRUE;
else
return FALSE;
}

A user is able to login into my site despite not having existed as a user in my membership table - why is this?

If a user does not exist its supposed to throw back an error on the login screen but the user is then brought to the home page as if they have previously registered in my sign controller. The login controller - validate credentials function - and my model - function can_log_in() - will illustrate the error its supposed to bounce back
model:
class Membership extends CI_Model
{
function Membership()
{
parent::__construct();
}
public function can_log_in()
{
$this->db->select('*')->from('membership');
$this->db->where('username', $this->input->post ('username'));
$this->db->where('password', md5($this->input->post ('password')));
$query = $this->db->get('membership');
if ($query->num_rows() == 1)
{
return true;
}
else{
return false;
}
}
login controller:
class Login extends CI_Controller
{
function Login()
{
parent::__construct();
$this->load->model('membership');
}
function loguserin()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|trim');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->form_validation->run()==TRUE)
{
$this->load->model('membership');
if($this->membership->can_log_in($this->input->post('username'),$this->input->post('password'))
{ // this is unepected despite a new if statement called
$this->session->set_userdata('status', 'OK');
$this->session->set_userdata('username', $username);
redirect('home');
} else //this else is unexpected
{
$this->session->set_userdata('status', 'NOT_OK');
$this->session->set_flashdata('Incorrect username/password');
$this->index();
}
} else {
$this->index;
}
}
function logout()
{
$this->session->sess_destroy();
redirect ('start');
}
function index()
{
$this->load->view('shared/header');
$this->load->view('account/logintitle');
$this->load->view('account/loginview');
$this->load->view('shared/footer');
}
}
Once again thanks :) its just that the user if not already in the table should not be able to sign into the home page
Your logic is all over the place and you're misunderstanding the concept of form validation. Form validation validates form input that's it, it does not validate credentials. The validate_credentials function you have is sort of pointless to be honest since you can't call the form validation error from outside the run function. So you may as well just make that go away entirely.
First, the initial call after form_validation should be like this:
if ($this->form_validation->run()==TRUE)
{
$this->load->model('membership');
if($this->membership->can_log_in($this->input->post('username'),$this->input->post('password')))
{
$this->session->set_userdata('status', 'OK');
$this->session->set_userdata('username', $username);
redirect('home');
} else {
$this->session->set_userdata('status', 'NOT_OK');// you'll need to do something
// here to tell them their credentials are wrong as I said this won't work through
// the form validation, perhaps look into using $this->session->set_flashdata()
$this->index();
}
} else {
$this->index; //reload the index to display the validation errors
Okay that takes care of sending the data to the login function, now the function actually needs to receive data, and since it is NOT the first page sent the data the post string will be empty, that is why I passed the data in the function above. The only part of the model that should need to change is the following:
public function can_log_in($username,$password)
{
$this->db->select('*')->from('membership');
$this->db->where('username', $username);
$this->db->where('password', md5($password));
try replacing
if ($this->form_validation->run())
with
if ($this->form_validation->run() && validate_credentials())

codeigniter set_rules allow more characters

I am building a registration system and i have come to a problem.
I want to allow dots(.) into my username but i cant find a way to do this...
This is just an example which i may want to use in order features of my app as well.
This is what i got so far:
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
Thanks
You'll have to create your own custom function in your controller:
class Form extends CI_Controller
{
function index()
{
$this->load->library('form_validation');
// 'callback_valid_username' will call your controller method `valid_username`
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_valid_username|min_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
// Validation failed
}
else
{
// Validation passed
}
}
function valid_username($str)
{
if ( ! preg_match('/^[a-zA-Z0-9.]*$/', $str) )
{
// Set the error message:
$this->form_validation->set_message('valid_username', 'The %s field should contain only letters, numbers or periods');
return FALSE;
}
else
{
return TRUE;
}
}
}
For more information on custom validation function, read the docs:
http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

Categories