Template in codeigniter - php

I am trying to develop a website using a templating method I have created different files and would like to run a query and that query would be available on all templates is it possible to do that? Like I would like to give you an example what I am doing here in the controller I have created a variable like this
$data['navigation'] = 'templates/main_menu';
$this->load->view('main');
Okay so now here what I did in the view of main is I included header and footer there and called the navigation file dynamically like this
$this->load->view($navigation);
Okay so now What I am trying to do is want to get an icons stored in database and other settings as well so I placed a query in the header file
<?php $settings = $this->db->get_where('settings', array('id' => 2));\\ This query is just placed above the doctype in the header file and I would like to be called every where ?>
templates/main_menu.php
$settings->row()->header_bg_color
But I am getting an error as Message: Undefined variable: settings and if i place this settings query within the main_menu.php file it works so like what should be the way i mean it does not make sense to call the query again and again if I would be requiring what will be the best way to do and what is tthe use of model would it be used for the queries if it is then if I place this settings query within the model how would I access it is it possible please advise me
Thank you

hi below is code of controller. i have created the common_library.php file in which i have written all common function that I want to use all views.
class Maintenance extends CI_Controller {
function Maintenance() {
parent::__construct();
// file for all common function
include('application/controllers/common/common_library.php');
$this->load->model('maintenance_model');
$this->load->library('session');
$this->load->library('form_validation');
}
function index(){
/*
* # desc : default function that loads the maintenance_view.
*
*
*/
$data['common_query'] = commonQuery() // define this function in common_library file
$data['model_data'] = $this->maintenance_model->projectdetail();
$data['formtitle'] = 'Maintenance List | BMS';
$this->load->view('maintenance_view',$data);
}
}

Related

Codeigniter Front End Controller Not working with libraries

I'm posting this after my hair has been ripped out, ran out of rum, and tried everything I can find on google. I've been developing a site using codeigniter which makes use of templates. I've built the backend first and all is working properly there. So now i've started on getting the front end working which is where I'm hitting the issue.
I've created a controller called pages.php which is going to parse the uri string of the current page, use my library to get the page data from the database, then display it. My pages are all created through an editor on the back end and stored in the database.
So here's the pages controller
class Pages extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library("pages");
}
public function display_page()
{
$page_slug = $this->uri->segment(1);
$data["joes"] = "Here's joes first variable";
$this->pages->get_page($page_slug);
}
}
and here's the error message i get when i hit my url like this demo.mydomain.com/joes-test
and here is how my routes are set up. $route['(:any)'] = 'pages/display_page';
My Pages.php library works perfect on the back end but it's a large file. I've only posted the get_page function below. If you need to see everything let me know. But i dont believe the issue has anything to do with the library itself.
public function get_page($slug){
$objPages = new pages();
$objPages->get_object('slug="'.$slug.'"');
return $objPages;
}
[EDIT] If i place the following inside my homepage controller it works. But the calling function needs to be inside the library.
$this->load->library('pages');
$the_page = $this->pages->get_page("joes-test");
I want to call $this->get_object("joes-test") but this doesn't work. get_object() is an inherited function inside the library.
Now oddly enough. The code i put above will NOT work if i do the exact same thing inside the pages controller
any help leading to a solution would be awesome. I'm under a time crunch and pay to get some assistance. Thanks in advance.
No you can't use the same name with controller and library. please choose another name. for example Mypages for you controller name.
change your routes
$route['(:any)'] = 'mypages/display_page';
then call your controller.
http://demo.mydomain.com/joes-test
I think there nothing wrong with library uri, because as codeigniter official website say: This class is initialized automatically by the system so there is no need to do it manually.
I don't know about lib pages, but how about use
$this->load->view(<file-html>);
and if you want to passing data in variable, you can add variable like this
$this->load->view(<file-html>, $data);
Hope this help, Cheers

Codeigniter multilanguage on controller

I'm using codeigniter multilanguage and it works fine. The problem is when I try to do multilanguage in the URL... how can I do it?
I mean the controller has to be a file, with a name, and its functions too... so I can't figure how can I do it.
The only alternative I thought is create the same controllers for each language I need... but this is a lot of repeated code just for change the name of the controller and functions... and the maintenance will be a big trouble.
Any help?
Pass the language indicator as a "GET" value to your controller functions:
eg.
base_url/controller/inventory/en
Then use it like this in your controller:
/**
* #desc This will get called when no method specified
* Will show home page (list of items)
*/
function inventory($lang="en",$from=0){
// load proper language file
$this->lang->load('language_filename', $lang);
// generate db where clause
$where = array(
"published"=>"1",
"language"=>$lang
);
// paging
$this->_setPagingLinks($this->newsModel->getTotalRecordsNumber($where),10,4,"inventory/".$lang,$lang);
// loading items from db
$this->data["news"] = $this->newsModel->getRecords($where,$from,10,"time");
// load the view according to language
$this->data["content"] = $this->load->view("$lang/news",$this->data,TRUE);
$this->load->view("$lang/container",$this->data);
}

Unexpected behavior by CodeIgniter while loading views

I have a viewer helper function that loads the main content alongside the footer/header. The bug/unexpected behavior occurred when I loaded the array's key for the header that shares the same name for a variable in the main content view - the same array is loaded for both the header and main content.
I thought it's normal, since the same $data array was sent to the header and main content as-well(as mentioned before). So the variable will naturally be present in both views. But, well, it wasn't exactly like that. I unset the $data variable after sending the data to the header then re-created it when I wanted to send some data to the main view - but still the problem is not fixed.
I made a simple example for this bug/unexpected behavior:
Consider this view, named test:
<?php
echo $some_data;
And this controller:
class Test extends CI_Controller {
function index() {
$data['some_data'] = 'Some data.';
$this->load->view('test', $data);
/*
* Output:
* Some data.
*/
unset($data);
unset($data['some_data']);//Just to make sure it's not PHP's fault.
$this->load->view('test');
/*
* Output:
* Some data.
*
* Even though the $data variable is unsetted AND not passed!
*/
$different_data = array();
$this->load->view('test', $different_data);
/*
* Output:
* Some Data.
*
* Still outputs the same thing, even though
* I'm sending different array(and the $data array is unstted).
*
*/
}
}
Note: The whole code will output Some data. three times.
The only way to solve this issue is sending a different array and setting the array key(which is some_data) to something else which will override the old one.
So, is this a bug or something made by CodeIgniter's dudes?
we had the same problem like you and our Alien coworker found THE solution:
if file: codeigniter\system\core\Loader.php
find the code: (i think the line number is 806):
$this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
and correct it to:
$this->_ci_cached_vars = $_ci_vars;
best regards
This is expected behavior.
Once variables are set they become available within the controller class and its view files. Sending an array in $this->load->view() is the same as sending an array directly to $this->load->vars() before calling the view file. This simplifies things for most people using multiple views in a controller. If you are using multiple view files in a single controller and want them to each have their own set of variables exclusively, you'll need to manually clear out the $this->load->_ci_cached_vars array between view calls.
A code comment in the Loader class describes another situation showing why this is the desired default behavior:
//You can either set variables using the dedicated $this->load_vars()
//function or via the second parameter of this function. We'll merge
//the two types and cache them so that views that are embedded within
//other views can have access to these variables.
This is a CodeIgniter issue. The variables you are sending in seems to be cached until you override them. I have encountered this myself and can verify it.
$this->load->view('test', array('some_data' => NULL));

Query caching in CodeIgniter

I want to cache a query in CodeIgniter. What I did for my test is make a controller, that I named show.php:
class Show extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('rejaal_show');
}
public function _remap($method = '',$param = array())
{
$method = intval($method);
$this->output->cache(5);
var_dump ($this->rejaal_show->temp($method));
}
}
And a model that I named rejaal_show.php:
public function temp($id)
{
$this->db->cache_on();
$this->db->where('id',$id);
$query = $this->db->get('system_store_table');
return $query->result();
}
When I call http://localhost/rejaal/show/1 for the first time, it will show a result, but when I call it for the second time, it does not show anything.
I should delete the query cache file to show it again? How should I solve this problem?
With special thanks for your attention.
Can you confirm that you have set $db['default']['cachedir'] to the path of a writable folder in application/config/database.php and that when the query is first run it creates a cache file in there?
The only other reason I can think of for it failing is by your use of the _remap override. I have not used db caching using _remap, but know that CodeIgniter creates a folder called controller+action in your cache folder, and might not be handled very well if using remap? Someone correct me if I am wrong about this.
In the CodeIgniter User Guide page for Web Page Caching, it says:
Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for your controller with a view.
Do your var_dump inside a view.

CodeIgniter default layout problem: How can i create a default layout for whole project in CodeIgniter_2.0.2?

I want to create a default layout for whole codeigniter project. (like cakephp)
I also need to pass value from database (through controller) to default layout.
How can i do this ?
You can use the hooks to achieve this
post_controller - You can set vars with this.
Called immediately after your controller is fully executed.
display_override - You can override display and include your own view.
Overrides the _display() function, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI->output->get_output()
reference : http://codeigniter.com/user_guide/general/hooks.html
You can consider using a template system. For example Template library
The CodeIgniter wiki is a great place to look for this type of help.
For example, here are four different approaches to achieve what you want to do.
Actually there's a very simple solution that you can use. This is a micro-library that I have written for using layouts in CodeIgniter :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Layout {
protected $CI;
public function __construct() {
$this->CI =& get_instance();
}
/**
* This method loads either the default layout (defined in the config.php file with the key default_layout) or a specific layout
* #param string $view
* #param array $params
* #param string $layout
*/
public function load_layout($view, $params = array(), $layout = "") {
// get the name of the layout file
$layout_file = file_exists(dirname(__FILE__) . "../views/" . $layout) ? $layout : $this->CI->config->item("default_layout");
// load it, transmit the params
$this->CI->load->view(
$layout_file,
array(
"view_name" => $view,
"view_params" => $params
)
);
}
?>
Add this file to your project in a Layout.php file, then just go to your config file and add the following line :
$config['default_layout'] = "your-default-layout-name.php";
And finally create a new file into the application/views folder of your project and name it with the value you put into your config file i.e. your-default-layout-name.php. Paste all the contents of the basic structure of your pages and add in the main wrapper :
<?php
// load required view
if (isset($view_name)) {
$this->load->view(
$view_name, $view_params
);
}
?>
Okay ! now you can simply replace the native :
$this->load->view("view-name.php", $params);
by :
// load the default layout
$this->layout->load_layout("view-name.php", $params);
// load a specific layout
$this->layout->load_layout("view-name.php", $params, "my-specific-layout.php");
And it will work like a charm !
Note: do not forget to include the library, either in you autoload.php file or directly in your script.

Categories