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
Related
How to Save the Checkbox Value Form to MySQL in One Field, can anyone help me..
Here is my code:
function student($param1 = '') {
if ($this->session->userdata('admin_login') != 1) {
redirect('login', 'refresh');
}
$running_year = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
if ($param1 == 'create') {
$data['ekskul_id'] = $this->input->post('ekskul_id');
$this->db->insert('student', $data);
}
}
this is my display code
<div class="form-group">
<label for="field-2" class="col-sm-3 control-label">Ekstrakurikuler</label>
<div class="col-sm-5">
<select data-placeholder="Select" name="ekskul_id[]" multiple class="chosen-select" tabindex="8">
<?php
$ekstra = $this->db->get('ekstrakurikuler')->result_array();
foreach($ekstra as $row):
?>
<option value="<?php echo $row['ekskul_id'];?>"><?php echo $row['ekskul_name'];?></option>
<?php
endforeach;
?>
</select>
</div>
</div>
use below code to store multiple id in one field:
<?php
$ekskul_id= implode(",",$_POST['ekskul_id']);
?>
In your code :
if(isset($this->input->post('ekskul_id'))){
$data['ekskul_id'] = implode(",",$this->input->post('ekskul_id'));
}
I'm currently coding a blog to get experience with php.
In the edit.php I want to give the category of a post if a post has one.
This is the edit.php:
<div class="categories-heading">
<?php if (!empty($entry->c_Id)): ?>
<div class="category-heading">
<h3>Category: <?php echo e($categoryFromId); ?></h3>
</div>
<div class="category-heading">
<h3>change category</h3>
</div>
</div>
<form method="post">
<div class="categories-post-edit">
<?php foreach($categories as $cat): ?>
<div class="category-post-edit">
<input type="radio" name="category" value="<?php echo e($cat->id); ?>">
<label> <?php echo e($cat->category); ?></label>
</input>
</div>
<?php endforeach; ?>
</div>
</form>
<?php else: ?>
<div class="category-heading">
<h3>choose category</h3>
</div>
</div>
<form method="post">
<div class="categories-post-edit">
<?php foreach($categories as $cat): ?>
<div class="category-post-edit">
<input type="radio" name="category" value="<?php echo e($cat->id); ?>">
<label> <?php echo e($cat->category); ?></label>
</input>
</div>
<?php endforeach; ?>
This is the part of the function edit() in the PostsAdminController.php which is relevant for this:
if(!empty($_POST['title']) AND !empty($_POST['subheading']) AND
!empty($_POST['content'])
AND !empty($_POST['category'])) {
$entry->title = $_POST['title'];
$entry->subheading = $_POST['subheading'];
$entry->content = $_POST['content'];
$entry->c_Id = $_POST['category'];
$this->postsRepository->update($entry);
$savedSuccess = true;
}
$categoryFId = $this->categoryRepository->oneCategory($entry->c_Id);
$categoryFromId = $categoryFId['category'];
var_dump($categoryFromId);
$this->render("post/admin/edit", [
'entry' => $entry,
'savedSuccess' => $savedSuccess,
'categories' => $categories,
'categoryFromId' => $categoryFromId
]);
}
And this is the function oneCategory in the CategoryRepository.php that interacts with the database.
public function oneCategory($id)
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->prepare("SELECT `category` FROM `$table`
WHERE id = :id");
$stmt->setFetchMode(PDO::FETCH_CLASS, $model);
$oneCategory = $stmt->fetch(PDO::FETCH_CLASS);
return $oneCategory;
}
oneCategory() gives out an array no matter if I put SELECT * or SELECT category in the query, that's why I put $categoryFId['category'] into a variable after.
It works, but I think there must be a more easy or quicker way (like special functions or so), I just didn't manage to find what I search for
I can't show the data that I want to edit from my table. The combobox and the table don't show data when I edit the data categories, sub-categories, and manufacturers. I want to be able to see the data from my table after editing.
Controller form
public function data_items_edit($id)
{
$this->load->model('additem_m');
$model3 = $this->additem_m;
$data['table'] = $model3->get_where2($id)[0];
//$data['table'] = $model3->get();
$this->load->model('category_m');
$model = $this->category_m;
$data['category'] = $model->get();
$this->load->model('subcategory_m');
$model1 = $this->subcategory_m;
$data['sub'] = $model1->get();
$this->load->model('manufactures_m');
$model2 = $this->manufactures_m;
$data['manu'] = $model2->get();
//print_r($data['table']);
$this->load->view('items/edit_items_v', $data);
}
Data table controller
public function index()
{
if($this->session->has_userdata('isLogin')){
$this->load->model('additem_m');
$model = $this->additem_m;
$data['table'] = $model->get('items.*, item_categories.name as ic,
item_categories_sub.name as ics, item_manufactures.name as im',
[
['table'=>'item_categories','condition'=>'item_categories.id =
items.item_category_id'],
['table'=>'item_categories_sub','condition'=>'item_categories_sub.id
= items.item_category_sub_id'],
['table'=>'item_manufactures','condition'=>'item_manufactures.id =
items.item_manufacturer_id'],
]);
//print_r($data['table']);
$this->load->view('items/items_v', $data);
}else{
redirect('login');
}
}
View Form
<div class="form-group">
<label class="col-sm-4 control-label form-label">Category :</label>
<div class="col-sm-8">
<select name="item_category_id" class="form-control" id="category">
<option value='' <?php if($category == '0'){ echo 'selected';} ?>>--Select--</option>
<?php foreach($category as $category){
echo '<option value="'.$category->id.'">'.$category->name.'</option>';
} ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label form-label">Sub Category</label>
<div class="col-sm-8">
<select name="item_category_sub_id" class="form-control" id="category_sub">
<option value=''>- Select Sub Category -</option>
</select>
</div>
</div>
<div class="rightcontact">
<div class="form-group">
<label class="col-sm-4 control-label form-label">Manufacturer</label>
<div class="col-sm-8">
<select name="item_manufacturer_id" class="form-control" id="item_manufacturer_id">
<option>- Select Manufacturer -</option>
<?php foreach($manu as $manu){
echo '<option value="'.$manu->id.'">'.$manu->name."</option>";
} ?>
</select>
</div>
</div>
</div>
My view
You have to add selected attribute to the options.
$category == $category->id ? "selected" : ""
Something like this
<?php
foreach($category as $category){
echo '<option value="'.$category->id.'" '. $category == $category->id ? "selected" : "" .'>'.$category->name.'</option>';
^ ^
}
?>
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;
}
}
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?