Codeigniter - Dependent Select Box with database - php

i'm just wanna ask again about codeigniter.
I want to make dependent select form in codeigniter with sql server database.
I have an database table name MS_UPB (it contains a location) and MS_RUANG (it contains a room in that location). My task is to show the room where the MS_RUANG.kd_lokasi (this is the room location ID) = MS_UP.kd_lokasi (this is the location ID) and show it in the dependent select box codeigniter
My Views:
<?php
echo form_open('admin/laporan/tampildbr',$att)
?>
<div class="control-group">
<label class="control-label" for="inputEmail">Unit Kerja</label>
<div class="controls">
<select name="unit" id="unit">
<?php
foreach ($isdata as $row) {
echo "<option value='".$row->KDUPB."|".$row->NAMAUPB."'>".$row->NAMAUPB."</option>";
}
?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Ruangan</label>
<div class="controls">
<select name="ruangan" id="ruangan" id="ruangan_label">
<option value=""></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Jenis</label>
<div class="controls">
<input type="radio" name="jenis" value="DAFTAR BARANG RUANGAN" />Daftar Barang ruangan
</div>
<div class="controls">
<input type="radio" name="jenis" value="REKAP DBR" />Rekap DBR
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success" name="submit" formtarget="_blank">Kirim</button>
</div>
</div>
</form>
<p> </p>
<p> </p>
<?php form_close();?>
<script type="text/javascript">
$('#ruangan,#ruangan_label').hide();
$('#unit').change(function(){
var unit_id = $('#unit').val();
if (unit_id != ""){
var post_url = "admin/laporan/getruangan" + unit_id;
$.ajax({
type: "POST",
url: post_url,
success: function(ruangan) //what's this ruangan mean?
{
$('#ruangan').empty();
$('#ruangan, #ruangan_label').show();
$.each(ruangan,function(kd_ruang,ruang)
{
var opt = $('<option />');
opt.val(kd_ruang);
opt.text(ruang);
$('#ruangan').append(opt);
});
} //end success
}); //end AJAX
} else {
$('#ruangan').empty();
$('#ruangan, #ruangan_label').hide();
}
});
</script>
My Controller:
function getruangan($unit)
{
$unit=explode('|',$unit);
$unitkerja=$unit[0];
$this->load->model('admin/laporanmodel','',TRUE);
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->laporanmodel->get_ruangan($unitkerja)));
}
My Model:
function get_ruangan($unit)
{
$this->db->select('kd_ruang,namaruang');
$this->db->from('MS_RUANG');
$this->db->where('kd_lokasi, "'.$unit.'"');
$query=$this->db->get();
$ruangan=array();
if($query->result()){
foreach ($query->result() as $ruang) {
$ruangan[$ruang->kd_ruang] = $ruang->kd_ruang;
}
return $ruangan;
} else {
return FALSE;
}
}
please help me, thanks for your help :)

I think you have issue while appending the value to your select box.
I would tell you to do all required stuff in model itself. If you do so, we can reduce execution time of one for loop
Try changing in your model like this.
In Model
if($query->result()){
$option = "<option>Select the value</option>";// this is for default value.
foreach ($query->result() as $ruang) {
$ruangan[$ruang->kd_ruang] = $ruang->kd_ruang;
$option .= "<option value='$ruang->kd_ruang'>{$ruang->kd_ruang}</option>".
}
return $option;
} else {
return FALSE;
}
In model only we are generating required html for our view.
In Controller
//header('Content-Type: application/x-json; charset=utf-8');// comment this line
echo ($this->laporanmodel->get_ruangan($unitkerja));
I have removed json part in controller. We will take plain text here.
In view
Im changing entire success() in ajax,
success: function(ruangan) //what's this ruangan mean?
{
$('#ruangan').append(ruangan);// just append the value coming from ajax call here.
}
We have reduced execution time of one loop.
Hope it helps.

Related

How to implode textarea value while using dynamic add and remove in ci?

this is my controller:
public function detail()
{
if($this->input->post('submit'))
{
$a = $this->input->post('tutorial_overview');
$tutorial_overview = implode(",",(array) $a);
$data = array(
'tutorial_overview' => $tutorial_overview
);
print_r($data)
}
}
view: detail.php
<script>
$(document).ready(function(){
$("#btnAdd").click(function() {
$("#add_ck").append('<div class="con"><label class="col-sm-3 control-label no-padding-right" for="form-field-1">Sub Heading Overview</label><div class="col-sm-7"><textarea id="overview" name="overview" class="col-xs-12"></textarea></div>' + '<input type="button" class="btnRemove" value="Remove"/></div>');
});
$('body').on('click','.btnRemove',function() {
$(this).parent('div.con').remove()
});
});
</script>
<div class="form-group" id="add_ck">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1">Sub Heading Overview</label>
<div class="col-sm-7">
<textarea id="overview" name="overview" class="col-xs-12"></textarea>
</div>
<div class="col-sm-2">
<input id="btnAdd" type="button" value="Add" />
</div>
</div>
In this code I have a textarea where I have used add and remove more textarea through jquery. Now the problem is that when I am using implode function to seperate textarea value with comma (,) but now what happen when I click on add button and write something inside the text box and then print value it show me last textarea value implode fuction are not working. So, how can I fix this issue ?
Thank You
Hope this will help You :
Replace textarea name attr name="overview" with this name="overview[]", both in form and js code
And your controller method detail should be like this :
public function detail()
{
if($this->input->post('submit'))
{
$a = $this->input->post('tutorial_overview');
if ( ! empty($a))
{
foreach($a as $key => $item)
{
$data[$key]['tutorial_overview'] = $item;
}
}
print_r($data)
}
}

How to pass default values from codeigniter application to different website

Error
Not able to pass the value from this application to other website.
View
In this view using action i have called the controller function. If the user selects Pay-Me then value 1 will be passed to controller function.
<form id="formMuktinath" method="post" action="<?php echo base_url().'index.php/booking/bookManakamana'?>">
<div class="form-group">
<label for="name" class="col-sm-3 col-lg-offset-2 control-label">Payment From </label>
<div class="col-sm-4">
<select class="select form-control" name="manakamana[payment_from]">
<option value="1" selected>Pay-Me</option>
<option value="2">BIL</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
Controller
If 1 is selected then it calls payme website. Then there redirect function using $data does not pass amt value to payme website.
public function bookManakamana(){
if ($data = $this->input->post('manakamana')) {
$data['created_on'] = date('Y-m-d H:i:s');
if ($data['payment_from'] == '1') {
$data['amt'] = '100';
redirect('http://dev.payme.com/pay/main',$data);
}
if ($data['payment_from'] == '2') {
echo 'bli';
exit;
}
redirect('booking/index');
} else {
$this->load->view('index');
}
}
if you want to pass values in link as get variable
www.somewebsite.com/?var='value'
but if you want to send variable as post you need to use curl

How do I get the data from a view to another view in ionic?

I have followed this tutorial ionic/angular - get data from database - data loaded, but no output on site
on how to retrieve data from database and show it in ionic but the problem is the data can only be seen in one view and I dont know how to view it in another view
screencap - I have successfully display the recipes in my ionic from my database and when I click the pen icon it should be displaying the recipe name, ingredients and more
screencap 2 - but when I click it it doesnt show any data.
here's my code for viewing data :
user_model.php (codeigniter - model )
public function user_recipe_data()
{
$this->db->select('*');
$this->db->from('usersrecipes');
$this->db->join('user', 'user.user_id = usersrecipes.user_id');
$this->db->where('usersrecipes.user_id = 12 ');
$query = $this->db->get();
return $query->result_array();
}
Main.php ( codeigniter - controller )
public function get_user_recipe_data()
{
$postdata = json_decode(file_get_contents("php://input"));
$user_recipe = $this->User_model->user_recipe_data();
echo json_encode($user_recipe);
}
RecipeService.js (ionic)
.factory('getRecipeService', function($http){
return {
all: function() {
return $http.get("http://localhost/admin-recipick/api/Main/get_user_recipe_data");
},
get: function(Recipe_ID) {
q = $http.get("http://localhost/admin-recipick/api/Main/get_user_recipe_data");
for (var i = 0; i < q.length; i++) {
if (q[i].id === parseInt(Recipe_ID)) {
return q[i];
}
}
return null;
}
};
});
controller.js (ionic)
getRecipeService.all().then(function(payload) {
$scope.userrecipedata = payload.data;
console.log(payload);
});
profile.html ( ionic )
<ion-list>
<ion-item ng-repeat="recipe in userrecipedata" class="item-remove-animate item-avatar item-icon-right" type="item-textu-wrap" href="#/app/recipes/{{recipe.Recipe_ID}}">
<img ng-src="img/food/porkmenudo.jpg">
<h2>{{recipe.Recipename}}</h2>
<p>{{recipe.Ingredients}}</p>
<i class="icon ion-edit"></i>
<ion-option-button class="button-assertive" ng-click="remove(recipe)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
recipe-detail.html ( ionic - in this html I want to display the data here also but it shows no data in the input type. What should I do?)
<div class="list">
<label class="item item-input">
<span class="input-label">Index Name</span>
<input type="text" ng-model="recipe.Recipe_ID">
</label>
<label class="item item-input">
<span class="input-label">Recipe Name</span>
<input type="text" ng-model="recipe.Recipename">
</label>
<label class="item item-input">
<span class="input-label">Ingredients</span>
<input type="text" ng-model="recipe.Ingredients">
</label>
<label class="item item-input item-select">
<span class="input-label">Cooking Time</span>
<select ng-model="recipe.Cookingtime">
<option value="20mins">20mins</option>
<option value="30mins">30mins</option>
<option value="1hr">1hr</option>
</select>
</label>
<label class="item item-input">
<textarea placeholder="PROCEDURE" rows="12" ng-model="recipe.Procedure">
</textarea>
</label>
<button class="button button-block button-assertive h1" ng-click="AddRecipe()">Update Recipe</button>
</div>
Use http for controller
.controller('Ctrl', function($scope, $http, $stateParams) {
$scope.userrecipedata = [];
$http.get('http://localhost/admin-recipick/api/Main/get_user_recipe_data').success(function(response){
$scope.userrecipedata = response;
});
})

dropdown select value in yii

I am currently trying to create a sample shopping site,The problem came when I created a search page.In my search page I Have two fields one for enter the keyword and other for select type of item
Which means search,keyword in the selected item.but the item defined in DB is 0 and 1 and i Trying to get it my code but fails...could any one help me...
The Gfunction code is
public static function item(){
$optionList='';
$CategoryList = OfferEvents::model()->findAllByAttributes(array());
foreach($CategoryList as $catdata)
{ $optionList.="<option value='".$catdata['type']."'>".$catdata['name']."</option>"; }
return $optionList;
}
and view code is
<form action="<?php echo Yii::app()->baseUrl; ?>/offer?>" method="GET" class="form-inline form-section-2 row fadeInDown animated">
<div class="col-sm-5 form-group">
<input type="text" name="search" class="form-control" id="search" value="" placeholder="Enter Your Keyword">
</div>
<div class="col-sm-4 form-group">
<select name="cat" class="form-control selectpicker">
<option value='0'>Select type</option>
<?php echo GFunctions::item(); ?>
</select>
</div>
<div class="col-sm-3 form-group">
<button type="submit" class="btn btn-default btn-new">Search</button>
</div>
</form>
why don't you use Yii built in functions to handle the dropdown?
I am not sure how your Models looks like but you can choose one of the following functions to achieve what you want instead of trying to return a String $optionList with HTML tags.
CHtml::activeDropDownList() // for directly bind to active record model
CHtml::dropDownList()
Try this code....
Function
public static function item(){
$CategoryList = OfferEvents::model()->findAllByAttributes(array());
$optionList = CHtml::listData($countries, 'type', 'name')
return $optionList;
}
In view
<?php echo CHtml::dropDownList('cat', '', GFunctions::item(), array('prompt'=>'Select type'));?>

Codeigniter 2 - Callback function in My_Controller

I have all my callback functions in My_Controller so that they are not repeated throughout the website. This works fine but for some reason one of my functions is not working when I am posting information using AJAX but is working on other pages. The message I get back when I use the callback is:
Unable to access an error message corresponding to your field name.
But then I've created a message for it using set_message() and it works fine on the other page without AJAX.
If you were interested in the log, here is the relevant output when entering an invalid date:
ERROR - 2013-05-24 16:03:08 --> -----Valid date format called, 223013-05-15
ERROR - 2013-05-24 16:03:08 --> -----Should be okay = , 223013-05-15
ERROR - 2013-05-24 16:03:08 --> -----Valid date format = false, 223013-05-15
And with a valid date:
ERROR - 2013-05-24 16:06:00 --> -----Valid date format called, 2013-05-24
ERROR - 2013-05-24 16:06:00 --> -----Should be okay = , 2013-05-24
ERROR - 2013-05-24 16:06:00 --> -----Valid date format = true, 05,24,2013
Here is the callback:
class MY_Controller extends CI_Controller
{
var $options;
public function __construct()
{
parent::__construct();
date_default_timezone_set('Europe/London');
$this->options->calendar = FALSE;
}
//Check date format aggainst mysql format, valid dates only, no 30-2-2010.
function _Valid_Date_Format($date)
{
log_message('error', '-----Valid date format called, '.$date);
if( empty($date) )
{
$this->form_validation->set_message('_Valid_Date_Format', 'This date is required.');
return FALSE;
}
else
{
log_message('error', '-----Should be okay = , '.$date);
}
$parsed = explode('-',$date);
if( checkdate($parsed[1],$parsed[2],$parsed[0]) )
{
log_message('error', '-----Valid date format = true, '.$parsed[1].','.$parsed[2].','.$parsed[0]);
return TRUE;
}
log_message('error', '-----Valid date format = false, '.$date );
$this->form_validation->set_message('_Valid_Date_Format', 'The Date entered is invalid.');
return FALSE;
}
}
Here is the AJAX Code:
//Submit time feature
$("#submit_time").click(function()
{
var cct = $.cookie('csrf_simple_cookie');//Overcome ajax limitation with csrf function, see below:
$.ajax({
url: folder,
type:"POST",
context: document.body,
data: {t_id:$('#t_id').val(),
time_for:$('#time_for').val(),
hrs_spent:$('#hrs_spent').val(),
mins_spent:$('#mins_spent').val(),
timer_description:$('#timer_description').val(),
date_worked:$('#date_worked').val(),
csrf_simple_collab:cct},
dataType: "json",
error: function(XMLHttpRequest,error)
{
if(error=='parsererror')//Not logged in.
{
window.location.replace(loginFolder)//redirect to login page
}
},
success: function(data)
{
if(data.success)
{
var message=$('#message-box').html('<span>Time data added successfully.</span>').hide();
message.fadeIn("slow");
javascript:location.reload(true);
}
else
{
if(data.validation)
{
//var message=$('#message-box').html("<span>Database error</span>");
var message=$('#message-box').html(data.error);
}
else
{
var message=$('#message-box').html(data.error);
$('#time-for-error').html(data.time_for);
$('#date-worked-error').html(data.date_worked);
$('#mins-spent-error').html(data.mins_spent);
$('#hrs-spent-error').html(data.hrs_spent);
$('#timer-description-error').html(data.timer_description);
}
}
}
});
return false;
});
Here is the view:
<?
//If we are an admin we can alter the user the information is added for.
if($this->session->userdata('userType')=='admin'): ?>
<div class="form_row">
<div class="form_field">
<label for="time_for">User:</label>
</div>
<div class="form_field name_element" id="time-for-container">
<select name="time_for" id="time_for">
<?
foreach($users as $key => $u):
if($u->userId==$this->session->userdata('userId')):
?>
<option selected="selected" value="<?=$u->userId?>"><?=$u->userName?></option> <?='\n'?>
<?
else:
?>
<option value="<?=$u->userId?>"><?=$u->userName?></option> <?='\n'?>
<?
endif;
endforeach;
?>
</select>
<p id="time-for-error"></p>
</div>
</div>
<? else: ?>
<input type="hidden" id="time_for" name="time_for" value="<?=$this->session->userdata('userId')?>">
<? endif; ?>
<div class="form_row">
<div class="form_field">
<label for="hrs_spent">Hours and minutes spent:</label>
</div>
<div class="form_field name_element" id="mins-spent-container">
<input type="text" maxlength="6" name="hrs_spent" id="hrs_spent" value="" />
<span id="min-separator">:</span>
<input type="text" maxlength="6" name="mins_spent" id="mins_spent" value="" />
<p id="mins-spent-error"></p>
<p id="hrs-spent-error"></p>
</div>
</div>
<div class="form_row">
<div class="form_field">
<label for="date_worked">Date Worked:</label>
</div>
<div class="form_field name_element" id="date-picker-container">
<input type="text" name="date_worked" id="date_worked" />
<p id="date-worked-error"></p>
</div>
</div>
<div class="form_row">
<div class="form_field">
<label for="timer_description">Description:</label>
</div>
<div class="form_field name_element" id="description-container">
<textarea name="timer_description" id="timer_description" value=""></textarea>
<p id="timer-description-error"></p>
</div>
</div>
<input type="hidden" id="c_id" name="c_id" value="<?=$task->c_id ?>" />
<input type="hidden" id="p_id" name="p_id" value="<?=$task->p_id ?>" />
<input type="hidden" id="t_id" name="t_id" value="<?=$task->t_id ?>" />
<input type="hidden" name="login-folder" id="login-folder" value="<?=base_url()?>login" />
<input type="hidden" name="submit-folder" id="submit-folder" value="<?=base_url()?>times/submit_time" />
<div class="form_row">
<div id="message-box"></div>
<input type="button" name="submit" id="submit_time" class="button-styles button-three" value="Add time" />
</div>
</div>
Controller method:
class Times extends MY_Controller
{
var $options;
//Ajax function used to submit the time information from task page form.
function submit_time()
{
$options=array();
$this->form_validation->set_rules("time_for","Time for","trim|required|is_natural_no_zero");
$this->form_validation->set_rules("hrs_spent","Hrs spent","trim|required|is_natural|min_length[1]|max_length[5]");
$this->form_validation->set_rules("mins_spent","Mins spent","trim|required|is_natural|min_length[1]|max_length[2]|less_than[60]");
$this->form_validation->set_rules("timer_description","Description","trim|min_length[5]|max_length[1000]");
$this->form_validation->set_rules("date_worked","Date Worked","trim|required|callback__valid_date_format");
//$json->data=array('success'=>0,'validation'=>1,'error'=> validation_errors() );
//$this->load->view('data/json_encode',$json);
if($this->form_validation->run())
{
$options['hrs_spent'] = $this->input->post('hrs_spent');
$options['mins_spent'] = $this->input->post('mins_spent');
$options['timer_description'] = $this->input->post('timer_description');
$options['date_worked'] = $this->input->post('date_worked');
$options['t_id'] = $this->input->post('t_id');
$options['u_id'] = $this->input->post('time_for');//Notice time for field here.
$add = $this->time_model->add_time($options);
if(!$add):
$json->data=array('success'=>0,'validation'=>1,'error'=>'Database error');
else:
$json->data=array('success'=>1,'validation'=>1);
$this->log_model->add_log_entry( array('log_id'=>1,'item'=>'Time record "'.reduce_string($options['timer_description'],50).'" was added for user '.$options['u_id'].'.') );
endif;
$this->load->view('data/json_encode',$json);
}
else
{
$json->data = array(
'time_for' => form_error('time_for'),
'hrs_spent' => form_error('hrs_spent'),
'mins_spent' => form_error('mins_spent'),
'timer_description' => form_error('timer_description'),
'date_worked' => form_error('date_worked'),
'success'=>0,
'validation'=>0,
'error'=>'There are errors in the form.'
);
$this->load->view('data/json_encode',$json);
}
}
}
The problem is the capitalization used in the callback method name. The method name, and all subsequent references to it as a validation rule, should be all lowercase.
To explain, this is the relevant part of the Form Validation library that causes the message:
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
All of your set_message() calls name the rule as _Valid_Date_Format, which is the array key that exists in $this->_error_messages.
Because your rule is defined as _valid_date_format, and because PHP is case-sensitive most of the time, the isset() rule fails, and you clearly don't have a language line defined for it, so it goes to the default.
In general, using capitalization in your controller methods will cause problems. So it's best to avoid doing so.

Categories