How to compare value from table in call back function in codeigniter form validaiton - codeigniter

This is my Callback function for form validation in CodeIgniter
public function user_check($str)
{
if ($str == 'sounitkar13')
{
return TRUE;
}
else
{
$this->form_validation->set_message('user_check', 'The %s is not found in our record');
return FALSE;
}
}
right now i am comparing $str with "sounitkar13" but i have a table with 100 username stored so i want to compare with those 100 user names and if it matches with any of those 100 then return TRUE otherwise FALSE. ( it is reverse of is_unique function.

you have to do condition on table rows using where condition
$query = $this->db->get_where('table', array(
'username' => $str
));
$count = $query->num_rows();
if ($Count != 0)
{
return TRUE;
}
else
{
$this->form_validation->set_message('user_check', 'The %s is not found in our record');
return FALSE;
}

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.

Can't save empty string into field value

I need to change value of NULL-field to empty string (in sales_flat_order table).
I tried this code:
$orders = Mage::getModel('sales/order')->getCollection()
->addAttributeToFilter('created_at', array('to' => $endDate))
->addAttributeToFilter('status', array('eq' => Mage_Sales_Model_Order::STATE_COMPLETE));
foreach ($orders as $order) {
$comment = $order->getCustomerNote();
if (is_null($comment)) {
$order->setData('customer_note', '');
try {
$order->save();
} catch (Exception $e){
echo $e->getMessage(); exit;
}
}
}
But in base I see still NULL value in this filed.
If I change empty string to any non-empty it works fine.
How can I update NULL value field to empty string?
Thanks.
The empty string is set to null in Varien_Db_Adapter_Pdo_Mysql::prepareColumnValue():
case 'varchar':
case 'mediumtext':
case 'text':
case 'longtext':
$value = (string)$value;
if ($column['NULLABLE'] && $value == '') {
$value = null;
}
break;
To reset the column value to empty string, add this in your resource model:
protected function _prepareDataForSave(Mage_Core_Model_Abstract $object)
{
$data = parent::_prepareDataForSave($object);
if ($object->getData('your_column_name') === '') {
$data['your_column_name'] = '';
}
return $data;
}
I tried and it's normal.
$order->setData('customer_note', new Zend_Db_Expr(''));
try {
$order->save();
} catch (Exception $e){
echo $e->getMessage(); exit;
}

Codeigniter logical operator

I ask the question before I was not getting anymore replies and I decide to re-post it if that will help. I hope i'm not doing anything wrong by re-posting?
$total_cost_for_A = $this->admin_model->total_cost_for_A($branch, $department, $date);
$total_cost_for_B = $this->admin_model->total_cost_for_B($branch, $department, $date);
The variables $total_cost_for_A and $total_cost_for_B hold the returned value from a mysql summation queries in the model. The queries return false if no record was found. Now, I'm trying to perform this operation.
if(($total_cost_for_A === FALSE) && ($total_cost_for_B === FALSE))
{
$data['no_record'] = 'No Record Found!';
$this->load->view('admin/bookings', $data);
}
else
{
$this->load->view('admin/summary', $data);
}
This test always fail and execute the else statement instead, which is not what. Any assistance will be appreciated. Thanks
Here are the functions
function total_cost_for_A($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE bk.date = "'.$date.'"';
}
$result = $this->db->query($select_amount_paid);
if($result->num_rows() > 0)
{
return $result;
}
else
{
return FALSE;
}
}
function total_cost_for_B($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$total_LF_amount = 'SELECT SUM(total_amount) total_amount FROM large_format_print
WHERE date = "'.$date.'"';
}
$result = $this->db->query($total_LF_amount);
if($result->num_rows() > 0)
{
return $result;
}
else
{
return FALSE;
}
}
Try to change like this
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE date = '.$date;//i assume that date is an colum from graphics_booking
you are wrong with "bk.date" you can give directly if it is in your table with where condition and also try to avoid the same name for the function in the model and the varaible assigned.Try to change as different.otherwise your code looks good
No when u return u cannot return the entire , you need to return a row
so you need to do in your model as :
function total_cost_for_A($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE bk.date = "'.$date.'"';
}
$result = $this->db->query($select_amount_paid);
if($result->num_rows() > 0)
{
return $result->row(); // you missed out here
}
else
{
return FALSE;
}
}
Same for the total_cost_for_B()

custom form validation going wrong in codeigniter

My custom function is not working. I am checking if passed value does not exist in the database it return error message. What I am doing wrong?
Controller function
function sp_exists($str)
{
$this->user_model->sp_exists($str);
$this->form_validation->set_message('sp_exists', 'The %s field does not exists');
}
Model function
function sp_exists($str)
{
$this->db->where('member_id',$str);
$query = $this->db->get('user');
if ($query->num_rows() > 0)
{
return false;
}
else
{
return true;
}
}
callback function
$this->form_validation->set_rules('sponsor_id', 'Sponsor ID', 'trim|required|xss_clean|callback_sp_exists');
Did you look at the user guide? It explains clearly how to do this.
First of all I think you should change the model function to this:
function sp_exists($str)
{
$this->db->where('member_id',$str);
$query = $this->db->get('user');
return $query->num_rows() > 0;
}
And the controller should look like this:
function sp_exists($str)
{
if(!$this->user_model->sp_exists($str))
{
$this->form_validation->set_message('sp_exists', 'The %s field does not exists');
return FALSE;
}
else
{
return TRUE;
}
}
change
function sp_exists($str)
{
$this->user_model->sp_exists($str);
$this->form_validation->set_message('sp_exists', 'The %s field does not exists');
}
to
function sp_exists($str)
{
$this->form_validation->set_message('sp_exists', 'The %s field does not exists');
return $this->user_model->sp_exists($str);
}

Codeigniter - form validation check for default value in <input>

I have default values set on form inputs and the form submits because the onlt rule I need to apply in this case is trim|required. How can I check if the submitted value is equal to the default and display an error?
Thanks
Did you try doing it this way...
In your controller....
function index() {
$this->load->helper(array('form', 'url'));
$this->load->library('validation');
$rules['sometext'] = "trim|required|callback_sometext_check";
$this->validation->set_rules($rules);
if ($this->validation->run() == FALSE) {
$this->load->view('myform');
} else {
$this->load->view('formsuccess');
}
}
function sometext_check($str) {
if ($str == "default") {
$this->validation->set_message('sometext_check', 'The %s field should be "default"');
return FALSE;
} else {
return TRUE;
}
}
More over here

Resources