Variable inside function __construct() in Codeigniter - codeigniter

I am using Tank_auth for user authentication in codeigniter. To check if any user is logged in or not, if he is then to get the username and id I need to use the following code in every functions of my controllers, which is very irritating.
// If any user is logged in get his/her userid or name
if ($this->tank_auth->is_logged_in()) {
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
}
So , I was wondering if I could make life easier by putting the following code inside the function __construct() like following,
but its not working.
Could you please tell me how to get it work?
Thanks in Advance :)
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('tank_auth');
if ($this->tank_auth->is_logged_in()) {
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
}
}

if you plan to use this array only inside this controller, you can use it like this:
//outside the functions define the $data as controller class property:
private $data = array();
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('tank_auth');
if ($this->tank_auth->is_logged_in()) {
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username'] = $this->tank_auth->get_username();
}
}
//and then use it like
function index(){
$this->load->view("something.php",$this->data);
}

Related

call another controller from dashboard using template pages

I working on Codeigniter project, I create page template to load header left menu and footer, everything working good, when I try the open link in the menu I want to open another controller. I do it but when the controller view open the variable inside to load database table for each row not working.. but the controller who load the database when I open it without my template its working fine
The Dashboard controller
class Dashboard extends CI_Controller{
protected $data = array();
function __construct()
{
parent::__construct();
$this->data['pagetitle'] = 'Invoices Manager';
}
protected function render($the_view)
{
$this->data['the_view'] = (is_null($the_view)) ? '' : $this->load->view($the_view,$this->data, TRUE);
$this->load->view('templates/master_page', $this->data);
}
public function home() {
// $this->load->view('templates/master_page', $this->data);
$this->render( 'templates/homepage_view');
}
public function dashboard() {
// $this->load->view('templates/master_page', $this->data);
$this->render( 'dashboard/home');
}
public function purchaselist(){
$this->render('purchase/index');
}
}
The purchase controller that working good alone
class Purchase extends CI_Controller{
protected $data = array();
protected $mydata = array();
function __Construct()
{
parent::__Construct ();
$this->load->database(); // load database
$this->load->model('Purchase_model'); // load model
$this->mydata['purchase']=null;
}
public function index()
{
$query = $this->Purchase_model->getPurchaselist();
if($query)
{
$mydata['purchase'] = $query;
}
$this->load->view('purchase/index', $mydata);
// $this->render( 'purchase/index');
}
}
when I call dashboard/purchaselist they say the
Message: Undefined variable: purchase
Filename: purchase/index.php
Line Number: 17
its should load database table inside the template
try using dashboard/index.php/purchaselist or load your modal $this->load->model('Purchase_model'); as global
Please pass null or empty array in purchase if $query is empty
public function index()
{
$query = $this->Purchase_model->getPurchaselist();
if(!empty($query)){
$mydata['purchase'] = $query;
}else{
$mydata['purchase'] = array();
}
$this->load->view('purchase/index', $mydata);
// $this->render( 'purchase/index');
}

Codeigniter global variable in view

I don't know if the title above is an correct title about my question.
Is there a way to declare a variable which we can access it from anywhere in view without need to redefine it again in each function in controller?
for example in controller file Students.php contains many function that handle the views, take a look below :
public function __construct() {
parent::__construct();
$data['count_student'] = $this->m_data->allStudent(); // count all students
}
public function index() {
$data['content'] = 'view-students';
$this->load->view('frontend/header' , $data);
}
public function showDetails() {
$data['content'] = 'view-detail-students';
$this->load->view('frontend/header' , $data);
}
I expected we can access $count_student in both view-students.php and view-detail-student.php without to define $data['count_student'] = $this->m_data->allStudent(); on each function that handle the view.
Is there possible ways to do that?
In the application/core/ create MY_Controller.php
<?php
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('m_data');
$this->data['count_student'] = $this->m_data->allStudent();
}
}
Controller use $this->data
class Students extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->data['content'] = 'view-students';
$this->load->view('frontend/header', $this->data);
}
public function showDetails() {
$this->data['content'] = 'view-detail-students';
$this->load->view('frontend/header', $this->data);
}
}
Now that you have extended the controller you shoudld be able to just go like
<?php echo $count_student;?>
On the view
I noticed that you can access variables in views without passing them if you declare them in the controller with $this->. Probably because they default to public visibility.
public function __construct() {
parent::__construct();
// $data['count_student'] = $this->m_data->allStudent(); // count all students
//
$this->count_all_the_students = $this->m_data->allStudents();
}
public function index() {
$data['content'] = 'view-students';
$this->load->view('frontend/header' , $data);
}
And then in the view you can use $this->count_all_the_students without putting it in the $data array.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
echo 'I have misled ' . $this->count_all_the_students . ' students with my MVC breaking suggestions.';
If you are using the same variable in every controller function then you have to declare it as follows
class Example extends CI_Controller{
protected $data = array();
public function __construct() {
parent::__construct();
$this->data['count_student'] = $this->m_data->allStudent();
}
public function index() {
$this->data['content'] = 'view-students'; //variables are same
$this->load->view('frontend/header' , $this->data);
}
public function showDetails() {
$this->data['content'] = 'view-detail-students'; //variables are same
$this->load->view('frontend/header' , $this->data);
}
}
This applies only if you have common variables for all views in this controller.
If you are using different variables then use the following code.
class Example extends CI_Controller{
protected $count_student= "";
public function __construct() {
parent::__construct();
$this->count_student = $this->m_data->allStudent();
}
public function index() {
$data['content'] = 'view-students'; //Variable is different
$data['count_student'] = $this->count_students;
$this->load->view('frontend/header' , $data);
}
public function showDetails() {
$data['details'] = 'view-detail-students'; // Variable is different
$data['count_student'] = $this->count_students;
$this->load->view('frontend/header' , $data);
}
}

Codeigniter & HMVC - Callback not working

I've pretty much gone through a lot of link and solutions provided here and other locations, but I am just not able to solve the callback issue that I am facing. I'm using Codeigniter with HMVC the code is below.
The following code is from My_Form_validation.php:
class MY_Form_validation extends CI_Form_validation {
function run($module = '', $group = ''){
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
Below if the Callback function :
public function _unique_email($str) {
// Check if user already exists
// Process only for current user
$id = $this->uri->segment(4);
$this->db->where('email', $this->input->post('email'));
!$id || $this->db->where('id !=', $id);
$user = $this->mdl_admin_users->get();
if (count($user)) {
$this->form_validation->set_message('_unique_email', 'User already exists. Please check %s.');
return FALSE;
}
return TRUE;
}
and the function :
public function user_edit($id = NULL) {
// Fetch a user or set a new one
if ($id) {
$data['user'] = $this->mdl_admin_users->get($id);
count($data['user']) || $data['errors'][] = 'User could not be found';
}
else {
$data['user'] = $this->mdl_admin_users->get_new();
}
// setup the form
$rules = $this->mdl_admin_users->rules_admin;
$id || $rules['password'] = '|required';
$this->form_validation->set_rules($rules);
//process the form
if ($this->form_validation->run($this) == TRUE) {
$data = $this->mdl_admin_users->array_from_post(array('firstname', 'lastname', 'email', 'password'));
$data['password'] = $this->mdl_admin_users->hash($data['password']);
$this->mdl_admin_users->save($data, $id);
redirect('admin/user');
}
// Load the view
$data['title'] = 'Edit Users';
$data['module'] = 'admin';
$data['header_file'] = 'header_admin';
$data['nav_file'] = 'nav_admin';
$data['view_file'] = 'edit_users';
$data['footer_file'] = 'footer_admin';
echo Modules::run('template/base_template', $data);
}
Would be a great help if someone could point me at the right direction to resolve the issue. Thanks in advance
Naveen
According to wiredesignz,
When using form validation with MX you will need to extend the CI_Form_validation class as shown below,
/** application/libraries/MY_Form_validation **/
class MY_Form_validation extends CI_Form_validation
{
public $CI;
}
before assigning the current controller as the $CI variable to the form_validation library. This will allow your callback methods to function properly.
class Xyz extends MX_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->form_validation->CI =& $this;
}
}
This will remove HMVC related callback problem without any changes to your code.
First of you are missing in the rules
$rules['email'] = 'required|callback__uniqueemail';
Also call back function should be not like this callback__unique_email for some reason I found codeigniter call back not like extra gap this better callback__uniqueemail
If private do not work make public function removing underscore
public function uniqueemail() // no need $str
When make public do not for get to remove extra underscore from here callback_uniqueemail
Another thing with echo Modules run best to be loaded from view only.
In your controller replace echo Modules run with $this->load->view();
You need to add $this->form_validation->run($this) add $this to run after create library below.
And Create a new library
<?php
class MY_Form_validation extends CI_Form_validation {
function run($module = '', $group = '') {
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
Tutorial Best https://www.youtube.com/watch?v=8fy8E_C5_qQ

Query Strings with Code Igniter

I'm trying to setup CodeIgniter (v2.1.4) with Query Strings and having problems with passing variables. The pages work when the controller_trigger and function_trigger are passed:
example.org/?c=page&m=index
But when I try to pass a variable:
example.org/?c=page&m=view&id=1
The script throws 'Missing argument' and 'Undefined variable' errors.
In 'application/config/config.php' I've set:
$config['enable_query_strings'] = TRUE;
In 'application/config/routes.php' I have:
$route['default_controller'] = "page";
And my Controller looks like:
<?php
class Page extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('page_model');
}
public function index()
{
$data['title'] = 'Page Title';
$this->load->view('templates/header', $data);
$this->load->view('page/page_index', $data);
$this->load->view('templates/footer');
}
public function view($id)
{
$data['title'] = 'Id Page Title';
$data['page_item'] = $this->page_model->get_page($id);
$this->load->view('templates/header', $data);
$this->load->view('page/page_view', $data);
$this->load->view('templates/footer');
}
}
Does anyone know what I've missed?
Any help would be greatly appreciated
In your config.php change:
$config['allow_get_array'] = TRUE; #example.com?who=me&what=something&where=here
Write it like this
example.org?c=page&m=index
without "/"

CodeIgniter routing issue, advice how to do it

I'm not CI programmer, just trying to learn it. Maybe this is wrong approach, please advice.
my controller(not in sub directory) :
class Users extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index($msg = NULL) {
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function process_logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}
And a route for login :
$route['user/login'] = 'users/index';
Problem is when I wanna logout, it shows me 404 because I do not have it in my route :
$route['user/process_logout'] = 'users/process_logout';
and in my view I put logout
When I add that, it works, and that is stuppid to add a route for everything. What I'm I doing wrong, please advice.
Thank you
Don't know why you are trying to implement login feature in index() function. However since you said you are learning CI I'm telling something about _remap() function.
Before that. You can try the following routing:
$route['user/:any'] = 'users/$1';
$route['user/login'] = 'users/index';
If you want to take value immediately after controller segment you need to use _remap() function and this function may be solve your routing problem, i mean you don't need to set routing. Lets implement your code controller 'users' using _remap() function.
class Users extends CI_Controller {
private $sections = array('login', 'logout');
function __construct() {
parent::__construct();
}
public function _remap($method)
{
$section = $this->uri->segment(2);
if(in_array($section, $this->sections))
call_user_func_array(array($this, '_'.$section), array());
else show_404(); // Showing 404 error
}
private function _login()
{
$msg = $this->uri->segment(3);
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function _logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}

Resources