validate combo box in CodeIgniter - validation

I am using CodeIgniter 3 where i am trying to validate my two combo boxes.
My code is like this:
view:
<tr>
<td >
<?php $extra=' class="selectCombo"';
$busVal=array();
$busVal[]="Select";
foreach($values as $val){
$busVal[$val->bus_id]=$val->bus_no;
}
echo form_dropdown('bus_id', $busVal,set_value('bus_id'),$extra);
?>
</td>
<td><?php echo form_error('bus_id');?></td>
</tr>
<tr>
<td >
<?php
$extra=' class="selectCombo"';
$route=array();
$route[]="Select";
foreach($values as $val){
$route[$val->route_id]=$val->route_name;
}
echo form_dropdown('route_id',$route,set_value('route_id'),$extra);
?>
</td>
<td><?php echo form_error('route_id');?></td>
</tr>
My controller code is like this:
public function add()
{
$this->form_validation->set_rules('bus_id', 'Bus', 'trim|required|callback_check_Bus');
$this->form_validation->set_rules('route_id', 'Route Name', 'trim|required|callback_validate_route');
if ($this->form_validation->run() == FALSE) {
echo 'Error';
}else{
}
}
public function check_Bus($val){
if($val ==0)
{
$this->form_validation->set_message('select_validate', 'Please Select Bus.');
return false;
}
else
{
return true;
}
}
public function validate_route($val){
if($val ==0)
{
$this->form_validation->set_message('select_validate', 'Please Select Route.');
return false;
}
else
{
return true;
}
}
I get following message for both fields:
Unable to access an error message corresponding to your field name Bus.(check_Bus)
Unable to access an error message corresponding to your field name
Route Name.(validate_route)
What should i do?

Use this code working fine.
callback validation rule
callback_fieldname_check
//function name callback_fieldname_check (){
}
// Set message - fieldname_check
see code
public function add()
{
$this->form_validation->set_rules('bus_id', 'Bus', 'trim|required|callback_bus_id_check');
$this->form_validation->set_rules('route_id', 'Route Name', 'trim|required|callback_route_id_check');
if ($this->form_validation->run() == FALSE) {
$this->load->view('load_your_view');
}else{
echo "Added";
}
}
public function bus_id_check($val){
if($val ==0)
{
$this->form_validation->set_message('bus_id_check', 'Please Select Bus.');
return false;
}
else
{
return true;
}
}
public function route_id_check($val){
if($val ==0)
{
$this->form_validation->set_message('route_id_check', 'Please Select Route.');
return false;
}
else
{
return true;
}
}

Related

How do we pass user defined variable in controller to blade in Laravel

This is working perfectly but I want the return statement be in <p> tag on the view
LARAVEL 8.x
$product = Product::find($id);
if(!$product) {
abort(419);
}
$value = $request->session()->get('id');
if ($value == $id) {
return "You can purchase an item at a time!";
} else {
$initial = $product->quantity;
if ($initial > 0) {
$final = $initial - 1;
$product->quantity = $final;
$product->save();
$request->session()->put('id', $id);
var_dump($value);
var_dump($product->quantity);
} else {
return "out of stock";
}
}
return redirect()->action([ProductController::class, 'index']);
I have tried how to do that. Though I could use #if on blade for the $product->quantity to display the "out of stock" but "you can only purchase an item at a time".
Here's how you would do it
THE CONTROLLER YOU PROVIDED
$product = Product::find($id);
if(!$product) {
abort(419);
}
$value = $request->session()->get('id');
if ($value == $id) {
return "You can purchase an item at a time!";
} else {
$initial = $product->quantity;
if ($initial > 0) {
$final = $initial - 1;
$product->quantity = $final;
$product->save();
$request->session()->put('id', $id);
var_dump($value);
var_dump($product->quantity);
} else {
return "out of stock";
}
}
return redirect()->route('products.index')->with(['product' => $product]);
In your web route file you shoud have like this.
Route::get('/products', [ProductController::class, 'index'])->name('product.index');
Then in you blade component you can
<h1> {{ $product->id ?? 'No Product ID given' }} </h1>

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.

Codeigniter radio buttons callback validation error?

I want to display error message if no gender is selected using Codeigniter callback validation error...
My HTML Page
<label class="control-label labeller" for="gender">Gender</label>
<input type="radio" id="gender" name="gender" value="Male">Male
<input type="radio" id="gender" name="gender" value="Female">Female
My Controller
$this->form_validation->set_rules('gender', 'Gender', 'callback_gender');
public function gender($str)
{
if ($str == '')
{
$this->form_validation->set_message( 'gender', 'Please Choose gender' );
return FALSE;
}
else
{
return TRUE;
}
}
I tried a lot of times... Please help....
Try using $this->input->post('gender') instead of $str
<?php
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$this->form_validation->set_rules('gender', 'Gender', 'callback_gender');
if ($this->form_validation->run() == FALSE) {
// Load view
} else {
// Success Stuff
}
}
public function gender() {
if ($this->input->post('gender')) {
return TRUE;
} else {
$this->form_validation->set_message( 'gender', 'Please Choose gender' );
return FALSE;
}
}
}
Or on callback $this->form_validation->set_rules('gender', 'Gender',
'callback_gender[gender]');
<?php
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$this->form_validation->set_rules('gender', 'Gender', 'callback_gender[gender]');
if ($this->form_validation->run() == FALSE) {
// Load view
} else {
// Success Stuff
}
}
public function gender($str) {
if ($str == '') {
$this->form_validation->set_message( 'gender', 'Please Choose gender' );
return FALSE;
} else {
return TRUE;
}
}
}

How can i display error messages in CodeIgniter

Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$this->year_model->insert($_POST);
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
Model:
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
}
View:
<div class="text-danger">
//display error message
</div>
MY Question: How can i display model error message in view............................................................
use below updated code for your solution
Model :
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
return TRUE;
}
add_year
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$ret = $this->year_model->insert($_POST);
if(!$ret){
$this->session->set_flashdata('error_view',$ret);
}
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
in view
<?php
echo $this->session->flashdata('error_view');
?>
Use this Code
Note : please set your table and field name in is_unique function !
Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id))
{
$this->form_validation->set_rules('year_name', 'Year Name', 'required|is_unique[table_name.field_name]');
if ($this->form_validation->run() == FALSE) {
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else {
if( $this->year_model->insert($_POST)==true)
{
redirect('admin/Year');
}
}
} else
{
redirect('admin/Login');
}
}
Model
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
return true;
} else {
return false;
}
}
View File
<div class="panel-body">
<?php if(validation_errors()) { ?>
<div class="alert alert-danger"><?php echo validation_errors(); ?></div>
<?php } ?>

I want to retrieve the values from the db using codeigniter

In the view it is getting the error like undefined variable categorylist,can u
pls help me !!!!!!!
Controller
public function categorylist()
{
$data['categorylist']=$this->userprocessmodel->categorylist();
$this->load->view('user/home',$data);
}
Model
public function categorylist()
{
$query=$this->db->get('category');
echo $query->num_rows();
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
view
<?php
if($categorylist)
{
foreach($categorylist as $categorylist)
{
$categorylist->categoryname;
}
}
?>
Just change these code in model
public function categorylist()
{
$query=$this->db->get('category');
echo $query->num_rows();
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return 0;
}
}
Now in controller if 0 get then
public function categorylist()
{
$data['categorylist']=$this->userprocessmodel->categorylist();
if($data['categorylist']=='0')
{
$datanone['categorylist']='None';
$this->load->view('user/home',$datanone);
}
else{
$this->load->view('user/home',$data);
}
}
Your view should be like this
<?php
if(count($categorylist)>0)
{
foreach($categorylist as $categorylist)
{
$categorylist->categoryname;
}
}else{
echo 'No category found';
}
?>
Also you dont need to echo $query->num_rows()
In your model, you must change:
return null;
With:
return false;
If you assign null to variable $categorylist, the variable is not initialized, and you get that error in your view, if you assing false instead, the variable is initialized with the boolean value false.

Resources