Ok I have a simple question I am using codeigniter frame work to create a simple blog. When I set up just a controller and a view I can print my database information (blog roll) to my view just fine. When I use the model controller view method i fail.
Here is what I would like to implement in to a method controller view setup.
my original view that works:
<?php
//is there an array from your search form?
if($_GET){
$books = $this->db->get('blog');//query the blog table in the database
if($books->num_rows() < 1)//are there clients to show?
{
echo 'There are no blog post'; //error message if no post
}
else
{
foreach(result() as $row)//loop through the blog
{
echo $row->title."<br>";//display each titles info
}
}
}
?>
This is what i have set for my New model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog_Model extends CI_Model {
function get($args = null)
{
$query = $this->db->get('blog');
return $query->result();
foreach(result() as $row)//loop through the books
}
function insert($data)
{
$this->db->insert('blog', $data);
}
function update($data,$id)
{
$this->db->where("id",$id);
$this->db->update('blog', $data);
}
function delete($id)
{
$this->db->where("id",$id);
$this->db->delete('blog');
}
}
this is my new controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller {
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog->get();
$this->load->view('blog',$data);
}
}
I am not sure what to do for my new view? I just want to echo the blog roll to the view
Well you´re doing a foreach in the model after the return function.
So what you return is just this:
$query->result()
You may should do the foreach in the view, this would be better placed as a model just should just return and not process information. Best place would be in this case the controller or may view - depending on how strict you are.
I did not work with CodeIgniter for a while so may try this:
Controller:
class Blog extends CI_Controller
{
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog_model->get()->result();
$this->load->view('blog',$data);
}
}
The View
Here goes some text...
<?php
foreach($blogs as $post)
{
echo $post['someData'];
echo $post['someData2'];
}
?>
After all this code...
May you want to lookup this (CodeIgniter Doc).
Hope this helps. Try to
Controller:
$data['blogs'] = $this->blog_model->get();
Even though you load the model in order to call its function you must pass its name.
Model:
Must always have result() or row() when query are applied.
Hope this helps in your endeavors
Related
I am new in codeigniter and i am working on ecommerce template. By default whenever index() has been hit, it's showing all products in different sections (in html) and I want to make this dynamic so should I use queries in index() for get different type of records or there is any other way? This is my code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
//echo "hello world";
$this->load->view('index');
}
}
?>
First need to create database and table as per your requirement.
Then you can create model for reference check this link : https://www.codeigniter.com/userguide3/general/models.html
<?php
class Blog_model extends CI_Model {
public function get_data_first()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
public function get_data_second()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
}
?>
After making model go to your controller and include it like:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
$this->load->model('my_model');
$data['first_list'] = $this->my_model->get_data_first();
$data['second_list'] = $this->my_model->get_data_second();
//echo "hello world";
$this->load->view('index', $data);
}
}
?>
Then use you param in index file like :
<html>
<head></head>
<body>
<?php
if($first_list){
foreach($first_list as $each){
echo $each->my_param;
}
}
?>
<?php
if($second_list){
foreach($second_list as $each){
echo $each->my_param2;
}
}
?>
</body>
</html>
I hope this helpful for you.
In Models folder write Home_model.php file for querying database.
Suppose you have a table called 'products'.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home_model extends CI_Model{
public function __construct()
{
parent::__construct();
}
public function getProducts()
{
$this->db->from('products');
$query=$this->db->get();
$out = $query->result_array();
return $out;
}
}
The function 'getProducts' will get you all the products from 'products' table.
Now in your controller load the 'database' library and the model.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('home_model');
$this->load->library('database');
}
public function index(){
$products = array();
$products = $this->home_model->getProducts();
$this->load->view('index',$products);
}
}
In index function function of controller you can call the 'getProduct' function of model.And can pass the data to view.
Documentation link for model.
enter link description here
I hope this helps.
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>
Hi guys i have problem using two tables from same DB in one view. When i use only one of the tables it works but when i try to fetch both of them my view does not load. This is my model: schedule_model.php:
<?php
class Schedule_model extends CI_Model {
public function __construct()
{
}
public function get_schedules()
{
$this->db->select('schedule.id, schedule.name');
$this->db->from('Schedule');
$this->db->group_by("schedule.id");
$query = $this->db->get();
return $query->result_array();
}
public function get_subscheds()
{
$this->db->select('subsched.id, subsched.name, subsched.enable, subsched.from, subsched.to, subsched.mode, subsched.fcu1, subsched.fcu2, subsched.fcu3, subsched.pon, subsched.vt, subsched.sr, subsched.cet, subsched.pet, subsched.sab, subsched.ned');
$this->db->from('Subsched');
$this->db->group_by("subsched.id");
$query = $this->db->get();
return $query->result_array();
}
}
?>
This is the controller: schedule.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Schedule extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('schedule_model');
}
public function index()
{
if(!$this->session->userdata('loggedIn')){
redirect("login");
}
$data['schedules'] = $this->schedule_model->get_schedules();
//$data['subscheds'] = $this->schedule_model->get_subscheds();
$this->load->view('schedule', $data); //my view is also named schedule :)
}
}
?>
Notice that i have commented the line that calls the function which gets the elements from the second table. If i uncomment it, my view freezes. Otherwise it works fine with only one table. In my view i loop through elements in foreach loops. What could be the problem? Thanks
Hope this one help you..
$schedules = $this->schedule_model->get_schedules();
$subscheds = $this->schedule_model->get_subscheds();
$data['schedules'] = $schedules;
$data['subscheds'] = $subscheds;
## and then pass to view.
$this->load->view('schedule', $data);
Try this one..I have made some modification..You can access "schedules" as $schedules and "subscheds" as $subscheds in 'schedule' view you have defined.
$data['schedules'] = $this->schedule_model->get_schedules();
$data['subscheds'] = $this->schedule_model->get_subscheds();
This will load both datas from shedules table and subsheds table. and then you can load view with these data by..
$this->load->view('schedule', $data);
Now you can loop through $data by using $data['schedules'] and $data['subscheds'] to use db fields wherever necessary.
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>
EDIT: With the code below now, I am unsure on how to print out the bookmarks and the tags correctly
I’m completely new to CI and I have recently hit a road block. I’m very unsure how I would go about passing a function argument from the view file to the controller so I could use it on a function?
I have a foreach loop on the view going through the all the items passed by function get_latest_bookmarks. That function returns a ID for each item and I am wanting to use this with another function called get_bookmark_tags which will get the tags of the bookmark from another table. I have provided the code I have done so far below.
Model:
<?php
class Bookmark_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_latest_bookmarks($limit)
{
// Load Database
$this->load->database();
// Query Database
$query = $this->db->get('Bookmark', $limit);
// Return Result
return $query;
}
function get_bookmark_tags($id)
{
// Load Database
$this->load->database();
$query = $this->db->query('SELECT Tag.Title
FROM `Tag`
INNER JOIN BookmarkTag
WHERE BookmarkTag.BookmarkID = "'.$id.'" AND Tag.TagID = BookmarkTag.TagID');
return $query;
}
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
// Load URL Helper
$this->load->helper('url');
// Load User Library
$this->load->library('ion_auth');
// Is User Logged In
if ($this->ion_auth->logged_in())
{
$data['user'] = $this->ion_auth->get_user_array();
}
else
{
redirect('auth/login');
}
// Load Bookmark Model
$this->load->model('Bookmark_model');
// Create Arrays
$bookmarks = array();
$tags = array();
// Query Database
$query = $this->Bookmark_model->get_latest_bookmarks(4);
//
foreach ($query->result() as $row) {
array_push($tags, $this->Bookmark_model->get_bookmark_tags($row->BookmarkID));
array_push($bookmarks, $row);
}
$data['tags_latest'] = $tags;
$data['bookmarks_latest'] = $bookmarks;
$this->load->view('welcome_message', $data);
}
}
View:
<h1>Latest Bookmarks</h1>
<?php foreach ($bookmarks_latest as $bookmark): ?>
<?php print_r($bookmark); ?>
<?php print_r($tags_latest->result()); ?>
<?php endforeach; ?>
You should do that in your Controller before you are passing the data to the View.
Try with something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
// Load Model
$this->load->model('Bookmarks');
// Get Latest Bookmarks
$query = $this->Bookmarks->get_latest_bookmarks(4);
$bookmarks = array();
$tags = array();
foreach ($query->result() as $row) {
$bookmark_query = $this->Bookmarks->get_bookmark_tags($row->id);
$bookmark_arr = array();
foreach (bookmark_query->result() as $bookm) {
array_push($bookmark_arr, $bookm);
}
array_push($tags, $bookmark_arr);
array_push($bookmarks, $row);
}
$data['tags'] = $tags;
$data['bookmarks'] = $bookmarks;
// Load and Pass Data into View
$this->load->view('welcome_message', $data);
}
}
You don't.
The point in using a Framework is to default to proper standards. CodeIgniter follows a loose MVC pattern but you should never pass things from the view to the controller.
You can do it, but if you do it you'll be getting into a spaghetti mess pretty soon.
Grab the ID's on the controller. Even if it implicates running the same loop twice. You'll thank yourself latter on.