I am trying to use a custom function in MY Loader parent construct area called DIR_TEMPLATE But it is not picking it up.
Error: Parse error: syntax error, unexpected '=' in C:\xampp\htdocs\codeigniter\codeigniter-cms\catalog\core\MY_Loader.php on line 14
I am wanting to be able to do something like this in controller.
if (file_exists(DIR_TEMPLATE . 'default' . '/template/common/header.tpl')) {
return $this->load->view('default' . '/template/common/header.tpl', $data);
} else {
return $this->load->view('default/template/common/header.tpl', $data);
}
MY_Loader.php
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
require APPPATH ."third_party/hmvc/loader.php";
class MY_Loader extends MX_Loader {
public function __construct() {
$this->_ci_view_paths = array(APPPATH . 'views/theme/' => TRUE);
$this->_ci_ob_level = ob_get_level();
$this->_ci_library_paths = array(APPPATH, BASEPATH);
$this->_ci_helper_paths = array(APPPATH, BASEPATH);
$this->_ci_model_paths = array(APPPATH);
DIR_TEMPLATE = $this->_ci_view_paths; // Error Here
$this->_ci_view_paths = DIR_TEMPLATE; // Not working
Severity: Notice
Message: Use of undefined constant DIR_TEMPLATE - assumed 'DIR_TEMPLATE'
Filename: core/MY_Loader.php
Line Number: 14
log_message('debug', "MY_Loader Class Initialized");
}
}
you need to define DIR_TEMPLATE
DIR_TEMPLATE = $this->_ci_view_paths; // Error Here
should be something like
define( 'DIR_TEMPLATE', $this->_ci_view_paths );
EDIT :
since its an array
you cant not define it as a PHP constant as it supports scalar and null only
you can use
define('DIR_TEMPLATE', serialize($this->_ci_view_paths));
and when ever you need it you can just unserialize()
I worked it out now. I had do modify the define part of My Loader but all good.
Loaded On Controller
if (file_exists(DIR_TEMPLATE .'default' . '/template/common/header.tpl')) {
return $this->load->view('default' . '/template/common/header.tpl', $data);
} else {
return $this->load->view('default/template/common/header.tpl', $data);
}
MY Loader.php
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
require APPPATH ."third_party/hmvc/loader.php";
class MY_Loader extends MX_Loader {
public function __construct() {
define('DIR_TEMPLATE', APPPATH . 'views/theme/');
$this->_ci_view_paths = array(APPPATH . 'views/theme/' => TRUE);
$this->_ci_ob_level = ob_get_level();
$this->_ci_library_paths = array(APPPATH, BASEPATH);
$this->_ci_helper_paths = array(APPPATH, BASEPATH);
log_message('debug', "MY_Loader Class Initialized");
}
}
Related
I am using php function_exists() function exist on my Welcome controller. But for some reason it keeps on throwing my show_error even though my slideshow function exists.
With in my foreach loop I get module function name from database which in the foreach loop is called $function = $module['code'];
Question is: How am I able to make sure function_exists checks
function exists correctly?
<?php
class Welcome extends CI_Controller {
public function index() {
$data['content_top'] = $this->content_top();
$this->load->view('home', $data);
}
public function content_top() {
$data['modules'] = array();
$modules = $this->get_module();
foreach ($modules as $module) {
$function = $module['code'];
if (function_exists($function)) {
$setting_info = array('test' => 'testing');
if ($setting_info) {
$data['modules'][] = $this->$function($setting_info);
}
} else {
show_error('This ' . $function . ' does not exist on ' . __CLASS__ . ' controller!');
}
}
return $this->load->view('content_top', $data, TRUE);
}
public function banner() {
}
public function slideshow($setting) {
$data['test'] = $setting['test'];
$this->load->view('module/slideshow', $data);
}
public function get_module() {
$query = $this->db->get('modules');
return $query->result_array();
}
}
function_exists() works on functions, but not class methods - these are different things. What you want is method_exists():
method_exists($this, $function);
On codeigniter 3 when loading a view, the default path is application / views /
I would like to be able to change the default path to application / views / template /
I use to be able to change the default view path on MY_Loader.php $this->_ci_view_path = APPPATH .'views/template/'; as shown below. Currenly it only suited for CI2 does not seem to work on CI3
Question On codeigniter 3.0 versions what is the best method of changing the default view path, can it be done similar to my MY_Loader from CI2 to CI3.
<?php
class MY_Loader extends CI_Loader {
function __construct() {
// Change this property to match your new path
$this->_ci_view_path = APPPATH .'views/template/';
$this->_ci_ob_level = ob_get_level();
$this->_ci_library_paths = array(APPPATH, BASEPATH);
$this->_ci_helper_paths = array(APPPATH, BASEPATH);
$this->_ci_model_paths = array(APPPATH);
log_message('debug', "Loader Class Initialized");
}
}
Solved
The problem was here
CI2 Versions
$this->_ci_view_path = APPPATH .'views/somefoldername/';
Now CI3 Versions
$this->_ci_view_paths = array(
APPPATH . 'views/somefoldername/' => TRUE
);
How to change the default view path in Codeigniter 3
application > core > MY_Loader.php
<?php
class MY_Loader extends CI_Loader {
public function __construct() {
$this->_ci_ob_level = ob_get_level();
$this->_ci_view_paths = array(
APPPATH . 'views/somefoldername/' => TRUE
);
$this->_ci_library_paths = array(APPPATH, BASEPATH);
$this->_ci_model_paths = array(APPPATH);
$this->_ci_helper_paths = array(APPPATH, BASEPATH);
log_message('debug', "Loader Class Initialized");
}
}
Update for HMVC & Codeigniter 3
This symbol * in glob on code below meaning module name.
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
/* load the MX_Loader class */
require APPPATH."third_party/MX/Loader.php";
class MY_Loader extends MX_Loader {
public function __construct() {
$this->_ci_ob_level = ob_get_level();
// Default
$this->_ci_view_paths = array(
APPPATH . 'views/' => TRUE
);
// Modules
$module_view_paths = glob(APPPATH . 'modules/*/views/template/', GLOB_ONLYDIR);
foreach ($module_view_paths as $module_view_path) {
$this->_ci_view_paths = array(
$module_view_path => TRUE,
);
}
$this->_ci_library_paths = array(APPPATH, BASEPATH);
$this->_ci_model_paths = array(APPPATH);
$this->_ci_helper_paths = array(APPPATH, BASEPATH);
log_message('debug', "Loader Class Initialized");
}
}
This allows you to do this for HMVC loading of views
$this->load->view('folder_name/view_name');
Instead of
$this->load->view('template/folder_name/view_name');
If you check index.php file again, you'll see that every single line is well explained. For this particular line in subject is written:
If you do move this, use the full server path to this folder.
Change this to
$this->_ci_view_path = APPPATH .'views/template/'; # Works on CI 3.0-
this
$this->_ci_view_paths = array(APPPATH.'views/template/' => TRUE); # Works on CI 3.0+
Posting My Comment as answer
Actually It's not the answer to your Question But it will act as a alternate solution.
Override view() method or create new function by extending CI_Loader to achive desired result
public function my_view($file,$data)
{
$this->view("template/$file",$data);
}
AGood morning all.
I have build a website in codeigniter3 hmvc. all routes and callback function work perfectly on my localhost xampp and after uploading the project on godday share hosting live server I am facing callback funciton problems and below errors show in log file I don't understand why this happen. my user logging function also show this error:-
Unable to access an error message corresponding to your field name Password.(verifylogin)
Error Logs in logs folder of codeigniter
ERROR - 2015-09-16 01:30:08 --> 404 Page Not Found:
ERROR - 2015-09-16 01:30:29 --> 404 Page Not Found: /index
ERROR - 2015-09-16 01:30:30 --> 404 Page Not Found:
ERROR - 2015-09-16 01:31:30 --> Could not find the language line "form_validation_verifylogin"
ERROR - 2015-09-16 01:31:30 --> 404 Page Not Found: /index
These are my application/config/config.php
$config['index_page'] = "index.php?";
$config['uri_protocol'] = "QUERY_STRING";
$config['url_suffix'] = '';
$config['language'] = 'english';
Bellow is my application/config/routes.php setting
$route['Frontend/album_photos/(:num)/(:any)/(:num)'] = 'Frontend/album_photos/index/$1/$2/$3';
$route['Frontend/album_photos/(:num)/(:any)'] = 'Frontend/album_photos/index/$1/$2';
$route['Frontend/news_detail/(:num)/(:any)'] = 'Frontend/news_detail/index/$1/$2';
$route['(:any)/(:any)'] = 'Frontend/index/$1';
$route['(:any)'] = 'Frontend/index/$i';
$route['default_controller'] = 'Frontend/index';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['Frontend/download_documents'] = 'Frontend/download_documents/$1';
//these routes works for admin panel
$route['Users/index'] = 'Users/index';
$route['Users/validate_login'] = 'Users/validate_login';
$route['Users/logout'] = 'Users/logout';
$route['Dashboard/index'] ='Dashboard/index';
$route['Aps_pages/manage'] ='Aps_pages/manage';
$route['Aps_pages/create'] ='Aps_pages/create';
$route['Aps_pages/submit'] ='Aps_pages/submit';
$route['Aps_pages/delete'] ='Aps_pages/delete';
$route['Aps_news/manage'] ='Aps_news/manage';
$route['Aps_news/create'] ='Aps_news/create';
$route['Aps_news/submit'] ='Aps_news/submit';
$route['Aps_news/delete'] ='Aps_news/delete';
$route['Aps_events/manage'] ='Aps_events/manage';
$route['Aps_events/create'] ='Aps_events/create';
$route['Aps_events/submit'] ='Aps_events/submit';
$route['Aps_events/delete'] ='Aps_events/delete';
$route['Document_upload/manage'] ='Document_upload/manage';
$route['Document_upload/create'] ='Document_upload/create';
$route['Document_upload/submit'] ='Document_upload/submit';
$route['Document_upload/delete'] ='Document_upload/delete';
$route['Aps_image_slider/manage'] ='Aps_image_slider/manage';
$route['Aps_image_slider/create'] ='Aps_image_slider/create';
$route['Aps_image_slider/submit'] ='Aps_image_slider/submit';
$route['Aps_image_slider/delete'] ='Aps_image_slider/delete';
$route['Aps_testimonials/manage'] ='Aps_testimonials/manage';
$route['Aps_testimonials/create'] ='Aps_testimonials/create';
$route['Aps_testimonials/submit'] ='Aps_testimonials/submit';
$route['Aps_testimonials/delete'] ='Aps_testimonials/delete';
$route['Aps_album_photo/manage'] ='Aps_album_photo/manage';
$route['Aps_album_photo/create'] ='Aps_album_photo/create';
$route['Aps_album_photo/submit'] ='Aps_album_photo/submit';
$route['Aps_album_photo/delete'] ='Aps_album_photo/delete';
$route['Aps_album_photo/search_result'] ='Aps_album_photo/search_result';
$route['Aps_photo_album/manage'] ='Aps_photo_album/manage';
$route['Aps_photo_album/create'] ='Aps_photo_album/create';
$route['Aps_photo_album/submit'] ='Aps_photo_album/submit';
$route['Aps_photo_album/delete'] ='Aps_photo_album/delete';
This is my Home.php Controller in Frontend Modules
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends MX_Controller
{
public $data =array();
function __construct()
{
parent::__construct();
$this->load->model('mdl_home');
$this->load->helper('site_helper');
$this->load->library('pagination');
}
public function index()
{
$slug = (string)$this->uri->segment(1);
//die($slug.'=is a slug');
$this->data['page'] = $this->mdl_home->get_pages(trim($slug));
// Fetch the page data
if(!empty($this->data['page'])){
$method = '_' .trim($this->data['page']->ViewTemplate);
if (method_exists($this, $method)) {
$this->$method();
}
else {
//die('nothing found method not found');
log_message('error', 'Could not load template ' . $method .' in file ' . __FILE__ . ' at line ' . __LINE__);
show_error('Could not load template ' . $method);
}
//some config to view out put
$this->data['view_file'] = $this->data['page']->ViewTemplate;
$this->data['module_name'] ='Frontend';
//these variable used for main page layout meta keywords description title
$this->data['page_title'] = $this->data['page']->Title;
$this->data['keywords'] = $this->data['page']->Keywords;
$this->data['description'] = $this->data['page']->Description;
$this->data['body'] = $this->data['page']->Body;
//load template module for front end
$this->load->module('Template');
$this->template->frontend_layout($this->data);
}else{
show_404();
}
}
//home page method
private function _home_page(){
$this->data['SliderList'] = $this->mdl_home->get_slider_list();
$this->data['NewsList'] = $this->mdl_home->get_news_with_limit('aps_news',12,'','','NewsDate DESC');
$this->data['EventsList'] = $this->mdl_home->get_event_list();
$this->data['TestimonialList'] = $this->mdl_home->get_testimonial_list();
$this->data['Documents'] = $this->mdl_home->get_uploaded_documents();
}
//this method is for static pages
private function _static_page(){
}
//this method load news page
private function _news_page(){
$table = 'aps_news';
$offset = ($this->uri->segment(2) != '' ? $this->uri->segment(2): 0);
$config['total_rows'] = $this->mdl_home->total_rows($table);
$config['per_page']= 20;
$config['uri_segment'] = 2;
$choice = $config["total_rows"] / $config["per_page"];
$config["num_links"] = floor($choice);
$config['base_url']= site_url((string)$this->uri->segment(1));
$this->pagination->initialize($config);
$this->data['paginglinks'] = $this->pagination->create_links();
$this->data['NewsList'] = $this->mdl_home->get_news_with_limit($table,$config["per_page"], $offset,'NewsDate DESC');
}
//this method load contact page
private function _contact_page(){
}
//this method load events page
private function _events_page(){
$table = 'aps_events';
$offset = ($this->uri->segment(2) != '' ? $this->uri->segment(2): 0);
$config['total_rows'] = $this->mdl_home->total_rows($table);
$config['per_page']= 20;
$config['uri_segment'] = 2;
$choice = $config["total_rows"] / $config["per_page"];
$config["num_links"] = floor($choice);
$config['base_url']= site_url((string)$this->uri->segment(1));
$this->pagination->initialize($config);
$this->data['paginglinks'] = $this->pagination->create_links();
$this->data['EventsList'] = $this->mdl_home->get_with_limit($table,$config["per_page"], $offset,'EventDate DESC');
}
//this method load photo album page
private function _album_page(){
$table = 'aps_photo_album';
$offset = ($this->uri->segment(2) != '' ? $this->uri->segment(2): 0);
$config['total_rows'] = $this->mdl_home->total_rows($table);
$config['per_page']= 12;
$config['uri_segment'] = 2;
$choice = $config["total_rows"] / $config["per_page"];
$config["num_links"] = floor($choice);
$config['base_url']= site_url((string)$this->uri->segment(1));
$this->pagination->initialize($config);
$this->data['paginglinks'] = $this->pagination->create_links();
$this->data['AlbumList'] = $this->mdl_home->get_with_limit($table,$config["per_page"], $offset,'AlbumID DESC');
}
public function download_documents($file){
$this->load->helper('download');
$path = './assets/uploaded_documents/'.$file;
force_download($path, NULL);
redirect(base_url());
}
}
This is my Form Validation Library file
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation{
function run($module = '', $group = ''){
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
and this is my Users Controller file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends MX_Controller
{
public function __construct()
{
parent::__construct();
//load financial year
$this->load->model('mdl_users');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
redirect('Dashboard');
}else
{
$this->login();
}
}
//this function used to show login form view in template one column layout view
public function login()
{
$data['view_file'] = "loginform";
$data['module_name'] ='Users';
$data['page_title'] = 'Login Page';
$this->load->module('Template');
$this->template->login_layout($data);
}
//after entering the login values login form submit value handled by this function or method
public function validate_login()
{
$this->form_validation->set_error_delimiters('<div style="color:red;">', '</div>');
$this->form_validation->set_rules('username', 'Username', 'required|max_length[30]|xss_clean');
$this->form_validation->set_rules('password','Password', 'required|callback_verify_login');
if ($this->form_validation->run($this) == FALSE)
{
$this->index();
}
}
//this function for callback validation after submit button press
public function verify_login() {
$username = $this->input->post('username');
$password = $this->input->post('password');
//this method is in model folder/directory which interact with database https://www.youtube.com/watch?v=8fy8E_C5_qQ
$user = $this->mdl_users->check_login_authentication($username, $password);
if(empty($user)){
$this->form_validation->set_message('verify_login', 'Sorry the details you provided have not been found');
return FALSE;
}else{
//set user data in session and redirect to dashboard
$data = array(
'username' =>$user->UserName,
'userid' => $user->UserID,
'logged_in' => TRUE
);
$this->session->set_userdata($data);
redirect('Dashboard');
}
}
//logout function
public function logout()
{
$this->session->sess_destroy();
redirect('Users');
}
}
I have tried many ways of getting the username in codeigniter models. that matches the row id. But can not seem to get my model to work.
I have looked at user guide many times all ways get errors.
It shows the row id / user id OK when echo it
But can not seem to make a model to be able to match username with row id and then echo it.
Any suggestion on suitable model function.
when I click on my edit button it shows up in url http://localhost/codeigniter/codeigniter-blog/admin/users/edit/1 which works.
Model
// Not return username that matches id.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_user extends CI_Model {
function getUsername() {
$this->db->select('username');
$this->db->where('user_id');
$query = $this->db->get('user');
return $query->row();
}
}
Controller function.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('user');
if ($this->session->userdata('isLogged') == TRUE) {
return true;
} else {
redirect('/');
}
}
public function index() {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['text_enabled'] = "Enabled";
$data['text_disabled'] = "Disabled";
$results = $this->model_user->getUsers();
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'edit' => site_url('users/edit/' . $result['user_id'])
);
}
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_list', $data);
}
function edit($user_id = 0, $user_group_id = 0) {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['user_id'] = "Current User ID" . " " . $user_id . ":";
$data['user_group_id'] = "Current User Group ID" . " " . $user_group_id . ":";
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername();
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
}
}
'where' requires a second argument, which you would pass as an argument to your model function. so something like this in the model
class Model_user extends CI_Model {
function getUsername($id) {
$this->db->select('username');
$this->db->where('user_id', $id);
$query = $this->db->get('user');
return $query->row();
}
}
this corresponds to an sql query like
SELECT username FROM user WHERE user_id = ?
so in the controller just pass the user id in the argument to the model function
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername($user_id);
I have found best way to get my username to match user id
On My Model
function getUsername($user_id) {
if (empty($user_id)) {
return FALSE;
}
$this->db->select('username');
$this->db->where('user_id', $user_id);
$query = $this->db->get('user');
if ($query->num_rows() == 1) {
$result = $query->result_array();
return $result[0]['username'];
} else {
return FALSE;
}
}
on Controller function
$this->model_user->getUsername($user_id);
I want to have a simple helper which records one hit in my database. I have created a $CI instance and attempt to access the model like this...
$CI->load->model('stats_model');
$CI->stats_model->set_hit();
But i get an error in the model..
Severity: Notice
Message: Undefined property: Stats_model::$db
Filename: models/stats_model.php
Line Number: 16
Line 16 is a simple...
$this->db->select('*');
I got the idea to do this from this link http://blog.avinash.com.np/2010/07/01/talk-to-the-database-from-a-helper-codeigniter/
I have tried $CI->db... instead of $this->db in the model but still no luck, any ideas?
HELPER
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
function check_hit() {
//stuff that uses CI
$CI = & get_instance();
$CI->load->library('user_agent');
if ($CI->agent->is_robot()) {
return FALSE;
} else {
//check for a 12 hour cookie
$check = $CI->input->cookie('stat');
if ($check == false) {
//insert a database entry
$CI->load->model('Stats_model');
$CI->Stats_model->set_hit();
//set a cookie
$cookie = array(
'name' => 'stat',
'value' => '1',
'expire' => '43200'
);
// $CI->input->set_cookie($cookie);
}
}
}
check_hit();
?>
MODEL
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Stats_model extends Model {
function Stats_model() {
// Call the Model constructor
parent::Model();
}
function set_hit() {
$date = date('Y-m-d');
$this->db->select('unique_visitors');
$this->db->from('daily_stats');
$this->db->where('date', $date);
$query = $this->db->get();
$date_rows = $query->num_rows();
$result = $query->row();
$visits = $result->unique_visitors;
$visits++;
$data = array(
'unique_visitors' => $visits,
'date' => $date
);
if ($date_rows == 1) {
$this->db->where('date', $date);
$this->db->update('daily_stats', $data);
} else {
$this->db->insert('daily_stats', $data);
}
}
}
?>
This part was a little confusing for me a while back. This seemed to work.
//load the CI instance
$this->ci =& get_instance();
//run a db get
$this->ci->db->get('mytable');