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);
}
Related
I have my little project running perfectly on my local computer. However, when I run it into my laptop, an entry is automatically loaded in my ci_sessions table each time the page is being reloaded or refresh. I am using the database as my session driver.
Based on the screenshot: row 4 says that my login session store successfully. However, the 2 extra rows (5, 6) that are being added cause this code to fail:
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
here's my config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
Here's my Page Controller
<?php
class Pages extends MY_Controller
{
public function view($page = 'login')
{
if (!file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
if($page == 'login') {
$this->isLoggedIn();
$this->load->view($page, $data);
}
else{
$this->isNotLoggedIn();
$this->load->view($page, $data);
}
}
}
MY_Controller Class
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
}
So far I have already tried adding the code below to my autoload.php but no luck.
$autoload['libraries'] = array('database', 'session');
Note: again this works in another unit with a similar setup.
after trying some work around, Codeigniter 3 is not yet compatible with php 7. I have to downgrade my php version to 5.6 to make it work. thanks folks for helping.
I suffered a lot of troubles with the original CI session library (included what you mention). Finally I arrived to this replacement that use native PHP session. It works!
Believe me, in the middle of a project, I did not stop to wonder why. Just works.
Here it is: CodeIgniter Native Session
BUT, due that it is an old library you MUST made some hacks. You can check those simple hacks in the library's forum
Just drop this file in codeigniter's library directory.
I have a website with a url like so (which works fine)
http://www.page.com/en/controller
But there always have to be a language and a controller in the url otherwise the page doesn't load or there is no language (no text).
Is it possible that when I enter a url like this
http://www.page.com
I get redirected to
http://www.page.com/en/controller
And the controller would be hidden? Only this would be left (my links require first segment to load a page with a particular language)
http://www.page.com/en
p.s tried routing and redirect, but with no luck
Sorry for the late response, I was away.
my routes
$route['default_controller'] = 'arena/display';
$route['(:any)/renginiai'] = "renginiai/getevents";
$route['(:any)/arena'] = "arena/display";
$route['(:any)/paslaugos'] = "paslaugos/displayServices";
$route['(:any)/kontaktai'] = "kontaktai/displayContacts";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
My_Controller which is located in core folder. I load my language libraries from here.
/**
*
*/
class MY_Controller extends CI_Controller{
public function __construct()
{
parent::__construct();
$languages = array("lt", "en");
if(in_array($this->uri->segment(1), $languages)){
$this->lang->load($this->uri->segment(1), $this->uri->segment(1));
}
}
}
And this is my front page controller
<?php
class Arena extends MY_Controller{
public function display($year = NULL, $month = NULL){
/*$this->load->model('Mycal_model');*/
$this->load->model('Image_model');
$data['images'] = $this->Image_model->get_image_data();
$this->load->view('includes/head');
$this->load->view('includes/nav', $data);
$this->load->view('includes/header', $data);
//$this->load->view('includes/calendar', $data);
$this->load->view('includes/section');
$this->load->view('includes/footer');
}
}
open application/config/routes.php file and change
$route['default_controller'] = "en/controller";
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 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");
}
}
I'm running a shell script via a cron job. It correctly sends an email. However I want to be able to pass data to the email template from the database which I seem unable to do.
Here is the shell
App::import('Core', 'Controller');
App::import('Component', 'Email');
class ExampleShell extends Shell {
var $uses = array('User');
function main() {
$users = $this->User->find('all');
$this->Controller =& new Controller();
$this->Email =& new EmailComponent(null);
$this->Email->initialize($this->Controller);
$this->Email->reset();
$this->Email->to = 'xx<xx#xx.com>';
$this->Email->subject = "Subject";
$this->Email->template = 'example';
$this->Email->sendAs = "both";
$this->Controller->set('users', $users);
$this->Email->send();
}
}
The variable $users does not seem to be available in the example.ctp file? How can I pass data from the shell script to the template please?
I managed to do it in following way
class ExampleShell extends Shell {
var $uses = array('User');
var $Controller = null;
function __construct(&$dispatch) {
App::import('Core', 'Controller');
App::import('Controller', 'App');
$this->Controller = & new Controller();
App::import('Component', 'Email');
$this->Email = new EmailComponent();
$this->Email->initialize($this->Controller);
parent::__construct($dispatch);
}
function main() {
$users = $this->User->find('all');
$this->Controller =& new Controller();
$this->Email =& new EmailComponent(null);
$this->Email->initialize($this->Controller);
$this->Email->reset();
$this->Email->to = 'xx<xx#xx.com>';
$this->Email->subject = "Subject";
$this->Email->sendAs = "both";
$this->Controller->set('users', $users);
$this->Email->send(null, 'template_1');
}
}
I hope it helps someone.
Make sure template is located where it should be app/views/elements/email/html/template_1.ctp and app/views/elements/email/text/template_1.ctp for text version. You should create layouts too in app/views/layouts/email/html/default.ctp and app/views/layouts/email/text/default.ctp