I make simple template use code codeigniter.
my code like this.......
This is template.php class
class Template {
protected $_ci;
function _construct() {
$this->_ci=&get_instance();
}
function display($template, $data = null) {
$data['_content'] = $this->_ci->load->view($template, $data, TRUE);
$data['_header'] = $this->_ci->load->view('template/header', $data, TRUE);
$data['_top_menu'] = $this->_ci->load->view('template/menu', $data, TRUE);
$data['_right_menu'] = $this->_ci->load->view('template/sidebar', $data, TRUE);
$this->_ci->load->view('/template.php', $data);
}
}
and this is my controller welcome.php class
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct() {
parent::__construct(); //you always have to call parent's constructor before ANYTHING
$this->load->library('template');
$this->load->helper('url');
}
public function index() {
$this->template->display('welcome_message');
}
function contoh_parameter() {
$this->template->display('view_parameter', array('judul' => 'Judul View'));
}
}
and this is my view class, welcome_message.php class
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.</p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
But I get error like this :
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: libraries/template.php
Line Number: 25
Sorry I am still a newbie in codeigniter and php. Please help me.
First of all your construct method isn't right it should be __construct instead of _construct
Second you use $this->_ci->load->view('/template.php', $data); when you load a view you shouldn't use any slash at the beginning path up to view directory is available to CI. So if your view file is template.php in CI view folder then use it in this way $this->_ci->load->view('template', $data);. Also you use .php extension CI self adds that extension.
Related
I am learning CI and I'm trying to do this tutorial where you fetch data. My browser is just dumping this and nothing else
{entries}
{id}
{title}
{news}
{/entries}
Can you please help me figure this out? I'm pretty sure it has to do with my parser in the controller file
now this is my view:
<head>
<title>News Blog</title>
</head>
<body>
{entries}
<p>{id}</p>
<h3>{title}</h3>
<p>{news}</p>
{/entries}
</body>
Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class NewsModel extends CI_Model {
public function __construct() {
$this->load->database();
}
public function getNews($slug = FALSE){
$query = $this->db->get('news');
return $query->result_array();
}
}
and controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class News extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('newsModel');
}
public function index() {
$news = $this->NewsModel->getNews();
// I believe the issue is in the next few lines
$data['contactjs']=$this->parser->parse('templates/Javascript/contactjs',[],TRUE);
$data['bootCSS']=$this->parser->parse('templates/CSS/bootCSS',[],TRUE);
$data['CSS']=$this->parser->parse('templates/CSS/CSS',[],TRUE);
$data['jQuery']=$this->parser->parse('templates/Javascript/jQuery',[],TRUE);
$data['bootstrap']=$this->parser->parse('templates/Javascript/bootstrap',[],TRUE);
$template = '{id} {title} {news}';
$newsData = array('entries'=> $news);
$newsData = $this->parser->parse('pages/news', [], TRUE);
$data['news'] = $this->parser->parse('pages/news', $news, TRUE);
$this->load->view('templates/header', $data);
$this->load->view('pages/news');
$this->load->view('templates/footer');
}
}
Did you load the parser library? Try to output the $news variable, see if it contains some data. Also, check your application/log folder for more information. Maby there is a php error you're not seeing.
Next line of code should load your pages/news view just like any other view without the parser:
$this->load->view('pages/news'); // This view doesn't contain any parsed data now
I think you should create a temp variable and place all the data of all parsed views into it. Then load it in a view. To check, try to output the last variable and see if it contains any data like so;
echo "<pre>"; print_r($data['news']);
How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.
You can call controller function from view in the following way:
Controller:
public function read() {
$object['controller'] = $this;
$this->load->view('read', $object);
}
View:
// to call controller function from view, do
$controller->myOtherFunct();
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You can call a controller function with AJAX on your view.
In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
I would like to answer this question as this comes all times up in searches --
You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.
Your controller may be like below class --
<?php
class VCI_Controller extends CI_Controller {
....
....
function abc($id){
return $id ;
}
}
?>
Now You can call this function in view files as below --
<?php
$CI =& get_instance();
$CI->abc($id) ;
?>
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Try this one.
Add this code in Your View file
$CI = & get_instance();
$result = $CI->FindFurnishName($pera);
Add code in Your controller File
public function FindFurnishName($furnish_filter)
{
$FindFurnishName = $this->index_modal->FindFurnishName($furnish_filter);
$FindFurnishName_val = '';
foreach($FindFurnishName as $AllRea)
{
$FindFurnishName_val .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');
}
where
FindFurnishName is name of function which is define in Your Controller.
$pera is a option ( as your need).
One idea i can give is,
Call that function in controller itself and return value to view file. Like,
class Business extends CI_Controller {
public function index() {
$data['css'] = 'profile';
$data['cur_url'] = $this->getCurrURL(); // the function called and store val
$this->load->view("home_view",$data);
}
function getCurrURL() {
$currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
return $currURL;
}
}
in view(home_view.php) use that variable. Like,
echo $cur_url;
views cannot call controller functions.
I know this is bad..
But I have been in hard situation where it is impossible to put this back to controller or model.
My solution is to call a function on model.
It can be do inside a view.
But you have to make sure the model has been loaded to your controller first.
Say your model main_model, you can call function on the model like this on your view :
$this->main_model->your_function();
Hope this help. :)
We can also pass controller function as variable in the view page.
class My_controller extends CI_Controller {
public function index() {
$data['val']=3;
$data['square']=function($val){
return $val*$val;
};
$this->load->view('my-view',$data);
}
}
In the view page
<p>Square of <?=$val?>
<?php
echo $square($val);
?>
</p>
The output is 9
it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}public function pledge_ph(){
$this->script->phpledge();
}
}
?>
This is the controller class Iris.php
and the model class with the function pointed to from the controller class.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
public function __construct() {
parent::__construct();
// Your own constructor code
}public function ghpledge(){
$gh_id = uniqid(rand(1,11));
$date=date("y-m-d");
$gh_member = $_SESSION['member_id'];
$amount= 10000;
$data = array(
'gh_id'=> $gh_id,
'gh_member'=> $gh_member,
'amount'=> $amount,
'date'=> $date
);
$this->db->insert('iris_gh',$data);
}
}
?>
On the view instead of a button just use the anchor link with the controller name and method name.
<html>
<head></head>
<body>
PLEDGE PH
</body>
</html>
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
I know this question is old but it is still a relevant question. From my experience there are situations that warrant calling a function from view in your Codeigniter 4 app, I'll just advise that you keep it clean and minimal. Below is how I have called controller function from view:
In your controller file add this code
public function index()
{
$data = [];
$model = new UsersModel();
$data['users'] = $model->findAll();
// $this refers to the controller to be called from view
$data['callfromview'] = $this;
return view('users', $data)
}
In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>
Finally in the controller, create the fetch_data function
public function fetch_data($id)
{
$image = new ImageModel();
return $image->find($id);
}
the END!
if you need to call a controller from a view,
maybe to load a partial view,
you thinking as modular programming,
and you should implement HMVC structure in lieu of plane MVC.
CodeIgniter didnt implement HMVC natively,
but you can use this useful library in order to implement HMVC.
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup
remember:that all your controllers should extends from MX_Controller in order to using this feature.
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>
I'm new to codeigniter and I have two controllers: utility.phpand welcome.php.
In utility.php, I have functions:
function getdata() {
//code here
}
function logdata() {
//code here
}
Inside welcome.php, I have this function:
function showpage() {
//some code here
//call functions here
}
What I want to do is inside my welcome.php, I want to call the functions from utility.php. How do I do this? Thanks.
Refrence from here
To extend controller please either follow this tutorial or see some code below.
differences between private/public/protected
make a file in folder /application/core/ named MY_Controller.php
Within that file have some code like
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data = Array(); //protected variables goes here its declaration
function __construct() {
parent::__construct();
$this->output->enable_profiler(FALSE); // I keep this here so I dont have to manualy edit each controller to see profiler or not
$this->load->model('some_model'); //this can be also done in autoload...
//load helpers and everything here like form_helper etc
}
protected function protectedOne() {
}
public function publicOne() {
}
private function _privateOne() {
}
protected function render($view_file) {
$this->load->view('header_view');
if ($this->_is_admin()) $this->load->view('admin_menu_view');
$this->load->view($view_file . '_view', $this->data); //note all my view files are named <name>_view.php
$this->load->view('footer_view');
}
private function _isAdmin() {
return TRUE;
}
}
and now in any of yours existing controllers just edit 1st or 2nd line where
class <controller_name> extends MY_Controller {
and you are done
also note that all your variables that are meant to be used in view are in this variable (array) $this->data
example of some controller that is extended by MY_Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->data['today'] = date('Y-m-d'); //in view it will be $today;
$this->render('page/about_us'); //calling common function declared in MY_Controller
}
}
You don't is the short answer.
The point of MVC is to have your code well organized.
What you can do though is create a library in the libraries folder where you put methods you need in more than one controller.
For example you can make a mylog library, where you can put all your log related stuff. In any controller you will then call:
$this->load->library('mylog');
$this->mylog->logdata();
Besides functions that deal with data models should reside in models. You can call any model from any controller in CI
That is out of concept, if you want to call code in different controllers do following:
create helper and call function whenever (even in view) you want.
extend CI_Controller so you can use one or more functions in any controller that is extended.
Lets start with helper:
create file in folder application/helpers/summation_helper.php
use following sample of code
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function sum($a, $b) {
//$CI =& get_instance();
// if you want to use $this variable you need to get instance of it so now instead of using $this->load... you may use $CI->load
$return = $a + $b;
return number_format($return, 3);
}
If you are going to use your helper in many controllers/views please load it in autoload, otherwise just load it manualy $this->load->helper('summation');
Extending Controller_CI: this is way better approach if you are using database. Please follow this tutorial, which explains it all.
*I have crafted an answer just before site went down posting this from cellphone.
I am a newbie in Codeigniter. I am doing a project in which in every pages, I would like to include a drop down for showing multi-languages. For this, I am including a view file in one of the view file in another controller as:
<?php $this->load->view('language/alllang');?>
In alllang.php, I would like to include the code for displaying drop down. For this I have created a controller LanguageController with the following code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Language extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
}
function alllang()
{
$data['val']="hhh"; // for testing
$this->load->view('alllang',$data);
exit;
}
}
Code for alllang.php is:
<?php
echo $val;
?>
But I am getting an error like this:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: val
Filename: language/alllang.php
Line Number: 2
This code is only for testing purpose (not the code for multilanguage). How can I set the value to be included in view file from controller.
Edited for database access functionality:
You could just create a library file and save it in application/libraries, call it "language_lib.php":
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Language_lib{
function __construct(){
$this->CI =& get_instance();
}
function lang_dropdown(){
//db queries:
$q = $this->CI->db->select('*')->from('table')->get()->result_array();
$html = … //your dropdown code here using $q
return $html;
}
}
Next, in application/config/autoload.php:
$autoload['libraries'] = array('language_lib');
Now in each controller method that needs the drop down, e.g. the index method:
function index(){
$data['dropdown'] = $this->language_lib->lang_dropdown();
$this->load->view('some_view', $data);
}
You can access this in the view with <?php echo $dropdown; ?>
Your explanation is a bit confusing, but by doing this
$this->load->view('language/alllang');
You're not calling a controller, you're calling a view only, without passing any data. If I get it right, you have a parent view, then inside it you'd like to call a language drop down view? Well, in this case a drop down view should be called with data array, and data should be coming from controller calling a parent view. Does it make sense?
Consider my code:
<?php
class MY_Controller extends Controller {
public function __construct()
{
parent::Controller();
}
function _displayPage($page, $data = array()) {
$this->load->view('structure/header', $data);
$this->load->view($page, $data);
$this->load->view('structure/footer', $data);
}
}
?>
page.php
<?php
class Page extends MY_Controller {
function __construct() {
parent::__construct();
}
function index() {
$data['content'] = array('title'=>'hello world');
$this->_displayPage('home', $data);
}
}
?>
Upon loading my page on my browser, I get this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Page::$view
Filename: libraries/MY_Controller.php
Line Number: 11
Does anyone know what I'm doing wrong?
Thanks
In your library My_Controller you should be using the parent keyword instead of $this.
your code should look like so:
class MY_Controller extends Controller
{
public function __construct()
{
parent::Controller();
}
function _displayPage($page, $data = array())
{
parent::load->view('structure/header', $data);
parent::load->view($page, $data);
parent::load->view('structure/footer', $data);
}
}
If I understand what you're trying to accomplish correctly, you're wanting to setup a template that includes your header view and footer view, but without calling header and footer views for each controller you use throughout your application. Here's what I've done to accomplish this.
First, create a new folder under your views, for this example we'll call it 'includes'. Inside the newly created includes folder, create three files, header.php, footer.php and template.php. Setup your header and footer appropriately and then edit your template.php to look as follows:
<?php echo $this->load->view('includes/univ_header'); ?>
<?php echo $this->load->view($main_content); ?>
<?php echo $this->load->view('includes/univ_footer'); ?>
Now, from your controller you can define what view you would like to set as your 'main_content'. For example, if you have home.php in your views folder and you want to wrap it with your header and footer you would do so in your controller as follows:
function index() {
$data['content'] = array('title'=>'hello world');
$data['main_content'] = 'home';
$this->load->view('includes/template', $data);
}
Hope this helps!