I Have Defined MY_ Controller in my core folder.
Then i have two controllers:
Admin_Controller
Customer_Controller
Now i want to put a query into my Customer_Controller whose result i can access all the controller which extends to Customer_Controllers.
I have put this code in Customer_Controller
public function get_users()
{
$id = $this->session->userdata('id');
$this->db->select('*');
$this->db->join('tenant','tenant.id = sites.tenant_id');
$this->db->where('tenant.id',$id);
$this->db->from('sites');
$query = $this->db->get();
$result = $query->result();
$sitedata = json_decode(json_encode($result));
$this->session->set_userdata($sitedata);
}
Now when i have a child class something like this
<?php
class User extends Customer_Controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
//Get Results from Customer_Controller
}
}
how do this?
you can follow this:
class Customer_Controller extends My_Controller
{
public function customer()
{
return 'costomers';
}
}
then
class User extends Customer_Controller
{
//call the function from Customer_Controller
$this->customer();
}
Let me give you a suggestion. Instead of creating a controller and extending the same, why don't you create a library class.
And then load your library inside the controller you want.
for example here is your library class file.
<?php
class users{
private $session;
public function __construct(){
$CI =& get_instance();
$this->session=$CI->session;
}
public function get_users()
{
// do the code and return the
}
}
AND in your controller
<?php
class User extends CI_Controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
$this->load->library('users');
$users = new users();
$userinfo = users->get_users();
//Results from library
}
}
You Try get_instance() like this in you User Controller
public function get_users()
{
$id = $this->session->userdata('id');
$this->db->select('*');
$this->db->join('tenant','tenant.id = sites.tenant_id');
$this->db->where('tenant.id',$id);
$this->db->from('sites');
$query = $this->db->get();
$result = $query->result();
$sitedata = json_decode(json_encode($result));
$this->session->set_userdata($sitedata);
return $result;
}
class User extends CI_controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
$CI=&get_instance();
$result=$CI->get_users();
foreach($result as $row)
{
echo $row->id;//here add you table field name for id
}
}
}
Codeigniter is MVC framework.
So You will put get_users in model part.
example: you must making custom_model.php in models folder.
<?php
class custom_model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function get_users($id)
{
$this->db->select('*');
$this->db->join('tenant','tenant.id = sites.tenant_id');
$this->db->where('tenant.id',$id);
$this->db->from('sites');
$query = $this->db->get();
$result = $query->result();
return $result;
}
}
?>
next step: you are remake custom_controller.
public function get_users()
{
$id = $this->session->userdata('id');
$this->load->model('custom_model');
$result=$this->cutom_model->get_users($id);
$sitedata = json_decode(json_encode($result));
$this->session->set_userdata($sitedata);
}
and next step:
class User extends Customer_Controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
//
}
public function get_users(){
parent::get_users();
}
Related
I create a model for fetching data then write code
model..
function get_courses(){
$this->db->from(TABLE_COURSE);
$this->db->where('name !=', '');
$query = $this->db->get();
$result = '';
if($query){
if($query->num_rows() > 0)
$result = $query->result();
}
return $result;
}
Controller
defined('BASEPATH') OR exit('No direct script access allowed');
class Quiz extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('Mastermodel','',TRUE);
}
public function index()
{
$data['courses'] = $this->Mastermodel->get_courses();
$data['view_file'] = "content/quiz/quiz_list";
$this->load->view('layout/dashboard/layout', $data);
}
public function quiz_of_day()
{
$data['courses'] = $this->Mastermodel->get_courses();
$data['view_file'] = "content/quiz/quiz_of_day";
$this->load->view('layout/dashboard/layout', $data);
}
public function quiz_edit()
{
$data['courses'] = $this->Mastermodel->get_courses();
$data['view_file'] = "content/quiz/quiz_edit";
$this->load->view('layout/dashboard/layout', $data);
}
}
How to call model in controller on constructor because I need write only one time?
To achieve what you want you can do the following...
You need to make the $data array a property of the class
Reference the new $this->data throughout the class
You need to move your call to the model in the constructor.
So what you get is this
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Quiz extends CI_Controller {
protected $data = array(); // Old school definition of an array (instead of [])for safety
public function __construct() {
parent::__construct();
$this->load->model('Mastermodel', '', TRUE);
$this->data['courses'] = $this->Mastermodel->get_courses();
}
public function index() {
$this->data['view_file'] = "content/quiz/quiz_list";
$this->load->view('layout/dashboard/layout', $this->data);
}
public function quiz_of_day() {
$this->data['view_file'] = "content/quiz/quiz_of_day";
$this->load->view('layout/dashboard/layout', $this->data);
}
public function quiz_edit() {
$this->data['view_file'] = "content/quiz/quiz_edit";
$this->load->view('layout/dashboard/layout', $this->data);
}
}
Tim's method would work just find, but I tend to do it more this way.
class Quiz extends CI_Controller {
public $courses; // can also be set to private
public function __construct(){
parent::__construct();
$this->load->model('Mastermodel','',TRUE);
$this->courses = $this->Mastermodel->get_courses();
}
public function index()
{
$data['courses'] = $this->courses;
$data['view_file'] = "content/quiz/quiz_list";
$this->load->view('layout/dashboard/layout', $data);
}
Can I obtain the model directly from a query in Code Igniter?
Model
<?php
class User_Model extends CI_Model {
public $user_id;
public $name;
public $team_id
public function getTeamName() {
$this->db->select('name');
$this->db->from('team');
$this->db->where('team_id',$this->team_id);
$query = $this->db->get();
$team = $query->row();
if($empresa == null){
return "";
} else {
return $team->name;
}
}
public function getUser($id) {
$query = $this->db->get_where('users', array('user_id' => $id));
$user = $query->row();
return $user;
}
I would like getUser($id) function returns a user object like 'new User_Model()' to be able to use getTeamName() function in the view. Can I do it?
Now returns an object, but not a User_Model() object.
is wrong call a method in the model from the view.
in the model use
function getUser($id){
$query = $this-db->select('*')
->from('users')
->where('user_id', $id)
->get();
return $query->result();
}
this return a object with all data, then you call the method in the controller like this
$data['user_model'] = $this->model_name->getUser($id);
$this->load->view('Your_View',$data);
then in the view $user_model is the object
in the view
print_r($user_model);
As long as the model is loaded, in your view you can access any public function or property like:
$this->user_model->getUser() or $this->user_model->team_id
View:
<?php
echo $this->user_model->getUser(1)->username;
This is against MVC in some respects but I can understand the logic behind doing so based on the following scenario where you want to say use num_rows and result without doing count:
class User_Model extends CI_Model {
public function getUsers() {
return $this->db->get('users');
}
}
class Some_Controller extends CI_Controller {
public function index() {
$this->load->model('user_model');
$data['users'] = $this->user_model->getUsers();
$this->load->view('some_view', $data);
}
}
View:
<?php
if ($users->num_rows() > 0) {
foreach ($users->result() as $row) {
echo $row->username;
}
} else {
echo 'No users';
}
Actually there is another possibility you can use
create a Team_model and an User_model
The Team_model could look like
class Team_model extends CI_Model
{
$arrTeamNames = [];
public function getTeamName($team_id)
{
if (!isset($this->arrTeamNames[$team_id]))
{
$query = $this->db
->select('name')
->from('team')
->where('team_id',$this->team_id)
->get();
if ($query->num_rows() == 1)
{
$objTeam = $query->row();
$this->arrTeamNames[$team_id] = $objTeam->name;
return $objTeam->name;
}
return '';
}
return $this->arrTeamNames[$team_id];
}
}
and the User_model
class User_Model extends CI_Model
{
public function getUser($id)
{
$query = $this->db->get_where('users', array('user_id' => $id));
if ($query->num_rows() == 1)
{
$user = $query->row(0, 'User_Object');
return $user;
}
}
}
class User_Object
{
public function getTeamName()
{
$ci = get_instance();
$ci->load->model('Team_model');
return $ci->team_model->getTeamName($this->team_id);
}
}
Note in the User_model you have an additional User_Object which
gets mapped by the row() function which is well documented
here.
Now if you call this model in one of your controller and pass it to your view you actually can access to a model function in a proper way e.g.
class User extends CI_Controller
{
public function detail($user_id)
{
$this->load->model('User_model');
$objUser = $this->User_model->getUser($user_id);
$this->load->view('user-detail', ['objUser' => $objUser]);
}
}
//user-detail view
echo $objUser->getTeamName();
I am new to CodeIgniter and I have been trying to populate the drop down list on the view page with data from the database with no success. I tried using the recomendations from this question but the drop down is still empty (display data from database to dropdown CodeIgniter)
Here is my view:
<label>City</label>
<select class="form-control>
<option value="">All</option>
<?php
foreach($groups as $city)
{
echo '<option value="'.$city['cityidd'].'">'.$city['city'].'</option>';
}
?>
</select> <br/>
Here is my controller:
<?php
class Main_controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index()
{
$this->load->helper('form');
$this->load->view('supplier_add');
}
}
Here is my model:
class Site_model extends CI_Model
{
public function __construct()
{
/* Call the Model constructor */
parent::__construct();
}
function getAllGroups()
{
$query = $this->db->query('SELECT city FROM citys');
return $query->result();
}
}
The table name is "citys" then the corresponding column heads are "cityidd" and "city"
There are several issue found there. Make changes as below
function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load_model('Site_model');
$this->load->database();
}
public function index(){
$this->load->helper('form');
$data['groups'] = $this->site_model->getAllGroups();
$this->load->view('supplier_add',$data);
}
Finally model
function getAllGroups(){
$query = $this->db->query('SELECT cityidd,city FROM citys');
return $query->result_array();
}
and now test
First change your SELECT query as
SELECT cityidd, city FROM citys
In the index() of controller change the code as
public function index()
{
$this->load->helper('form');
$data['groups'] = $this->site_model->getAllGroups();
$this->load->view('supplier_add',$data);
}
you have to call your model method and pass it to view in the controller, code:
public function index()
{
$this->load->helper('form');
$this->load->model('site_model');
$data['groups'] = $this->site_model->getAllGroups();
$this->load->view('supplier_add',$data);
}
if you are working on linux dont forget upper and lowercase names!
class Main_controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->model('Site_model');
}
public function index()
{
$this->load->helper('form');
$data['groups']=$this->Site_model->getAllGroups();
$this->load->view('supplier_add',$data);
}
}
Here is my model:
class Site_model extends CI_Model
{
public function __construct()
{
/* Call the Model constructor */
parent::__construct();
}
function getAllGroups()
{
$query = $this->db->query('SELECT * FROM citys');
return $query->result();
}
}
Try like this
Make these changes
IN Model convert data to array as you are using it as array in view so change to this
function getAllGroups()
{
$query = $this->db->query('SELECT * FROM citys');
return $query->result_array();
}
In Controller
public function index()
{
$this->load->helper('form');
$this->load->model('site_model');
$data['groups'] = $this->site_model->getAllGroups();
$this->load->view('supplier_add',$data);
}
You are not loading model load the Model
for example:-
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('Site_model')
$this->load->database();
}
public function index()
{
$this->load->helper('form');
$data['record']=$this->Site_model->getAllGroups()
$this->load->view('supplier_add', $data);
}
}
Model:-
class Site_model extends CI_Model
{
public function __construct()
{
/* Call the Model constructor */
parent::__construct();
}
function getAllGroups()
{
$query = $this->db->query('SELECT city FROM citys');
return $query->result();
}
}
I'm testing my CodeIgniter project with PHPUnit Testing framework (CITest.php). When the function test_model(), calls the model directly to get the details of an user, it works perfectly. But when I do the same via a controller by calling the function test_controller(), it does not output anything (When I debugged, the model itself doesn't gets called). I even verfied if the post data is passed correctly by creating a function test_post_data(). Am I missing something?
I could only find online resources to test the mdoel directly or a controller separately. But I couldn't find any useful link which calls a controller that triggers the model.
CITest.php
class CITest extends PHPUnit_Framework_TestCase
{
private $CI;
public function setUp()
{
$this->CI = &get_instance();
$this->CI->load->model('Test_model');
$this->model = $this->CI->My_model; // load the model
$this->auth = new Test_controller; // load the controller
}
public test_model() {
$user_id = 6;
print_r($this->model->getUserData($user_id));
}
public test_post_data() {
$_POST['useR_id'] = 22;
print_r($this->model->check_post_data());
}
public test_controller() {
$_POST['useR_id'] = 22;
print_r($this->model->get_user_data());
}
}
Test_controller.php
class Test_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Test_model');
}
public function check_post_data() {
return $this->input->post();
}
public function get_user_data() {
$user_id = $this->input->post('user_id');
return $this->Test_model->getUserData($user_id);
}
}
Test_model.php
class Test_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function getUserData($user_id) {
return $this->db->select("*")
->from("users")
->where("user_id", $user_id)
->get()->result_array();
}
}
The code in CITest.php
public test_controller() {
$_POST['useR_id'] = 22;
print_r($this->model->get_user_data());
}
should be like the following?
public test_controller() {
$_POST['useR_id'] = 22;
print_r($this->auth->get_user_data());
}
What is the best way to create my model so I can call it from my controller like this?
$this->model_model->function->dbname
I have the following model but its rubbish:
Model:
function systemName()
{
$query = $this->db->query("SELECT cms_name FROM options");
return $query->result();
}
Update:
function systemOptions($options)
{
$this->db->select($options);
$query = $this->db->get('options');
return $query->num_rows();
}
Why would you want to? Why not call it like this?:
$this->model_model->functionname('dbname');
A complete skeleton of a model is like this:
<?php
class Mymodel extends Model
{
function get_some_entries($number_rows)
{
return $result = $this -> db -> query("SELECT id, name
FROM tablename
LIMIT $number_rows");
}
}
?>
Best way? You can probably read on CodeIgniter general guide and alter to your situation. But the basic idea is that, you create the model class then load from your controller. Then just call the model function accordingly. For example,
class Custom_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function systemName()
{
$query = $this->db->query("SELECT cms_name FROM options");
return $query->result();
}
...
...
function systemOptions($options)
{
$this->db->select($options);
$query = $this->db->get('options');
return $query->num_rows();
}
}
<?php
class CustomController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('custom_model', 'fubar');
}
public function index()
{
$result = $this->fubar->systemName('dbname');
print_r ($result);
}
}
?>