Displaying values in select box dynamically is not working in codeigniter - php

I am trying to get values in select box as dynamic is not working
here is the my controller code below:
public function CreateNewAsset()
{
$data['courselist'] = $this->Dashboard_model->getDashboardCourses();
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('topicname', 'Topicname', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset');
$this->load->view('template/footer');
} else {
//Setting values for tabel columns
$data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
//Transfering data to Model
$this->Dashboard_model->assetInsert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset', $data);
$this->load->view('template/footer');
}
}
Here is the my view below:
<form action="<?php echo base_url();?>Dashboard/CreateNewAsset" method="post">
<div class="form-row">
<div class="col-md-3">Course:</div>
<div class="col-md-9">
<select name="courseid" class="form-control">
<option value="0">Select Course</option>
<?php foreach ($courselist as $course) { ?>
<option value="<?php echo $course->id; ?>"><?php echo $course->coursename; ?></option>
<?php } ?>
</select>
</div>
</div>
</form>
I have added both getting values and insert in the same function. is this the problem I am not getting values in drop-down can anyone help me what is the mistake
and I am getting an error as Undefined variable: courselist

Change the insert part like this since u overriding $data:
$insert_data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
$this->Dashboard_model->assetInsert($insert_data);
The whole code should be like this :
NOTE : make sure u have loaded form_validation library and method getDashboardCourses return some data
public function CreateNewAsset()
{
$data['courselist'] = $this->Dashboard_model->getDashboardCourses();
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('topicname', 'Topicname', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset',$data);
$this->load->view('template/footer');
}
else
{
$insert_data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
$this->Dashboard_model->assetInsert($insert_data);
$data['message'] = 'Data Inserted Successfully';
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset', $data);
$this->load->view('template/footer');
}
}

Your "View" can't find the courseList variable.
You need to do add courseList to your data array before you pass it to the view with the form.
Eg:-
data['courseList'] = $this->getCourseList(); // Fetch the list of rows

Related

Multiple Insert with dropdown codeigntier

I have3 table with name frm_data_aset,frm_monitor,frm_lokasi
I want if I insert on frm_data_aset column monitor_aset with dropdown from tabel monitor and lokasi from tabel lokasi. on table monitor column lokasi updated with data same at I insert from tabel data_Aset
this my structure :
enter image description here
enter image description here
now I get error :
Unknown column 'frm_monitor' in 'where clause'
UPDATE frm_monitor SET lokasi_monitor = '123' WHERE frm_monitor IS NULL
this my controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id= $this->input->post('kd_monitor', TRUE);
$data = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data);
$this->M_data_aset->insert($data);
redirect(site_url('data_aset'));
}
}
this my model M_monitor
function update_lokasi($id,$data){
$this->db->where('frm_monitor', $id);
$this->db->update('frm_monitor', $data);
}
and this my dropdown monitor at form insert data_aset
<option value="0">Pilih Monitor</option>
<?php
$monitor = $this->db->get('frm_monitor')->result();
foreach ($monitor as $row){
echo "<option value='$row->kd_monitor' ";
echo $row->kd_monitor==$monitor_aset?'selected':'';
echo ">". strtoupper($row->kd_monitor)."</option>";
}
?>
try changing your model query as like this
function update_lokasi($id,$data){
$this->db->where('id_monitor', $id);
$this->db->update('frm_monitor', $data);
}
Before that make sure that the post for 'kd_monitor' in the controller is not null
You should rename the $data variable being passed to $this->M_monitor->update_lokasi() because it will overwrite $data that is going to be passed to $this->M_data_aset->insert() with only 'lokasi_monitor' array on it. Or even better try rename both $data to prevent confusion.
Modify your controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data_aset = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id = $this->input->post('kd_monitor', TRUE);
$data_monitor = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data_monitor);
$this->M_data_aset->insert($data_aset);
redirect(site_url('data_aset'));
}
}
And change 'frm_monitor' to 'kd_monitor' on the conditional query :
function update_lokasi($id,$data){
$this->db->where('kd_monitor', $id);
$this->db->update('frm_monitor', $data);
}

Codeigniter : how to update mulitiple record where id

I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.
my view :
<?php echo form_open('stock/updating_stock');?>
<div class="panel-body scroll-menu" style="margin-top:0px;height:170px;padding-top:5px;">
<?php foreach($critical_plus_warning as $data){?>
<input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">
<h5 class="hidden-xs"><b><?php echo $data->product_name;?></b> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
<?php
$stock = $data->stocks;
if($stock < 10){
echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
}else{
echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
}
?>
</h5>
<h5 class="hidden-lg"><b><?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?></b> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
<?php
$stock = $data->stocks;
if($stock < 10){
echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
}else{
echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
}
?>
</h5>
<?php }?>
</div>
<div class="col-xs-12" style="margin-top:-5px;background-color:white;padding:6px;background-color:white;box-shadow:0px 0px 8px 0px #bababa;"><button type="submit" name="submit" class="btn btn-success">Save data</button></div>
<?php echo form_close();?>
and my controller :
function updating_stock(){
$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
for($i=0;$i<count($id);$i++){
$data = array(
array(
'id' => $id,
'stok' => $stok,
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
),
);
}
//print_r($data);
$this->stok_adm->update_stok($data);
}
and my models :
function update_stok($data){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();
}
You need a where clause:
$this->db->where('id', $id);
...I think.
Try this:
Controller
function updating_stock(){
$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
for($i=0;$i<count($id);$i++){
$data = array(
array(
'id' => $id,
'stok' => $stok,
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
),
);
}
//print_r($data);
$this->stok_adm->update_stok($data,$id);
}
Model:
function update_stok($data,$id){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();
}
I think in your example update_batch will generate incorrect query beacues you need to update each record in db instead of updating them together - update_batch replaces values in multiple rows which fulfills conditions so there is possibility to update also incorrect rows (check example in documentation). So better idea is to update each single product using it's ID. It could look like that:
Model
function update_stok($data, $id_product){
$this->db->where('id_product', $id_product);
return $this->db->update($this->table, $data);
}
Controller
function updating_stock(){
$ids = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
foreach($ids as $key => $id_product) {
$data = array(
'stok' => $stok[$key],
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
);
$this->stok_adm->update_stok($data, $id_product);
}
}
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->update_batch('mytable', $data, 'title');
http://www.codeigniter.com/user_guide/database/query_builder.html?highlight=update_batch

Insert session userdata into a new database in CodeIgniter

How would I go about inserting the session userdate id into my new table using the form I have in my view so that I may use the id as a foreign key?
Controller:
function validate_credentials() {
$this->load->model('member_model');
$query = $this->member_model->validate();
if ($query) { // if user credentials validate the user session start
$data = array(
'username' => $query->username,
'id' => $query->id,
'first_name'=>$query->first_name,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('members/members_area');
} else {
$this->index();
echo 'Incorrect Password or Username';
}
}
View:
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Length'));
echo form_submit('submit', 'Create Account')
echo validation_errors('<p class="error"/>');
Try this :
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Length'));
**echo form_input('id', set_value('id', $this->session->userdata('id'));**
echo form_submit('submit', 'Create Account')
echo validation_errors('<p class="error"/>');
Note : where 'id' in first parameter of form_input function can be replace by any name you want to pass when form will be submit.
In the method used in the controller banks where you handle the posted data from the from.
add something like this:
$data = array('bank_name' => $this->input->post('bank_name'), // add more post data
'id' => $this->session->userdata('id') ); //this will take the
//value 'id' from session
and pass it to your respective model.

Inserting two fields into a database

I am struggling to add data and a category_id in to my database using the MVC architecture.
here is my controller method, which is probably all wrong.
public function create(){
$data['categories'] = $this->get_m->createJoke();
$data = array(
'joke' => $this->input->post('joke'),
'category_id' => $this->input->post('category')
);
$this->get_m->createJoke($data);
$this->load->view('create', $data);
}
Here is my model method:
function createJoke($data){
// Retrieving categories from the database
$categories = $this->db->query('SELECT * FROM category');
$this->db->insert('jokes', $data);
return $categories->result();
}
and finally, this is the form which i want to be able to select a category for a joke:
<?php
echo form_open('home/create');
?>
<p>
<label for="joke">Joke</label>
<input type="text" name="joke" id="joke" />
</p>
<select class="category" name="category">
<option value=0>Select something…</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['category_id']; ?>"<?php echo $category_id == $category['category_id'] ? ' selected="selected"' : ''; ?>><?php echo $category['name']; ?></option>
<?php } ?>
</select>
<p>
<input type="button" value="Submit"/>
</p>
<?php echo form_close(); ?>
Before i just had the joke label up (although it did add data in the database), it only added a "0" for some reason.
I have been watching some CRUD tutorials which focus on inserting data, and this is the best i can come up with really!
You didn't check whether form is submitted or not in your controller.
public function create(){
$data['categories'] = $this->get_m->createJoke();
if($this->input->post("joke")!="" and $this->input->post("category")!="") // check post have some value
{
$data = array(
'joke' => $this->input->post('joke'),
'category_id' => $this->input->post('category')
);
$this->get_m->createJoke($data);
}
$this->load->view('create', $data);
}
try this i think this will work
//controller
public function create(){
$data = array(
'joke' => $this->input->post('joke'),
'category_id' => $this->input->post('category')
);
$this->get_m->createJoke($data);
$this->load->view('create', $data);
}
public function selectdata(){
$data['categories'] = $this->get_m->get_joke_categoryid();
}
//model
function createJoke($data){
$this->db->insert('joker', $data);
$this->session->set_flashdata("message", "Contract record successfully created.");
function get_joke_categoryid(){
$query = $this->db->get('joker');
return $query->result();
}
kindly check this if this code help you

Twitter Typeahead in CodeIgniter. Not passing array datum to hidden form field

I'm trying to use the typeahead.js Twitter Typeahead (not Bootstrap typeahead) to display names pulled from a mysql table using the CodeIgniter framework. The model also collects id values along with the name.
The controller and model seem to be presenting the correct array format.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$mode = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($mode == 'signin')
$this->db->where("status !=", "enter");
else
$this->db->where("status", "enter");
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['value']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
}
Controller (relevant functions)
function get_person() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->get_post();
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
Sample JSON data returned
[{"value":"Anna Woodhouse","id":"2"},{"value":"Elaine Woodhouse","id":"4"}]
View
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm"))?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="hidden" name="person_id" id="person_id" value="" />
<input class="people-typeahead" type="text" id="typeahead" name="name" placeholder="person's full name"/>
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="<?php echo $baseURL?>assets/js/typeahead.min.js"></script>
<script>
$(function($) {
$('input.people-typeahead').typeahead({
name: 'people',
remote: 'http://localhost/badgeentry/index.php/attendance/get_person',
dataType: 'json'
});
$("#people-typeahead").on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(person_id).val() = datum.id
});
});
</script>
In the form field I get the correct drop down list, but when an item is selected any new database entry has an id of "0" instead of the selected name id. I'm almost certain that this is an issue with the javascript code in the view not being correct, but quite frankly, I have no js skills to sort it out!
I see an issue here :
$(person_id).val() = datum.id
You are using jQuery's .val() incorrectly and the use of the selector is wrong too. It should look like :
$("#person_id").val(datum.id);
jQuery .val() documentation
I finally figured out how to get this working. Part of the problem was that I could find no examples of using typeahead.js in CodeIgniter that showed how the various script, view, controller and model components interact. I tried switching to Twitter bootstrap typeahead. However, despite finding references to using it with an arrays rather than a string, I still could not get a working solution.
In the end I went back to Twitter typeahead and started from scratch. I found this tutorial helped enormously:
Twitter Bootstrap typeahead.js with underscore.js Templating – A Tutorial - Alan Greenblatt
I'm posting what worked for me in case it can help anyone else with similar issues. This version also includes setting the remote source as a variable which allowed me to define it through PHP so that I could select data in the model based on the URL.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$modeinout = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($modeinout == 'signin'){
$this->db->where('status !=', 'enter');
}
else {
$this->db->where('status', 'enter');
}
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['name']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
Controller (relevant functions)
function signin() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['title'] = "Sign Someone In";
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['mode'] = 'signin';
$this->load->view("home/attendance/signinout", $data);
}
function signout() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['id'] = '';
$data['title'] = "Sign Someone Out";
$data['mode'] = 'signout';
$this->load->view("home/attendance/signinout", $data);
}
function get_people() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->post('query');
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('person_name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('person_name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
View
<?php
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm",'class' => "form-horizontal validate"))?>
<input type="hidden" name="person_id" id="person_id">
<?php echo validation_errors(); ?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="text" placeholder="person's full name" name="person_name" id="person_name" class="person-typeahead">
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script>
var person_url="<?php echo site_url('attendance/get_people')."/".$mode;?>";
$(function($) {
_.compile = function(templ) {
var compiled = this.template(templ);
compiled.render = function(ctx) {
return this(ctx);
}
return compiled;
}
$('.person-typeahead').typeahead({
template: '<p><strong><%= name %></strong>: <%= id %></p>',
name: 'people',
valueKey: 'name',
engine: _,
remote: (person_url),
dataType: 'json'
}).on('typeahead:selected typeahead:autocompleted', function(event, datum) {
$('#person_id').val(datum.id);
$('#person_name').val(datum.name);
});
});
</script>
<?=jquery_validate('attendance/signout');?>

Categories