I have table ingredient w/c consist of(ingredient_id,name),category w/c consist of(category_id,name) and category_ingredients w/c consist of(ingredient_id,category_id). I created a form for adding many ingredients by category and It check if 1 or more ingredients already exists in that category then I will only have to get the id's of the ingredient and then the other ingredients that don't exist will be inserted in my DB. Please help me i really need your help :(
VIEW:
<?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">
<select required class="form-control" name="ingredient_category">
<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->category_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>
<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>
CONTROLLER:
public function uploadIngredients(){
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name' => trim($value)
);
}
}
$ingredient_id = $this->products_model->saveIngredients($saveData);
foreach (explode(',', $this->input->post('ingredient_category')) as $key => $value)
{
foreach ( $ingredient_id as $key => $str ){
$joinData[] = array(
'ingredient_id' => $str,
'category_id' => intval($value)
);
}
$this->products_model->saveCategoryIngredients($joinData);
redirect('dashboard/add_ingredients');
}
MODEL:
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;
}
public function getIngredientByName($name) {
$this->db->select('ingredient_id');
$this->db->limit(1);
$this->db->where('category_id', $category_id);
$ingredientQuery = $this->db->get('category_ingredient');
$ingredient_id = $ingredientQuery->row()->ingredient_id;
$this->db->select('name');
$this->db->where('ingredient_id', $ingredient_id);
$query = $this->db->get('ingredient');
foreach($query->result() as $row)
{
return $row->name;
}
}
Related
I am using yii2. I want to pass the model id to a view but while doing so I am getting an error.
Controller
public function actionProcess($id){
try {
$model = $this->findModel($id);
} catch (NotFoundHttpException $e) {
} // this will find my model/record based on the id
$file_name = $_GET['file_name'];
// $data = \moonland\phpexcel\Excel::import("uploads/test.xlsx"); // $config is an optional
try {
$header_index = $_GET['header_no'];
$data = \moonland\phpexcel\Excel::widget([
'mode' => 'import',
'fileName' => 'uploads/' . $file_name,
'setFirstRecordAsKeys' => false, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
'setIndexSheetByName' => false, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
'getOnlySheet' => 0, // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
]);
if (isset($data[0])) {
$headers = $data[0][$header_index];
} else {
$headers = $data[$header_index];
}
}catch (Exception $x){
print_r($x->errorInfo);
}
return $this->render('excel_options',['headers'=>$headers,'file_name'=>$file_name,'header_index'=>$header_index,'id'=>$model->id]);
}
View
In my view, I am trying to pass the model id in a submit button
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4">
<br />
Submit
</div>
</div>
Now when I try to access my excel_options view, I am getting the below error.
Undefined variable: model
in E:\xampp\htdocs\inventory-web\backend\views\meteracceptanceheader\excel_options.php at line 103
Submit
Update 1
The controller from which I am rendering the excel_options is below
public function actionProcess($id){
$model = $this->findModel($id);
// this will find my model/record based on the id
$file_name = $_GET['file_name'];
// $data = \moonland\phpexcel\Excel::import("uploads/test.xlsx"); // $config is an optional
try {
$header_index = $_GET['header_no'];
$data = \moonland\phpexcel\Excel::widget([
'mode' => 'import',
'fileName' => 'uploads/' . $file_name,
'setFirstRecordAsKeys' => false, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
'setIndexSheetByName' => false, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
'getOnlySheet' => 0, // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
]);
if (isset($data[0])) {
$headers = $data[0][$header_index];
} else {
$headers = $data[$header_index];
}
}catch (Exception $x){
print_r($x->errorInfo);
}
return $this->render('excel_options',['headers'=>$headers,'file_name'=>$file_name,'header_index'=>$header_index,'id'=>$model->id]);
}
View
<div class="box">
<!-- /.box-header -->
<div class="box-body">
<form action="import" method="post">
<input type="hidden" name="file_name" value="<?=$_GET['file_name']?>" />
<input type="hidden" name="header_index" value="<?= $_GET['header_no'] ?>"/>
<h1>Maping</h1>
<div class="row">
<div class="col-md-2">
Ref #:
</div>
<div class="col-md-4">
<select name="field[0][ref_no]" class="form-control">
<option value="">Select A field</option>
<?php foreach($headers as $k=>$v) { ?>
<?php if (trim($v) != '') { ?>
<option value="<?=$k?>"><?=$v?></option>
<?php } ?>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-2">
Meter MSN:
</div>
<div class="col-md-4">
<select name="field[0][meter_msn]" class="form-control">
<option value="">Select A field</option>
<?php foreach ($headers as $k => $v) { ?>
<?php if (trim($v) != '') { ?>
<option value="<?= $k ?>"><?= $v ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-2">
Meter Type:
</div>
<div class="col-md-4">
<select name="field[0][meter_type]" class="form-control">
<option value="">Select A field</option>
<?php foreach ($headers as $k => $v) { ?>
<?php if (trim($v) != '') { ?>
<option value="<?= $k ?>"><?= $v ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-2">
Sub-Div:
</div>
<div class="col-md-4">
<select name="field[0][sub_div]" class="form-control">
<option value="">Select A field</option>
<?php foreach ($headers as $k => $v) { ?>
<?php if (trim($v) != '') { ?>
<option value="<?= $k ?>"><?= $v ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4">
<br />
Submit
</div>
</div>
</form>
</div>
</div>
How can I pass my model id into the view?
Any help would be highly appreciated
Try to pass not id but $model it self.
return $this->render('excel_options',['headers'=>$headers,'file_name'=>$file_name,'header_index'=>$header_index,'model'=>$model]);
and Keep you code in view.
Submit
I'm new with codeigniter and to the point I don't understand about this one. It's work in another view (form add) while this one (form edit) didn't working.
and there isn't any notification of an error.
my case is i would like to show dropdown menu from database in form edit like in the form add.
this is my code (the working one for form add):
controllers Admin.php :
for add data
class Admin extends CI_Controller {
public function tambah_data(){
$this->load->helper('form');
//kategori
$this->load->model('models_kategori_barang', 'mkb');
$datakb = $this->mkb->GetKategoriBarang();
//model
$this->load->model('models_model_barang', 'modb');
$datamdb = $this->modb->GetModelBarang();
//material
$this->load->model('models_material_barang', 'matb');
$datamatb = $this->matb->GetMaterialBarang();
//merk
$this->load->model('models_merk_barang', 'merb');
$datamerb = $this->merb->GetMerkBarang();
$this->load->view('templates/admin/tambah_data',array(
'datakb' => $datakb,
'datamdb' => $datamdb,
'datamatb' => $datamatb,
'datamerb' => $datamerb));
}
}
view tambah_data.php
<?php echo form_open_multipart('crud_barang/do_insert'); ?>
<label>Kode Barang<br>
<input type="text" autofocus placeholder="Kode" name="kode_barang" autofocus required></label>
<label>Nama<br>
<input type="text" placeholder="Nama" name="nama_barang" required></label>
<label>Kategori<br>
<select name="kategori_barang" required>
<option disabled selected>Pilih Katergori...</option>
<?php foreach ($datakb as $dkb) { ?>
<option><?php echo $dkb['nama_kategori_barang'];?></option>
<?php }?>
</select>
</label>
<label>Model<br>
<select name="model_barang" required>
<option disabled selected>Pilih Model...</option>
<?php foreach ($datamdb as $dmdb) { ?>
<option><?php echo $dmdb['nama_model_barang'];?></option>
<?php }?>
</select>
</label>
<label>Material<br>
<select name="material_barang" required>
<option disabled selected>Pilih Material...</option>
<?php foreach ($datamatb as $dmtb) { ?>
<option><?php echo $dmtb['nama_material_barang'];?></option>
<?php }?>
</select>
</label>
<label>Merk<br>
<select name="merk_barang" required>
<option disabled selected>Pilih Merk...</option>
<?php foreach ($datamerb as $dmb) { ?>
<option><?php echo $dmb['nama_merk_barang'];?></option>
<?php }?>
</select>
</label>
<label>Harga<br><input type="text" placeholder="Harga" name="harga_barang" required></label>
<label>Ukuran<br><input type="text" placeholder="Ukuran" name="size_barang" required></label>
<label>Keterangan<br>
<textarea placeholder="Keterangan" name="ket_barang"></textarea>
</label>
<p><input type="submit" value="Masukan" class="btn"></p>
<?php echo form_close(); ?>
model models_barang.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Models_barang extends CI_Model {
public function GetBarang($where=""){
$datab = $this->db->get('barang'.$where);
return $datab->result_array();
}
public function InsertData($tabelName, $datab){
$res = $this->db->insert($tabelName,$datab);
return $res;
}
public function UpdateData($tabelName,$datab,$where){
$res = $this->db->update($tabelName,$datab,$where);
return $res;
}
public function DeleteData($tabelName,$where){
$res = $this->db->delete($tabelName,$where);
return $res;
}
}
this one not work while i put it in form edit :
controller crud_barang.php
class crud_barang extends CI_Controller {
//funciton insert was here
public function edit_data($id_barang){
/*load model dahulu, karena bukan global model*/
$this->load->model('models_barang', 'mb');
$brg = $this->mb->GetBarang(" where id_barang = '$id_barang'");
$datab = array(
'id_barang' => $brg[0]['id_barang'],
'kode_barang' => $brg[0]['kode_barang'],
'nama_barang' => $brg[0]['nama_barang'],
'material_barang'=> $brg[0]['material_barang'],
'model_barang' => $brg[0]['model_barang'],
'kategori_barang' => $brg[0]['kategori_barang'],
'harga_barang' => $brg[0]['harga_barang'],
'size_barang' => $brg[0]['size_barang'],
'merk_barang' => $brg[0]['merk_barang'],
'ket_barang' => $brg[0]['ket_barang']
);
$this->load->view('templates/admin/form_edit_barang',$datab);
$this->load->model('models_kategori_barang', 'mkb');
$this->load->model('models_model_barang', 'modb');
$this->load->model('models_material_barang', 'matb');
$this->load->model('models_merk_barang', 'merb');
$datakb = $this->mkb->GetKategoriBarang();
$datamodb = $this->modb->GetModelBarang();
$datamatb = $this->matb->GetMaterialBarang();
$datamerb = $this->merb->GetMerkBarang();
$this->load->view('templates/admin/form_edit_barang',array(
'datakb' => $datakb,
'datamodb' => $datamodb,
'datamatb' => $datamatb,
'datamerb' => $datamerb), TRUE);
}
public function do_update(){
/*load model dahulu, karena bukan global model*/
$this->load->model('models_barang', 'mb');
$id_barang = $_POST['id_barang'];
$kode_barang = $_POST['kode_barang'];
$nama_barang = $_POST['nama_barang'];
$material_barang = $_POST['material_barang'];
$model_barang = $_POST['model_barang'];
$kategori_barang = $_POST['kategori_barang'];
$harga_barang = $_POST['harga_barang'];
$size_barang = $_POST['size_barang'];
$merk_barang = $_POST['merk_barang'];
$ket_barang = $_POST['ket_barang'];
$data_update = array(
'id_barang' => $id_barang,
'kode_barang' => $kode_barang,
'nama_barang' => $nama_barang,
'material_barang'=> $material_barang,
'model_barang' => $model_barang,
'kategori_barang' => $kategori_barang,
'harga_barang' => $harga_barang,
'size_barang' => $size_barang,
'merk_barang' => $merk_barang,
'ket_barang' => $ket_barang
);
$where = array('id_barang' => $id_barang);
$res = $this->mb->UpdateData('barang', $data_update, $where);
if($res>=1){
$this->session->set_flashdata('pesan_barang','- Update Data Barang Sukses');
redirect('admin/lihat_data');
}else{
echo "<h2>Update Data Barang Gagal</h2>";
}
}
view form_edit_barang.php
<?php echo form_open_multipart('crud_barang/do_update'); ?>
<label>Id Barang<br>
<input type="text" autofocus placeholder="Id Barang" name="id_barang" value="<?php echo $id_barang; ?>" readonly>
</label>
<label>Kode Barang<br>
<input type="text" autofocus placeholder="Kode" name="kode_barang" value="<?php echo $kode_barang; ?>">
</label>
<label>Nama<br>
<input type="text" placeholder="Nama" name="nama_barang" value="<?php echo $nama_barang; ?>">
</label>
<label>Kategori<br>
<select name="kategori_barang">
<option><?php echo $kategori_barang;?></option>
<?php foreach ($datakb as $dkb) { ?>
<option><?php echo $dkb['nama_kategori_barang'];?></option>
<?php }?>
</select>
</label>
<label>Model<br>
<select name="model_barang" required>
<option><?php echo $model_barang;?></option>
<?php foreach ($datamdb as $dmdb) { ?>
<option><?php echo $dmdb['nama_model_barang'];?></option>
<?php }?>
</select>
</label>
<label>Material<br>
<select name="material_barang" required>
<option><?php echo $material_barang;?></option>
<?php foreach ($datamatb as $dmtb) { ?>
<option><?php echo $dmtb['nama_material_barang'];?></option>
<?php }?>
</select>
</label>
<label>Merk<br>
<select name="merk_barang" required>
<option><?php echo $merk_barang;?></option>
<?php foreach ($datamerb as $dmb) { ?>
<option><?php echo $dmb['nama_merk_barang'];?></option>
<?php }?>
</select>
</label>
<label>Harga<br><input type="text" placeholder="Harga" name="harga_barang" value="<?php echo $harga_barang; ?>"></label>
<label>Ukuran<br><input type="text" placeholder="Ukuran" name="size_barang" value="<?php echo $size_barang; ?>"></label>
<label>Keterangan<br><textarea placeholder="Keterangan" name="ket_barang""><?php echo $ket_barang; ?></textarea></label>
<p><input type="submit" value="Simpan" class="btn"></p>
<?php echo form_close(); ?>
the dropdown menu data from database won't show in form edit. i don't understand why, do i miss something or what? cause there isn't notification of error. help me pls, thank you :)
the result in form add (working):
1
while in form edit, only show the original data :
2
I'm guessing its because in your edit_data function you are loading your view twice. Why that isn't giving you notices for undefined $id_barang .etc. is beyond me; also not sure why you aren't seeing the view twice (probably because you have errors suppressed).
Please note the comments.
public function edit_data($id_barang) {
/* load model dahulu, karena bukan global model */
$this->load->model('models_barang', 'mb');
$brg = $this->mb->GetBarang(" where id_barang = '$id_barang'");
$datab = array(
'id_barang' => $brg[0]['id_barang'],
'kode_barang' => $brg[0]['kode_barang'],
'nama_barang' => $brg[0]['nama_barang'],
'material_barang' => $brg[0]['material_barang'],
'model_barang' => $brg[0]['model_barang'],
'kategori_barang' => $brg[0]['kategori_barang'],
'harga_barang' => $brg[0]['harga_barang'],
'size_barang' => $brg[0]['size_barang'],
'merk_barang' => $brg[0]['merk_barang'],
'ket_barang' => $brg[0]['ket_barang']
);
// DUPLICATE, REMOVED
//$this->load->view('templates/admin/form_edit_barang', $datab);
$this->load->model('models_kategori_barang', 'mkb');
$this->load->model('models_model_barang', 'modb');
$this->load->model('models_material_barang', 'matb');
$this->load->model('models_merk_barang', 'merb');
$datakb = $this->mkb->GetKategoriBarang();
$datamodb = $this->modb->GetModelBarang();
$datamatb = $this->matb->GetMaterialBarang();
$datamerb = $this->merb->GetMerkBarang();
// MERGED ARRAY HERE
$this->load->view('templates/admin/form_edit_barang', array_merge($datab, array(
'datakb' => $datakb,
'datamodb' => $datamodb,
'datamatb' => $datamatb,
'datamerb' => $datamerb)));
}
I have table ingredient w/c consist of(ingredient_id,name),category w/c consist of(category_id,name) and category_ingredients w/c consist of(ingredient_id,category_id). I create a form for adding many ingredients by category and i want to check if 1 or more ingredients already exist then i will only have to get the id's of the ingredient and then the other ingredients that don't exist will be inserted in my db. can u guys help me pls?
Here's my code:
VIEW:
<?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">
<select required class="form-control" name="ingredient_category">
<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->category_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>
<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>
CONTROLLER:
public function uploadIngredients()
{
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
$saveData[] = array('ingredient_id' => null,
'name' => trim($value)
);
}
$ingredient_id = $this->products_model->saveIngredients($saveData);
foreach (explode(',', $this->input->post('ingredient_category')) as $key => $value)
{
foreach ( $ingredient_id as $key => $str ){
$joinData[] = array(
'ingredient_id' => $str,
'category_id' => intval($value)
);
}
//var_dump($joinData); die();
$this->products_model->saveCategoryIngredients($joinData);
redirect('dashboard/add_ingredients');
}
}
MODEL:
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;
}
public function saveCategoryIngredients($data)
{
foreach($data as $row => $value)
{
$this->db->insert('category_ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;}
}
You just have to add a function to your model, like this :
<?php
public function getIngredientByName($name) {
return $this->db
->from('ingredient I')
->where('I.name', $name)
->get()->row(); //Will return the row of ingredient if ingredient exists, else null
}
And in your controller :
<?php
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name' => trim($value)
);
}
}
Thanks Gwendal for answering this question i am modifying this answer a bit to prevent duplicate inserts e.g.:- if user inserts SuGar CaNe but we have in our database Sugar Cane then the with answer's code we will have 2 sugar cane to avoid these type of inserts we can use this code for model
<?php
public function getIngredientByName($name) {
return $this->db
->from('ingredient I')
-> where("( REPLACE( LOWER(I.name), ' ', '') LIKE '".strtolower(preg_replace('/\s+/', '', $name)) ."%')")
->get()->row(); //Will return the row of ingredient if ingredient exists, else null
}
for controller same as
<?php
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name' => trim($value)
);
}
}
I have a table ingredient w/c consist of(ingredient_id,name). I can perfectly add an ingredient. But i want to add a condition that prohibit on adding existing ingredient. I have the code for that condition but i think it's wrong because the condition didn't work and i can still add an existing ingredient. please help me
HERE'S MY CODE:
VIEW:
<?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">
<select required class="form-control" name="ingredient_category">
<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>
<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>
CONTROLLER:
public function uploadIngredients()
{
foreach(explode(',', $this->input->post('ingredients')) as $key => $value) {
$saveData[] = array('ingredient_id' => null,
'name' => trim($value)
);
}
$ingredient_id = $this->products_model->saveIngredients($saveData);
redirect('dashboard/add_ingredients');
} }
MODEL:
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
if($query->num_rows > 0) {
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
} else {
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
}
return $insert_id;
}
Change your model to
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('name', $value->name);
if($query->num_rows > 0) {
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
} else {
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
}
return $insert_id;
}
That should do it. Just changing the $query line.
If that doesn't work, do a var_dump on $value just above that line, so you can see if you need to adjust the value you're targeting.
Use below code.
CONTROLLER:
public function uploadIngredients()
{
foreach(explode(',', $this->input->post('ingredients')) as $key => $value) {
$result = this->products_model->saveIngredients(trim($value));
if($result['status'])
{
$ids[]=$result['id'];
}else{
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
}
}
redirect('dashboard/add_ingredients');
} }
MODEL:
public function saveIngredients($data)
{
$query=$this->db->where('name', $data);
if($query->num_rows > 0) {
return ['status'=>FALSE];
} else {
$this->db->insert('ingredient', array('name'=>$data));
$insert_id = $this->db->insert_id();
return ['status'=>TRUE,'id'=>$insert_id];
}
}
OK, so I have looked everywhere for a solution to my problem but found none so far.My code looks like this.I have created a dynamic view page in which edit and add views are loaded dynamically.But the problem arises when i try to retain the value of select dropdown during editing.I would be grateful if someone could help me out.
View
<div class="panel-body">
<div class="row">
<div class="col-lg-6">
<?php if(#$patient_info){
echo '<h1 class="page-header">Edit Patient</h1>';
}else{
echo '<h1 class="page-header">Add Patient</h1>';
}
?>
<?php if($this->session->flashdata('error')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('error'); ?></div>
<?php } ?>
<?php if($this->session->flashdata('erroredit')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('erroredit'); ?></div>
<?php } ?>
<?php //echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form role="form" method="post" action="<?php echo isset($patient_info) ? site_url('home/patient/edit') .'/' .$patient_info->patientID : site_url('home/patient/new'); ?>">
<div class="form-group">
<?php echo form_error('pname', '<div class="alert alert-danger">', '</div>'); ?>
<label for="pname">Patient Name</label>
<input class="form-control" placeholder="Enter Patient Name" name="pname" value="<?php echo isset($patient_info) ? $patient_info->patientName : ''; ?>">
</div>
<!-- Dropdown menu for selecting clinic -->
<div class="form-group">
<label for="select">Select Clinic Name</label>
<select class="form-control" name="selectClinic">
<option value="none">Select Clinic Below</option>
<?php foreach($allclinic as $key=>$clinic){ ?>
<!--<?php //foreach($clinicByPatient as $clin): ?>-->
<option value="<?php $clinic->clinicID; ?>"
<?php if(isset($patient_info)){
echo 'selected="selected"';
}
?>
>
<?php echo $clinic->clinicName; ?>
</option>
<?php //endforeach; ?>
<?php } ?>
</select>
</div>
<!-- Select Clinic ends-->
<div class="form-group">
<label for="select">Select Dentist</label>
<select class="form-control" name="selectDentist">
<option value="">Select Dentist</option>
<?php foreach($dentistdet as $key=>$dentist){ ?>
<option value="<?php echo $did = $dentist->dentistID;?>"><?php echo $dentist->dentistName; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" name="submit" value="<?php echo isset($patient_info) ? 'Update Patient' : 'Add Patient'; ?>" >
</div>
</form>
<div class="form-group">
<input type="submit" class="btn btn-danger btn-lg btn-block" value="Cancel">
</div>
Edit controller
public function edit(){
$id = $this->uri->segment(4);
$this->load->library('form_validation');
$this->load->model('clinic_model');
$this->load->model('dentist_model');
$data['patient_info'] = $this->patient_model->getPatientById($id);
$data['clinicByPatient'] = $this->patient_model->getPatientByClinic();
$data['allclinic'] = $this->clinic_model->getAllClinics();
// $data['clinicdet'] = $this->patient_model->getPatientByClinic();
if($_POST){
$this->form_validation->set_rules('pname', 'Patient Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('paddress', 'Patient Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('pcontact', 'Patient Contact', 'trim|required|xss_clean');
if($this->form_validation->run()== FALSE){
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout', $data);
}else{
$patientname = $this->input->post('pname');
$patientaddress = $this->input->post('paddress');
$patientcontact = $this->input->post('pcontact');
$select = $this->input->post('selectClinic');
$option = $this->input->post('selectDentist');
$edited = $this->patient_model->editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option);
if($edited){
$this->session->set_flashdata('successedit', 'Successfully updated the record');
redirect('home/patient');
}
}
}else{
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout',$data);
}
}
Model looks like this
<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
class Patient_model extends CI_Model{
public function countPatients(){
$countPatient = $this->db->count_all('patient');
return $countPatient;
}
public function getallpatients(){
$query = $this->db->get('patient');
if($query->num_rows()>0){
return $query->result();
}
else{
return FALSE;
}
}//getallpatients function ends
public function getPatientByClinic(){
$this->db->select('*');
$this->db->from('patient');
$this->db->join('clinic', 'patient.clinicID = clinic.clinicID', 'left');
$this->db->join('dentist', 'patient.dentistID = dentist.dentistID', 'left');
$query = $this->db->get();
if($query->num_rows>0){
return $query->result();
}
}
public function addPatientByClinic($patientname, $patientadd, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientadd,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
return $this->db->insert('patient',$data);
}// method ends
public function deletePatient($id){
$verifyID = array('patientID' => $id);
// $affRows = $this->db->affected_rows();
// $obj = new Patient_model;
if($verifyID){
$this->db->where($verifyID);
$this->db->delete('patient');
if($this->db->affected_rows()){
return TRUE;
}
}
}
public function editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientaddress,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
$query = $this->db->where('patientID', $id)
->update('patient', $data);
if($query){
return true;
}
}//method ends
public function getPatientById($id){
$query = $this->db->where('patientID', $id)
->get('patient');
return $query->row();
}
}//class ends
?>
In the code for your select box, you aren't actually echoing $clinic->clinicID. Thus, when the form is submitted, the value will be empty.
You also need to be careful with how you are choosing which select element will be selected by default - you aren't comparing with anything that will change within the loop. Should you be checking against $clinic->clinicID?