I have difficulty with populating dropdown
This is the add.php view
<?php
echo form_open('',$attributes);?>
<table cellpadding="0" cellspacing="0" class="user_table biz_table">
<tr>
<th>City:</th>
<td>
<select id="city_id" name="city_id">
<?php foreach($cities as $c){ ?>
<option value="<?php echo $c->id; ?>" <?php if ($biz['city_id']===$c->id){
>selected="selected"<?php }?> ><?php echo $c->name?></option>
<?php }?>
</select>
<tr>
<th>Neighborhood:</th>
<td>
<select id="district_id" name="district_id">
<option value=""></option>
<?php foreach($districts as $d){ ?>
<option value="<?php echo $d->id; ?>" <?php if($biz['district_id']===$d->id){?
>selected<?php }?>><?php echo $d->name?></option>
<?php }?>
</select>
<span style="color: red;"><?php echo form_error('district_id'); ?></span>
</td>
</tr>
This is the javasript. I believe it was used to refresh the page!!!!!
<script type="text/javascript">
var cities = [];
<?php foreach($cities as $city):?>
cities[<?php echo $city->id ?>] = '<?php echo $city->name?>';
<?php endforeach;?>
$(function(){
$('#city_id').change(function(){
city_id=$('#city_id').val();
Utils.loadAction('#district_id','/biz/get_children/'+city_id+'/city');
});
$('#catid_1').change(function(){
catid_1=parseInt($('#catid_1').val());
Utils.loadAction('#subcat','/biz/get_children/'+catid_1+'/category');
});
<?php if(isset($biz['rating']) && $biz['rating']>0):?>
var biz_rating=parseInt('<?php $biz['rating']?>');
if(biz_rating>0)
{
$('#rating').val(biz_rating);
$('.star-'+biz_rating).addClass('active-star');
$(".rating-hint").html($(".star-"+biz_rating).attr("title"));
}
<?php endif;?>
});
This is a controller biz.php
Class Biz extends CI_controller
{
function __construct()
{
parent::__construct();
}
public function add()
{
if(!$this->tank_auth->is_logged_in())
{
redirect('/ucp/login/');
}
$this->load->helper('form');
$biz=$this->get_form_data();
$with_review=1;
if(!empty($_POST)&&!isset($_POST['with_review']))
{
$with_review=0;
}
//validating
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('','');
$this->form_validation->set_rules('city_id', 'City',
'trim|required|intval|max_length[20]|callback_city_check');
$this->form_validation->set_rules('district_id', 'District',
'trim|intval|max_length[20]|callback_city_check');
if($this->form_validation->run())
{
//get validated data
$biz=$this->get_form_data();
}
//save business
$this->load->model('bizs');
$bizid = $this->bizs->add($biz);
redirect('/biz/'.$bizid);
}
//get cities
$this->load->model('catsAndCities','cc');
$this->cc->set_table_name('city');
$data['cities'] = $this->cc->get_top();
if(!$biz['city_id'])
{
//$city=$data['cities'][0];
$biz['city_id'] = 0;
if($this->tank_auth->get_user_city())
$biz['city_id']=$this->tank_auth->get_user_city()->id;
}
$data['districts']=$this->cc->get_children($biz['city_id']);
//$data['districts']=$this->cc->get_children($biz['city_id']);
//$data['districts']=$this->cc->get_children();
$data['biz']=$biz;
$data['heading']="Add A Business";
$this->load->view('biz/add',$data);
}
get_form_data() inside controller biz.php
private function get_form_data()
{
$biz=array(
'city_id'=>$this->input->post("city_id"),
'district_id'=>$this->input->post("district_id")
);
return $biz;
}
get User city in libraries/tank_auth.php
function get_user_city()
{
$this->ci->load->model('catsAndCities','cc');
$this->ci->cc->set_table_name('city');
$this->ci->load->helper('cookie');
if($cookie_v = get_cookie($this->ci->config-
>item('default_city_cookie_name'),TRUE))
{
if($city = $this->ci->cc->get($cookie_v,'slug'))
{
if($city->parent_id == 0)
{
$this->city = $city;
return $city;
}
}
}
$city = array_shift($this->ci->cc->get_top());
$this->city = $city;
return $city;
}
These two are in model catsandcities.php
public function get_all()
{
$data=array();
$this->db->order_by('parent_id','asc');
$this->db->order_by('`order`','asc');
$query=$this->db->get($this->table_name);
foreach($query->result() as $row)
{
$data[$row->id]=$row;
}
return $data;
}
public function get_children($parent_id)
{
$children=array();
if($items=$this->get_all())
{
foreach($items as $i)
{
if($i->parent_id === $parent_id)
{
$children[]=$i;
}
}
}
return $children;
}
the files are located here https://github.com/leungxd/upble
Thanks
I don't fully understand your question but looking at the code I see a lot of hassle to do a simple task. My advice:
Use the form helper to generate the dropdowns
Simplify the way you access your data and delegate the controller to only retrieve such data
Put as little as you can in the views, don't do any logic there
1 - use the form helper
<?= form_dropdown('city_id', $cities, 'default') ?>
This will generate the select and options html code for you. Just make sure it is inside the form_open() function.
2 - Simplify the way to access data...
Take for example your method:
public function get_children($parent_id)
{
$children=array();
if($items=$this->get_all())
{
foreach($items as $i)
{
if($i->parent_id === $parent_id)
{
$children[]=$i;
}
}
}
return $children;
}
Instead of loading all the records from your table, filter by the parent on a query level:
public function get_children($parent_id)
{
$this->db->where('id_parent', $parent_id);
$query = $this->db->get($this->table_name);
$result = $query->result();
return $result;
}
3 - Don't put logic on the views
I would suggest to create a method in your controller where you return a json encoded object and then call it by an ajax request with jquery and then populate the children dropdown:
public function get_children($parent_id)
{
$this->db->where('id_parent', $parent_id);
$query = $this->db->get($this->table_name);
$result = $query->result();
if(empty($result) == FALSE) {
return json_encode($result);
}
return NULL;
}
So whenever you call yoururl/controller/get_children and pass the parent id by a post you'll get the children for that city in a json encoded way that you can get with jquery to manipulate data client-side, instead of having thousands of records bloating up your html.
Read the guidelines of stackoverflow or you won't get much help, and try to be clear on what problem you are trying to solve. Good luck!
I just added a subdomain, and it solved the problem.
thanks
Related
I have a controller it take multiple model function results and pass it to controller I did it like this
adpreview_ctrl.php
public function showBusinessReviews($vehicleid){
$data=array();
$data['details']=$this->ads_model->getBusinessReviews($vehicleid);
$data['noOfReviews']=$this->ads_model->countReviews($vehicleid);
$this->load->view('pages/templates/header');
$this->load->view('pages/viewReviews',$data);
$this->load->view('pages/templates/footer');
}
public function countBusinessReviews($vehicleid){
$data['details']=$this->ads_model->countReviews($vehicleid);
$this->load->view('pages/templates/header');
$this->load->view('pages/viewReviews',$data);
$this->load->view('pages/templates/footer');
}
}
viewReviews.php
<?php
foreach($noOfReviews as $reviewAmount){
echo $reviewAmount.'Reviews';
}
foreach($details as $review){
$Breview=$review->rating;
if($details==null)
{?>
<?php echo '<center><b><h3>No any reviews has been posted yet!</h3></b></center>';?>
<input type="submit" name="ok" class="btn btn-primary btn-lg" value="ok">
<?php }
else{
?>
Ads_model.php
public function getBusinessReviews($Vehicleid){
$status="Approved";
$this->db->select("*");
$query=$this->db->where('Vehicleid',$Vehicleid);
$query=$this->db->where('Status',$status);
$query=$this->db->get('businessreviews');
return $query->result();
}
public function countReviews($Vehicleid){
$status="Approved";
$this->db->select("*");
$query=$this->db->where('Vehicleid',$Vehicleid);
$query=$this->db->where('Status',$status);
$query=$this->db->get('businessreviews');
return $query->num_rows();
}
what I need to know is, it gives error saying it cannot identify $noOfReviews.
foreach($noOfReviews as $reviewAmount){
echo $reviewAmount.'Reviews';
}
I need to know how to retrieve multiple model function data in view,
and $noOfReviews only gives the no of reviews, a user has given. So their, without using a foreach loop how can i get the value of that, using a foreach loop is not necessary here.
Try this:
model:
public function countReviews($Vehicleid) {
$status = "Approved";
$this->db->select("*");
$query = $this->db->where('Vehicleid', $Vehicleid);
$query = $this->db->where('Status', $status);
// it will return with only the number of data
return $query->count_all_results('businessreviews');
}
viewReviews.php
<?php
// show number of reviews
echo $noOfReviews . 'Reviews';
// show details if exists
if(!empty($details)) {
foreach($details as $review) {
// echo what you want
}
} else {
echo 'No details.';
}
?>
I'm not good in codeigniter i'm still learning this. So i need your help guys.
I want to get the data from the database that the id is equal to the value of the dropdown list button.so heres is my code.
This is my controller: controller.php
function getdataload(){
$this->load->view('data',$data);
}
I really don't know what to put in the controller.
This is my view: view.php
<html>
<body>
<label for="member">Member</label>
<select class="form-control" id="member" name="member" required onchange="showCustomer(this.value)">
<option selected="" value="">--select--</option>
<?php foreach ($members as $row): ?>
<option value="<?php echo $row->mem_id; ?>"><?php echo ucwords($row->mem_fname.' '.$row->mem_lname) ?></option>
<?php endforeach ?>
</select>
</body>
</html>
<script>
$('#member').on('change',function(){
$.post('<?php echo base_url("transactions/getdataload")?>',
{
mem_id:$(this).val()
}).done(function(res)
{
$('#select_member').text(res);
});
});
</script>
This is the other view that the called from the controller data.php
<?php
$q = intval($_GET['member']);
$con = mysqli_connect('localhost','root','','global89_point');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"global89_point");
$sql="SELECT * FROM loading_service WHERE member='".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>";
echo "<tr>";
echo " <th>";
echo "Member ID";
echo "</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['member'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
please help me with this guys.
You should call database lib from controller if you do not use models and database logic write to controller see this:
public function result()
{
$this->load->library('database')
$data = array();
$service_list = $this->db->query("SELECT * FROM loading_service WHERE member='".$q."'")->result_array();
$data['service'] = $service_list;
$this->load->view('result', $data);
}
Here result view you get $service array and you can easily iterate this.
Our model in CodeIgniter will be placed in application/models/form_model.php
<?php
class Form_model extends Model {
function Formmodel() {
// load the parent constructor
parent::Model();
}
function submit_posted_data() {
// db is initialized in the controller, to interact with the database.
$this->db->insert('loading_service ',$_POST);
}
function get_all_data() {
// again, we use the db to get the data from table ‘form’
$data['result']=$this->db->get('loading_service');
return $data['result'];
}
}
?>
controller
ss Form extends Controller {
function Form(){
// load Controller constructor
parent::Controller();
// load the model we will be using
$this->load->model('form_model');
// load the database and connect to MySQL
$this->load->database();
// load the needed helpers
$this->load->helper(array('loading_service','url'));
}
//Display the posted entries
function index() {
$data['member']='Form Data';
//use the model to get all entries
$data['result'] = $this->form_model->get_all_data();
// load 'forms_view' view
$this->load->view('forms_view',$data);
}
//Process the posted loading_service
function submit() {
//use the model to submit the posted data
$this->form_model->submit_posted_data();
redirect('loading_service');
}
}
?>
you can refer this code..It will helpful for u...
Just trying to find out the best way to get my custom error message working. Isset does not seem to work in codeigniter.
And for some reason my inputs are displaying the number '1'
Controller
<?php
class Step_3 extends MX_Controller {
private $error = array();
public function index() {
if(($this->input->server('REQUEST_METHOD') == 'POST') && $this->validate()) {
$data['db_hostname'] = $this->input->post('db_hostname');
}
if ($this->error['db_hostname']) {
$data['error_db_hostname'] = $this->error['db_hostname'];
} else {
$data['error_db_hostname'] = '';
}
if ($this->input->post('db_hostname')) {
$data['db_hostname'] = $this->input->post('db_hostname');
} else {
$data['db_hostname'] = 'localhost';
}
}
private function validate() {
if (!$this->input->post('db_hostname')) {
$this->error['db_hostname'] = 'Hostname required!';
}
}
} // End Of
On View File Sample
<input type="text" name="db_hostname" value="<?php echo $db_hostname; ?>" id="input-db-hostname" class="form-control" size="50"/>
<?php if ($error_db_hostname) { ?>
<div class="text-danger"><?php echo $error_db_hostname; ?></div>
<?php } ?>
Your "validate" function doesn't return anything, so your first if statement will never be true.
Also at the moment the input will automatically have a value of 'localhost'. It may be better to test for an empty string and strip spaces just in case like this:
if ("" == trim($this->input->post('db_hostname')))
I'm stacked on this matter. I have a model that retrieves data from a mysql database
class load_model extends CI_Model{
function __construct(){
parent::__construct();
}
Function loadsuppliers()
{
$this->db->select('SupplierID, Name');
$records=$this->db->get('supplier');
$data=array();
foreach ($records->result() as $row)
{
$data[$row->SupplierID] = $row->Name;
}
return ($data);
}
}
?>
This model submits value to a function in my controller
public function getSupplier()
{
$this->load->model('load_model');
$data['unit'] = $this->load_model->loadsuppliers();
$this->load->view('SupplierMGT', $data);
}
and I want to display the retrieved data to my view as a combo box. I tried to check if I am able to retrieve database values using echo json_encode($data) and it returns {"unit":{"2":"test","3":"Delta"}} ,
Could you help me with this? I tried using
<?php foreach($unit as $result):
print_r($result);
endforeach;?>
to check if i am able to pass the value but i failed.
Small changes in the model:
function loadsuppliers()
{
$this->db->select('SupplierID, Name');
$records=$this->db->get('supplier');
$data=array();
if($records->num_rows() > 0){
$data = $records->result_array();
}
return ($data);
}
In your view SupplierMGT.php write this:
<select name="" id="" multiple="">
<?php
if(isset($unit) && is_array($unit) && count($unit) > 0){
foreach($unit as $key=>$each){
?>
<option value="<?=$each['SupplierID']?>"><?=$each['Name']?></option>
<?php
}
}
?>
</select>
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
Hihow r u all?
I m trying to calculate basic salary with Particular employee_id but when i m trying to .. give me fatal error..
Fatal error: Call to a member function num_rows() on a non-object in D:\wamp\www\template\application\models\salary.php on line 112
my code is: model
<?php
class Salary extends Model
{
/*
Determines if a given person_id is a profile
*/
function exists($salary_id)
{
$this->db->from('salary_scale');
$this->db->where('id',$salary_id);
$this->db->where('deleted',0);
$query = $this->db->get();
return ($query->num_rows()==1);
}
/*
Determines if a given employee_id is a employee
*/
function exists_employee($employee_id)
{
$this->db->from('grade_history');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
return ($query->num_rows()==1);
}
/*
Returns all the suppliers
*/
function get_all()
{
$this->db->from('salary_scale');
$this->db->where('deleted', 0);
$this->db->order_by("name", "asc");
return $this->db->get();
}
/*
*
* Gets information about a particular employees salary
*/
function grade_rules_info($salary_grade)
{
$this->db->from('salary_scale_rules');
$this->db->where('salary_grade',$salary_grade);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('salary_scale_rules');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
/*
*
* Gets information about a particular employees salary
*/
function get_info($employee_id)
{
$this->db->from('allowance');
//$this->db->join('deductions', 'deductions.eid = allowance.eid');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
/**
* Gets information about a particular employees salary
*
**/
function get_grade_info($employee_id)
{
$this->db->from('grade_history');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $employee_id is NOT an employee
$grade_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('grade_history');
foreach ($fields as $field)
{
$grade_obj->$field='';
}
return $grade_obj;
}
}
/**
* Inserts or updates configuration data
*
*/
function save_grade(&$data, $employee_id=false)
{
if (!$employee_id)
{
if($this->db->insert('grade_history', $data))
{
$data['id']=$this->db->insert_id();
return true;
}
return false;
}
$this->db->where('id', $employee_id);
return $this->db->update('grade_history', $data);
}
// ------------------------ End of save_salary_cinfig function -----------------------------
/*
* Basic pay salary calculation
*/
function basic_pay($employee_id)
{
// Get grade information from grade_history table
// Get Particular person grade ifnormation by employ_id
$grade_info = $this->get_grade_info($employee_id);
$salary_grade = $grade_info->salary_grade;
$no_of_increment = $grade_info->number_of_increment;
// Get Grade rules information about particular grade by passing $salary_grade number
$grade_rules = $this->grade_rules_info($salary_grade);
$basic_amount = $grade_rules->basic_amount;
$increment = $grade_rules->increment;
$max_no_of_increment = $grade_rules->number_of_increment;
$max_amount = $grade_rules->max_amount;
return $basic_pay = $basic_amount + $increment*$no_of_increment;
}
}
?>
controller
<?php
require_once ("secure_area.php");
class Salaries extends Secure_area
{
function __construct()
{
parent::__construct('salaries');
}
function index()
{
$data['controller_name']=strtolower($this->uri->segment(1));
$data['form_width']=$this->get_form_width();
$data['manage_table']=get_profile_manage_table($this->Profile->get_all(),$this);
$this->load->view('salaries/manage',$data);
}
/*
Returns profile table data rows. This will be called with AJAX.
*/
function search()
{
$search=$this->input->post('search');
$data_rows=get_profile_manage_table_data_rows($this->Profile->search($search),$this);
echo $data_rows;
}
/*
Gives search suggestions based on what is being searched for
*/
function suggest()
{
$suggestions = $this->Profile->get_search_suggestions($this->input->post('q'),$this->input->post('limit'));
echo implode("\n",$suggestions);
}
/*
Loads the profile form
*/
function view($employee_id=-1)
{
//$data['salary_summary_info'] =$this->Salary->get_info($salary_id);
//$data['salary_deductions_summary_info'] =$this->Salary->get_deductions_info($salary_id);
$employee_id = array('' => '-- Select Employee ID --');
foreach($this->Profile->get_employee_id()->result_array() as $row)
{
$employee_id[$row['employee_id']]= $row['employee_id'];
}
$data['employee_id'] = $employee_id;
// $data['selected_employee_id'] = $this->Profile->get_info($employee_id)->employee_id;
$data['basic_pay'] = $this->Salary->basic_pay($employee_id);
$this->load->view("salaries/salary_summary_form", $data);
}
//--------------------------------------End view function-----------------------------------
/*
Loads the profile form
*/
function grade_view($employee_id=-1)
{
$data['salary_grade_info'] = $this->Salary->get_grade_info($employee_id);
$data['basic_pay'] = $this->Salary->basic_pay($employee_id);
$this->load->view("salaries/grade_view", $data);
}
//--------------------------------------End view function-----------------------------------
/*
Inserts/updates a profile
*/
function save_salary_grade($id=-1)
{
$grade_data = array(
'eid' =>$this->input->post('employee_id'),
'salary_grade' =>$this->input->post('salary_grade'),
'number_of_increment' =>$this->input->post('number_of_increment'),
'comments' =>$this->input->post('comments'),
'date' =>date('Y-m-d H:i:s')
);
if($this->Salary->save_grade($grade_data, $id))
{ //New profile
if($id==-1)
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_adding').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['eid']));
}
else //previous profile
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_updating').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['eid']));
}
}
else//failure
{
echo json_encode(array('success'=>false,'message'=>$this->lang->line('profiles_error_adding_updating').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['id']));
}
}
/*
This deletes profiles from the profiles table
*/
function delete()
{
$profiles_to_delete=$this->input->post('ids');
if($this->Profile->delete_list($profiles_to_delete))
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_deleted').' '.
count($profiles_to_delete).' '.$this->lang->line('profiles_one_or_multiple')));
}
else
{
echo json_encode(array('success'=>false,'message'=>$this->lang->line('profiles_cannot_be_deleted')));
}
}
/*
get the width for the add/edit form
*/
function get_form_width()
{
return 900;
}
}
?>
and view
<?php
echo form_open('salaries/save/'.$employee_id, array('id'=>'salary_summary_form'));
//echo form_open('salaries/save/', array('id'=>'salary_summary_form'));
?>
<div id="required_fields_message"><?php echo $this->lang->line('common_fields_required_message'); ?></div>
<ul id="error_message_box"></ul>
<fieldset id="salary_allowance_info">
<legend><?php echo $this->lang->line("salaries_allowance_info"); ?></legend>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_employee_id').':', 'employee_id', array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_dropdown('employee_id', $employee_id);?>
</div>
</div>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_allowance_basic_salary').':', 'basic_salary', array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_input(array(
'name'=>'basic_salary',
'id'=>'basic_salary',
'value'=>$basic_pay
));
?>
</div>
</div>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_allowance_house_rent').':', 'house_rent',array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_input(array(
'name'=>'house_rent',
'id'=>'house_rent',
// 'value'=>$salary_summary_info->house_rent
));
?>
</div>
</div>
<?php
echo form_submit(array(
'name'=>'submit',
'id'=>'submit',
'value'=>$this->lang->line('common_submit'),
'class'=>'submit_button float_right')
);
?>
</fieldset>
<?php
echo form_close();
?>
pls help me if any one
You don't test if your call to $db -> get() succeeded. I don't know the details of your $db class, but I suspect it only returns something if the call to it was successful. If the query fails does $db -> get() still return something?
Try doing a var_dump on what you get out of $db -> get() so you can see if it's returning what you think it's returning.
Fatal error: Call to a member function num_rows() on a non-object... is usually because there were no results return from a given query or possibly from a bad query.