Cant pass array value from codeigniter controller to view - php

Inside my controller, I have a line that needs to pass $content['pass_check'] to the view. It is inside an if statement that checks for validation. This I have found causes it to break. Once I move the $content['pass_check'] outside of any if statement, it works just fine passing to the view. All of the other values are passed (accounts, expense_accounts, vendors, terms). What must I do to get it to pass within this if statement. I've even tried moving it outside of the validation and it still wont set.
function create() {
require_permission("INVOICE_EDIT");
$this->load->library("form_validation");
$this->form_validation->set_rules("invoice_number", "Invoice Number", "required");
if($this->form_validation->run() !== false) {
$post = $this->input->post();
$this->session->set_userdata("create_invoice_vendor", $post['vendor_id']);
$this->session->set_userdata("create_invoice_date", $post['invoice_date']);
$invoice_number_exists = $this->invoices->count(array("invoice_number" => $post['invoice_number'])) > 0;
$post['invoice_date'] = date("Y-m-d", strtotime($post['invoice_date']));
$post['due_date'] = date("Y-m-d", strtotime($post['due_date']));
$post['date_entered'] = "now()";
$id = $this->invoices->insert_invoice($post);
$this->load->model("vendors");
if(isset($post['invoice_number'])){
$string_check= $post['invoice_number'];
$string_check= preg_replace('/\d/', '#', $string_check);
$string_check= preg_replace('/\w/', '#', $string_check);
$invoice_pattern=array();
$invoice_pattern = $this->db->select("invoice_pattern")->where("vendor_id",
$post['vendor_id'])->get("vendors")->result();
$invoice_pattern=$invoice_pattern[0]->invoice_pattern;
* //// THIS IS WHERE I NEED HELP ///////
if($invoice_pattern == $string_check){
***$content['post_check'] = 1;***
$this->invoices->flag_invoice($id);
};
};
$history = array(
"type" => "invoice_entered",
"comments" => "Invoice was entered",
"link" => $id,
"admin_id" => $this->user->admin_id,
"date" => "now()",
);
$this->vendors->insert_history($post['vendor_id'], $history);
if($post['flagged'] == 1) {
$this->invoices->flag_invoice($id);
}
if($invoice_number_exists) {
redirect("invoices/confirm_invoice/".$id);
} else {
// redirect("invoices/view/".$id);
redirect("invoices/create");
}
}
$content['accounts'] = $this->db->get("acct_chart_of_accounts")->result();
$content['expense_accounts'] = $this->db->get("invoice_expense_accounts")->result();
$content['vendors'] = $this->db->select("vendor_id, name, terms, override, invoice_pattern")
->order_by("name ASC")->get("vendors")->result();
$content['terms'] = $this->db->query("SELECT DISTINCT(terms) FROM vendors")->result();
}
}
$this->template['sub_heading'] = "Create";
$this->template['content'] = $this->load->view("invoices/create", $content, true);
$this->template['sidebar'] = $this->load->view("invoices/sidebar", array(), true);
$this->template['scripts'] = array("codeigniter/javascript/invoices/create.js");
$this->template['styles'][] = "codeigniter/styles/invoices/create.css";
$this->display();
}

Obviously it won't pass it to the view if the condition doesn't match, because you're only declaring the variable within the condition if it matches.
Just create $content['pass_check'] with an initial value of 0 or whatever before the conditional check first.
function create() {
...snip...
$content['pass_check'] = 0;
if($invoice_pattern == $string_check) {
$content['post_check'] = 1;
$this->invoices->flag_invoice($id);
};
...snip...
}
Let me know if this works or not please.

Related

Persist filter values in codeigniter with pagination library

I use the default codeiginter pagination library. I tried implementing this in a previously created page which shows all vacancies, but since we are getting TOO many on the site, the performance is terrible. This is why I need pagination on this page. Note that this is not the cleanest solution, there is a new track going on which overhauls the entire page and starts from scratch. This is a quick & dirty solution because we need to keep it working on our live environment until the rework is done.
This is the controller code I have:
public function overviewVacancies($city = null)
{
$this->is_logged_in();
// Load Models
$this->load->model('vacancy/vacancies_model');
$this->load->model('perk/interests_model');
$this->load->model('perk/engagement_model');
$this->load->model('user/userSavedVacancies_model');
// Passing Variables
$data['title'] = lang("page_title_activities_overview");
$data['description'] = lang('meta_desc_activities');
$data['class'] = 'vacancy';
$data['engagements'] = $this->engagement_model->getAll();
$data['interests'] = $this->interests_model->getAllInterests();
$data['bread'] = $this->breadcrumbmanager->getDashboardBreadcrumb($this->namemanager->getDashboardBreadName("0"), $this->namemanager->getDashboardBreadName("1"));
$data['tasks'] = $this->interests_model->getAllTasks();
// Set session data
$this->session->set_userdata('previous',"http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
$this->session->set_userdata('previous-title', "1");
$filterdata = array(
'interests' => $this->input->post('interests'),
'skills' => $this->input->post('skills'),
'fulldate' => $this->input->post('daterange'),
'location' => $this->input->post('location'),
'city' => $this->input->post('sublocality_level_1'),
'capital' => $this->input->post('locality')
);
if (!empty($filterdata['interests'])) {
$filterdata['interests'] = rtrim($filterdata['interests'], ";");
$filterdata['interests'] = str_replace(' ', '', $filterdata['interests']);
$filterdata['interests'] = str_replace(';', ',', $filterdata['interests']);
}
if (!empty($filterdata['skills'])) {
$filterdata['skills'] = str_replace(' ', '', $filterdata['skills']);
$filterdata['skills'] = explode(",", $filterdata['skills']);
}
//Manually clear the commune and city variables if the location was empty
if (empty($filterdata['location'])) {
$filterdata['city'] = '';
$filterdata['capital'] = '';
}
if($city == null){
$orgId = $this->organization_model->getOrgIdByName(LOCATION);
}
else{
$orgId = $this->organization_model->getOrgIdByName($city);
$data['bread'] = $this->breadcrumbmanager->getLocalBreadcrumb($this->namemanager->getDashboardBreadName("0"), $city, $data['title'], $data['vacancydetails']);
}
//Set the location to the subdomain automatically (e.g. when the link is clicked) so the activities of that subdomain only show up
if (!empty(LOCATION)) {
$data['title'] = sprintf(lang('page_title_local_activities'), ucwords(LOCATION));
$data['description'] = sprintf(lang('meta_desc_local_activities'), ucwords(LOCATION));
$filterdata['location'] = LOCATION;
$data['bgcolor'] = $this->localSettings_model->getBgColorHexValueForOrgId($orgId->org_id);
}
if (!empty($filterdata['fulldate'])) {
$splitfromandto = explode(" - ", $filterdata['fulldate']);
$filterdata['datefrom'] = $splitfromandto[0];
$filterdata['dateto'] = $splitfromandto[1];
} else {
$filterdata['datefrom'] = null;
$filterdata['dateto'] = null;
}
//Put these variables in the data variable so we can prefill our filters again with the previous values
//This is necessary because we don't use AJAX yet
$data['filterdata'] = $filterdata;
//Pagination : We do it here so we can re-use the filter query to count all our results
$this->load->library('pagination');
$data['all_vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata);
$pagconfig['base_url'] = base_url().VACANCY_OVERVIEW;
$pagconfig['total_rows'] = count($data['all_vacancies']);
$pagconfig['per_page'] = 1;
$pagconfig['uri_segment'] = 2;
$pagconfig['use_page_numbers'] = TRUE;
$this->pagination->initialize($pagconfig);
$data['links'] = $this->pagination->create_links();
$start = max(0, ( $this->uri->segment(2) -1 ) * $pagconfig['per_page']);
//This variable contains all the data necessary for a vacancy to be displayed on the vacancy overview page
$data['vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata, false, null, false, null, false, false, $pagconfig['per_page'], $start);
// Template declaration
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/overview', 'footer' => '_master/footer/footer');
$data['vacancygrid'] = $this->load->view('dashboard/vacancy/vacancygrid', $data, TRUE);
$this->template->load('_master/master', $partials, $data);
}
As you can see in the code i keep a variable called $filterdata, this contains all data which is used in our filters, since we don't use AJAX in this version, we need to pass it to the view every time to fill it up again and present it to the visitor.
However, using pagination this breaks because it just reloads my controller method and thus the values in $filterdata are lost.
How do I go about this?
Note: it does not have to be a clean solution, it just needs to work since this page is going offline in a couple of weeks anyway.
Thanks a lot in advance!

Trying to learn Laravel. How do I create a separate "post" function using this "get" codes?

ManagementController.php
public function getDuplicate(Request $request)
{
$data = \App\Chalet::find( \Crypt::decrypt($request->input('cid')) );
if ( $data->group_id == Auth::user()->group->group_id ) {
$cid = \Crypt::decrypt($request->input('cid'));
$mid = Extras::getMeta( 'chalet_details', '\App\ChaletMeta', $cid, 'chalet_id', true );
$sid = Extras::getMeta( 'chalet_status', '\App\ChaletMeta', $cid, 'chalet_id', true );
$ciid = Extras::getMeta( 'chalet_images', '\App\ChaletMeta', $cid, 'chalet_id', true );
$arid = Extras::getMeta( 'auto_release_excemption', '\App\ChaletMeta', $cid, 'chalet_id', true );
$rchalet = \App\Chalet::find($cid);
$dup_chalet = $rchalet->replicate();
$dup_chalet->unit_no = '';
$dup_chalet->status = 0;
$dup_chalet->visibility = 1;
$dup_chalet->save();
$nCID = $dup_chalet->chalet_id;
$rmchalet = \App\ChaletMeta::find($mid);
$dupM_chalet = $rmchalet->replicate();
$dupM_chalet->chalet_id = $dup_chalet->chalet_id;
$dupM_chalet->save();
$archalet = \App\ChaletMeta::find($arid);
if ( $archalet ) {
$dupA_chalet = $archalet->replicate();
$dupA_chalet->chalet_id = $dup_chalet->chalet_id;
$dupA_chalet->save();
}
$schalet = \App\ChaletMeta::find($sid);
$dupSChalet = $schalet->replicate();
$dupSChalet->chalet_id = $dup_chalet->chalet_id;
$dupSChalet->save();
$cichalet = \App\ChaletMeta::find($ciid);
$dupCIChalet = $cichalet->replicate();
$dupCIChalet->chalet_id = $dup_chalet->chalet_id;
$dupCIChalet->save();
return Redirect::to(Auth::user()->group->alias.'/app/echalet/view/?cid=' . \Crypt::encrypt($nCID) .'&action=view')->with('message', Extras::alert('success', 'Successful Duplicated Chalet! Please enter Unit #.'))->with('duplicate', true);
} else {
return Redirect::to( Auth::user()->group->alias.'/app/echalet' )->with('message', Extras::alert( 'error', "Something went wrong, Didn't managed to duplicate chalet" ));
}
}
This "get" function creates a duplicate of an item after clicking the button that says "duplicate". I wish you guys can help me point out which part of the code should I remove so I can make a separate "post" function.
This code replicates the ChatletMeta model and returns a message. If you want to modify the method(GET/POST) this function can be called, you need to modify the route belonging to this Controller/action.
Also, you can remove the Model replications.

showing my models value on view in codeigniter

im new in codeigniter and get some trouble with my function
here is my model
public function kode_unik(){
$q = $this->db->query("select MAX(RIGHT(id_obat,5)) as code_max from obat");
$code = "";
if($q->num_rows()>0){
foreach($q->result() as $cd){
$tmp = ((int)$cd->code_max)+1;
$hitung = strlen($tmp);
if ($hitung == 1 ){
$a = "0000".$tmp;
} elseif ($hitung == 2) {
$a = "000".$tmp;
}elseif ($hitung == 3) {
$a = "00".$tmp;
}elseif ($hitung == 4) {
$a = "0".$tmp;
}else{
$a = $tmp;
}
$code = sprintf("%s", $a);
}
}else{
$code = "0001";
}
$kodenyami = "E".$code;
return $kodenyami;
}
and then i wanna get the result of my models to show in my view.
here is my controller
public function add_data()
{
$this->load->helper( array('fungsidate', 'rupiah', 'url') );
$this->load->model('obat');
$this->load->database();
$data['a'] = $this->obat->tampil_data();
$data['b'] = $this->obat->kode_unik();
$componen = array(
"header" => $this->load->view("admin/header", array(), true),
"sidebar" => $this->load->view("admin/sidebar", array(), true),
"content" => $this->load->view("admin/add_obat", array("data" => $data), true)
);
$this->load->view('admin/index', $componen);
}
and my view goes here.
<i class="fa fa-medkit fa-5x"></i></div>
<div class="col-xs-9 text-right">
line20-> <div class="huge"><?php echo $b; ?></div>
<div>ID Obat</div>
the code give me an errors Message: Undefined variable: b
just don't know how to put the value of my models $kode_unik into my view ..
thanks
$data is already an array. Maybe like this :
"content" => $this->load->view("admin/add_obat", $data, TRUE)
CodeIgniter will extract the keys in $data so you will be able to use them in your view as $b
BTW instead of passing array() as a parameter of the load->view you can use NULL
P.S If you set the last parameter to TRUE, you will return the populated content of that view as a String (HTML in that case)
Here is something to start with :
public function __construct() {
parent::construct();
$this->load->helper(‘array(‘fungsidate’, ‘rupiah’, ‘url’);
$this->load->model(‘obat’);
$this->load->database(); // Should be already loaded depending on your config
}
public function add_data() {
// Set the data
$data[‘a’] = $this->obat->tampil_data();
$data[‘b’] = $this->obat->kodeunik();
// Load the views
$componen = array(
‘header’ => $this->load->view(‘admin/header’, NULL, TRUE);
‘sidebar’ => $this->load->view(‘admin/sidebar’, NULL, TRUE);
‘content’ => $this->load->view(‘admin/add_obat', $data, TRUE);
);
$this->load->view(‘admin/index’ ,$componen);
}
From what I understand about your code, in your templates you will need to echo the array keys
in admin/header you will echo $header;
in admin/sidebar you will echo $sidebar;
in admin/add_obat you will need to echo $content
and then you admin/index should be populated. I won’t do that if I were you to be honest I would probably load each template as is instead of outputting them as HTML string inside the final index. I don’t know exactly how you did your structure so it’s kinda hard for me to guess well. But in my case I would have use something like this instead of the componen array
public function add_data() {
// Set the data
$data[‘a’] = $this->obat->tampil_data();
$data[‘b’] = $this->obat->kodeunik();
// Load the views
$this->load->view(‘admin/header’);
$this->load->view(‘admin/sidebar’);
$this->load->view(‘admin/add_obat, $data); // This should be the body template of your page
$this->load->view(‘admin/footer’); // I guess you have a footer template
}
I hope this will help you!

PDO Update 1 column multiple rows with array

I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

codeigniter - calling two functions from same controller one after the other, second function fails

This one's got me stuck!
I have two functions in a controller which can be called from a menu independantly and they work fine.
I want to call them in a month end routine (in the same controller), one after the other; the first function works fine and returns to the calling function, the second function is called but fails because the load of the $model variable fails.
Here is the code for the month end routine,
function month_end_routines()
{
// create stock inventory valuation report in excel format
$export_excel = 1;
$this -> inventory_summary($export_excel);
// create negative stock
$export_excel = 1;
$this -> inventory_negative_stock($export_excel);
echo 'debug 2';
// reset rolling inventory indicator
$this -> load->model('Item');
$this -> load->library('../controllers/items');
$this -> items->reset_rolling();
}
Here is the code for the first function called inventory_summary,
function inventory_summary($export_excel=0, $create_PO=0, $set_NM=0, $set_SM=0)
{
// load appropriate models and libraries
$this -> load->model('reports/Inventory_summary');
$this -> load->library('../controllers/items');
// set variables
$model = $this->Inventory_summary;
$tabular_data = array();
$edit_file = 'items/view/';
$width = $this->items->get_form_width();
$stock_total = 0;
// get all items
$report_data = $model->getData(array());
foreach($report_data as $row)
{
$stock_value = $row['cost_price'] * $row['quantity'];
$stock_total = $stock_total + $stock_value;
// set up the item_number to handle blanks
if ($row['item_number'] == NULL) {$row['item_number'] = $this->lang->line('common_edit');}
$tabular_data[] = array (
$row['category'],
anchor (
$edit_file.$row['item_id'].'/width:'.$width,
$row['item_number'],
array('class'=>'thickbox','title'=>$this->lang->line('items_update'))
),
$row['reorder_policy'],
$row['name'],
$row['cost_price'],
$row['quantity'],
$stock_value,
$stock_total
);
}
$today_date = date('d/m/Y; H:i:s', time());
$data = array (
"title" => $this->lang->line('reports_inventory_summary_report'),
"subtitle" => ' - '.$today_date.' '.$this->lang->line('common_for').' '.$this->db->database.'.',
"headers" => $model->getDataColumns(),
"data" => $tabular_data,
"summary_data" => $model->getSummaryData(array()),
"export_excel" => $export_excel
);
if ($export_excel == 1)
{
$this->load->model('Common_routines');
$this->Common_routines->create_csv($data);
}
else
{
$this->load->view("reports/tabular", $data);
}
return;
.. and here is the code for the second function,
function inventory_negative_stock($export_excel=0, $create_PO=0, $set_NM=0, $set_SM=0)
{
echo 'debug 1.5';
$this -> load->model('reports/Inventory_negative_stock');
$this -> load->library('../controllers/items');
echo 'debug 1.6';
$model = $this->Inventory_negative_stock;
var_dump($model);
$tabular_data = array();
$edit_file = 'items/view/';
$width = $this->items->get_form_width();
echo 'debug 1.7';
$report_data = $model->getData(array());
echo 'debug 1.8';
foreach($report_data as $row)
{
// set up the item_number to handle blanks
if ($row['item_number'] == NULL) {$row['item_number'] = $this->lang->line('common_edit');}
// load each line to the output array
$tabular_data[] = array(
$row['category'],
anchor (
$edit_file.$row['item_id'].'/width:'.$width,
$row['item_number'],
array('class'=>'thickbox','title'=>$this->lang->line('items_update'))
),
$row['name'],
$row['cost_price'],
$row['quantity']
);
}
// load data array for display
$today_date = date('d/m/Y; H:i:s', time());
$data = array (
"title" => $this->lang->line('reports_negative_stock'),
"subtitle" => ' - '.$today_date.' '.$this->lang->line('common_for').' '.$this->db->database.'.',
"headers" => $model->getDataColumns(),
"data" => $tabular_data,
"summary_data" => $model->getSummaryData(array()),
"export_excel" => $export_excel
);
if ($export_excel == 1)
{
$this->load->model('Common_routines');
$this->Common_routines->create_csv($data);
}
else
{
$this->load->view("reports/tabular", $data);
}
return;
}
This line is failing
$model=$this->Inventory_negative_stock;
In the first function $model is loaded correctly. In the second it isn't.
It does not matter in which order these functions are called; $model always fails to load in the second function called.
Any help would be great and thanks in advance. I hope I've given enough code; if you need more information let me know.
As requested, here is the code in Inventory_negative_stock,
<?php
require_once("report.php");
class Inventory_negative_stock extends Report
{
function __construct()
{
parent::__construct();
}
public function getDataColumns()
{
return array (
$this->lang->line('reports_category'),
$this->lang->line('reports_item_number'),
$this->lang->line('reports_item_name'),
$this->lang->line('reports_cost_price'),
$this->lang->line('reports_count')
);
}
public function getData(array $inputs)
{
$this->db->select('category, name, cost_price, quantity, reorder_level, reorder_quantity, item_id, item_number');
$this->db->from('items');
$this->db->where("quantity < 0 and deleted = 0");
$this->db->order_by('category, name');
return $this->db->get()->result_array();
}
public function getSummaryData(array $inputs)
{
return array();
}
}
?>

Categories