I want to make my logo global so that I can access it anywhere in my website. For that I am declaring $logo in a custom parent controller MY_Authorization and every class is extended by this custom controller.
but when i call the $logo variable in my view a php error occurs that undefined variable: $logo
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Authorization extends CI_Controller {
var $logoCont='logo';
function __construct()
{
parent::__construct();
$CI = & get_instance();
$CI->load->library('session');
$CI->load->helper('url');
if ( !$this->session->userdata('loginuser'))
{
redirect('login');
}
}
}
In my view i am calling logo like this
<img src="<?php echo base_url().sprintf("uploads/%s", $logoCont)?>"alt="logo">
Create custom helper file and placed in helper folder
Navigate to application/helper
List item
Create a new custom file
example : my_custom_helper.php
function logo(){
$ci = & get_instance();
$result = $ci->db->query("you custom query here");
//fetch the logo from database and store in the variable and return this variable
return $result;
}
autoload this helper in autoload.php file at (application/config/autoload.php)
find the variable $autoload['helper'] = array();
add your custom helper there like $autoload['helper'] = array('my_custom_helper.php);
Now the logo() function is global and it will available everywhere in controller/model/view ,and whenever change made in helper function it will be affect the application where logo() function is used.
Your data is not being passed on to the view.
if ( !$this->session->userdata('loginuser'))
{
---added this---
$this->session->set_flashdata('item', 'value');
// OR $this->session->set_flashdata($data); $data is of type array
----------------
redirect('login');
}
Now your data is set in the session (and will be removed after the next request), you can access this data in the view by using $this->session->flashdata('item').
https://codeigniter.com/user_guide/libraries/sessions.html#flashdata
Hope this helps.
Related
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?
I am trying to get scroll news in any page of the website from database without having to pass the variable in every controller of the site. So I decided to use hooks instead of passing scroll variable in every controller.
I did create a class like this
class Scroll
{
function getScroller()
{
$data = array();
$CI =& get_instance();
$CI->db->where('a_status','active');
$CI->db->limit(4);
$CI->db->order_by('id','desc');
$Q = $CI->db->get('news');
if($Q->num_rows() > 0){
foreach($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
}
What I get now is
Severity: Notice
Message: Trying to get property of non-object
Call to a member function get() on a non-object in E:\xampp\htdocs\
Can anyone please help me how to do this ? Thanks I want to get scrollernews in any controller's view automatically without having to pass in each controller. Thanks
If you are defining that on a view level, there is no need for that.
You can define db requests directly in a view.
Other approach would be to have separated controller which with separate view and load it in the page through iframe. It's often used for "web widgets" that can be later on loaded in to another pages.
Extending the core class of CI Controller will should cause you less troubles.
http://ellislab.com/codeigniter/user-guide/general/core_classes.html
application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
//By do this, all controllers who use this class as parent controller
//will have $news in their views
$this->load->vars(array(
'news' => array()
));
}
}
application/controller/welcome.php
class Welcome extends MY_Controller {
public function index()
{
$this->load->view('welcome_message');
}
}
application/views/welcome_message.php
var_dump($news);
use separated library or helper and call that method on controller's constructs like :
class My_Controller extends CI_Controller(){
function __construct(){
parent::__construct();
//load your library
//call your library method
}
}
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>