Related
Is there a way in plates php where I can make a template in a controller but render it using another controller. Say I have two controllers. HeaderController and a SearchController.
SearchController
class Search extends \system\core\BaseController
{
public function Index()
{
$data['text_search'] = 'Search..';
// This $this->template->render down below is what I don't want now
// okay asign the data but do not display the template yet
echo $this->template->render('common/search', $data);
}
}
The dummy SearchController should assign $data to the template search.tpl but not render/display the template.
This is where I will be calling the above controller
HeaderController
class HeaderController extends \system\core\BaseController
{
public function Index()
{
// Some codes
// Call / load the SearchController and asign it to $data['search']
$data['search'] = $this->load->controller('common/SearchController');
// and then pass all $data and render/display it.
echo $this->template->render('common/header', $data);
}
}
Is there a way of doing it?
The issue actually comes from the fact, that you are using echo within your class. If your "controllers" (well, they actually seem to be a combination of view and controller) were to return either the content or Response class instance, then you problem should disappear.
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 want to load a controller from a function in another controller because the library I integrated to my project I don't want to load it to the controller because I want to keep it clean and related.
I tried using modules but I still had to put controller in the url like
http://example.com/maincontroller/function
http://example.com/othercontroller/function
I have default controller so I can load http://example.com/function so how could I access the controller from a function from main so I don't have to put the controller in the url.
I'm still willing to use HMVC if I can load the controller function from the main controller function.
yes you can (for version 2)
load like this inside your controller
$this->load->library('../controllers/whathever');
and call the following method:
$this->whathever->functioname();
You can't load a controller from a controller in CI - unless you use HMVC or something.
You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.
UPDATE
After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.
If this is the case, you'd get a cleaner solution by getting creative with your routes.
For a really basic example, say you have two controllers, controller1 and controller2. Controller1 has a method method_1 - and controller2 has a method method_2.
You can set up routes like this:
$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";
Then, you can call method 1 with a URL like http://site.com/method_1 and method 2 with http://site.com/method_2.
Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.
You could also go with remapping your controllers.
From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
you cannot call a controller method from another controller directly
my solution is to use inheritances and extend your controller from the library controller
class Controller1 extends CI_Controller {
public function index() {
// some codes here
}
public function methodA(){
// code here
}
}
in your controller we call it Mycontoller it will extends Controller1
include_once (dirname(__FILE__) . "/controller1.php");
class Mycontroller extends Controller1 {
public function __construct() {
parent::__construct();
}
public function methodB(){
// codes....
}
}
and you can call methodA from mycontroller
http://example.com/mycontroller/methodA
http://example.com/mycontroller/methodB
this solution worked for me
I had a similar problem. I wanted to have two controllers:
homepage.php - public facing homepage
home.php - home screen once a user was logged in
and I wanted them both to read from 'mydomain.com'
I was able to accomplish this by setting 'hompepage' as the default controller in my routes config and adding a remap function to homepage.php
function _remap()
{
if(user_is_logged_in())
{
require_once(APPPATH.'controllers/home.php');
$oHome = new Home();
$oHome->index();
}
else
{
$this->index();
}
}
I was having session file not found error while tried various ways, finally achieved like this. Made the function as static (which I want to call in the another controller), and called like
require_once('Welcome.php');
Welcome::hello();
While the methods above might work, here is a very good method.
Extend the core controller with a MY controller, then extend this MY controller for all your other controllers. For example, you could have:
class MY_Controller extends CI_Controller {
public function is_logged()
{
//Your code here
}
public function logout()
{
//Your code here
}
}
Then your other controllers could then extend this as follows:
class Another_Controller extends MY_Controller {
public function show_home()
{
if (!$this->is_logged()) {
return false;
}
}
public function logout()
{
$this->logout();
}
}
I came here because I needed to create a {{ render() }} function in Twig, to simulate Symfony2's behaviour. Rendering controllers from view is really cool to display independant widgets or ajax-reloadable stuffs.
Even if you're not a Twig user, you can still take this helper and use it as you want in your views to render a controller, using <?php echo twig_render('welcome/index', $param1, $param2, $_); ?>. This will echo everything your controller outputted.
Here it is:
helpers/twig_helper.php
<?php
if (!function_exists('twig_render'))
{
function twig_render()
{
$args = func_get_args();
$route = array_shift($args);
$controller = APPPATH . 'controllers/' . substr($route, 0, strrpos($route, '/'));
$explode = explode('/', $route);
if (count($explode) < 2)
{
show_error("twig_render: A twig route is made from format: path/to/controller/action.");
}
if (!is_file($controller . '.php'))
{
show_error("twig_render: Controller not found: {$controller}");
}
if (!is_readable($controller . '.php'))
{
show_error("twig_render: Controller not readable: {$controller}");
}
require_once($controller . '.php');
$class = ucfirst(reset(array_slice($explode, count($explode) - 2, 1)));
if (!class_exists($class))
{
show_error("twig_render: Controller file exists, but class not found inside: {$class}");
}
$object = new $class();
if (!($object instanceof CI_Controller))
{
show_error("twig_render: Class {$class} is not an instance of CI_Controller");
}
$method = $explode[count($explode) - 1];
if (!method_exists($object, $method))
{
show_error("twig_render: Controller method not found: {$method}");
}
if (!is_callable(array($object, $method)))
{
show_error("twig_render: Controller method not visible: {$method}");
}
call_user_func_array(array($object, $method), $args);
$ci = &get_instance();
return $ci->output->get_output();
}
}
Specific for Twig users (adapt this code to your Twig implementation):
libraries/Twig.php
$this->_twig_env->addFunction('render', new Twig_Function_Function('twig_render'));
Usage
{{ render('welcome/index', param1, param2, ...) }}
Create a helper using the code I created belows and name it controller_helper.php.
Autoload your helper in the autoload.php file under config.
From your method call controller('name') to load the controller.
Note that name is the filename of the controller.
This method will append '_controller' to your controller 'name'. To call a method in the controller just run $this->name_controller->method(); after you load the controller as described above.
<?php
if(!function_exists('controller'))
{
function controller($name)
{
$filename = realpath(__dir__ . '/../controllers/'.$name.'.php');
if(file_exists($filename))
{
require_once $filename;
$class = ucfirst($name);
if(class_exists($class))
{
$ci =& get_instance();
if(!isset($ci->{$name.'_controller'}))
{
$ci->{$name.'_controller'} = new $class();
}
}
}
}
}
?>
There are many ways by which you can access one controller into another.
class Test1 extends CI_controller
{
function testfunction(){
return 1;
}
}
Then create another class, and include first Class in it, and extend it with your class.
include 'Test1.php';
class Test extends Test1
{
function myfunction(){
$this->test();
echo 1;
}
}
You can call Model from a Controller so put your functions inside a Model and call it from the controller . Worked for me.
(codeignitor 3)
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 have a controller that have with in let's say thingy/stuff directory
<?php public function index() { /*thingy stuff */ }
public function anotherfunction() {/*other thingy stuff*/} ?>
i see tthe url like index.php?route=thingy/stuff&var=dd
what i want is to call an $.post to this function inside that controller
so it uses another template file thingy.tpl and return html to use
what the URL should like ??
i searched for hours ans it sounds like there is no development documentation for open-cart out there
let's say you have a controller called "stuff" under the thingy folder and a function called "my function" within that class, that looks like this:
class ControllerThingyStuff extends Controller {
public function index() {
// Some code
}
public function myfunction() {
// Your code
}
}
if you want to directly communicate with this function using the URL you can add the function name to the end of the route parameter "route=thingy/stuff/myfunction& ..." and load the thingy.tpl inside the function and return it after rendering:
// some code
$this->template = 'template/product/thingy.tpl';
...
$this->response->setOutput($this->render());
if are using the open cart 1.5 and you want to use jQuery AJAX with JSON then you'll need to import the JSON library before rendering:
$this->template = 'thingy/stuff/thingy.tpl';
$json['output'] = $this->render();
$this->load->library('json');
$this->response->setOutput(Json::encode($json));
take a look at the checkout page to get some ideas, the default open cart 1.5 template uses the same technique to load the templates for each section.
It's added to the route if it's not index, which it is by default, for example
<?php
class ControllerThingyStuff extends Controller {
public function index() {
// This is called with route=thingy/stuff or thingy/stuff/index
}
public function something() {
// This is called with route=thingy/stuff/something
}
}