I put the line
$route['404_override'] = 'my404';
in the routes.php file, and I made a controller with a name my404:
<?php
include 'page.php';
class My404 extends Page {
private $page;
public function __construct() {
$page = new stdClass();
parent::__construct();
}
public function index() {
// $this->page->page_title = "Page not found!";
$this->page_view($this->load->view('my404', $this->page, true));
}
}
?>
and I made a View with a name of my404
It is working fine when I make a syntax error in the controller name, but it won't work if I write a wrong method and a Server error will occur instead of the customized 404 page, have I missed something in the routes.php file ?
From Codeigniter user guide:
This route indicates which controller class should be loaded if the requested controller is not found.
Apparently that rout will only work when controller isn't found.
you can instead override the default error_404 page at 'application/errors/error_404.php'.
I have a variable, contaning data that should be present in the entire site. Instead of passing this data to each view of each controller, I was wondering if there is a way to make this data available for every view in the site.
Pd. Storing this data as a session variable / ci session cookie is not an option.
Thanks so much.
Create a MY_Controller.php file and save it inside the application/core folder. In it, something like:
class MY_Controller extends CI_Controller {
public $site_data;
function __construct() {
parent::__construct();
$this->site_data = array('key' => 'value');
}
}
Throughout your controllers, views, $this->site_datais now available.
Note that for this to work, all your other controllers need to extend MY_Controllerinstead of CI_Controller.
You need to extend CI_Controller to create a Base Controller:
https://www.codeigniter.com/user_guide/general/core_classes.html
core/MY_Controller.php
<?php
class MY_Controller extend CI_Controller {
public function __construct() {
parent::__construct();
//get your data
$global_data = array('some_var'=>'some_data');
//Send the data into the current view
//http://ellislab.com/codeigniter/user-guide/libraries/loader.html
$this->load->vars($global_data);
}
}
controllers/welcome.php
class Welcome extend MY_Controller {
public function index() {
$this->load->view('welcome');
}
}
views/welcome.php
var_dump($some_var);
Note: to get this vars in your functions or controllers, you can use $this->load->get_var('some_var')
Set in application/config/autoload.php
$autoload['libraries'] = array('config_loader');
Create application/libraries/Config_loader.php
defined('BASEPATH') OR exit('No direct script access allowed.');
class Config_loader
{
protected $CI;
public function __construct()
{
$this->CI =& get_instance(); //read manual: create libraries
$dataX = array(); // set here all your vars to views
$dataX['titlePage'] = 'my app title';
$dataX['urlAssets'] = base_url().'assets/';
$dataX['urlBootstrap'] = $dataX['urlAssets'].'bootstrap-3.3.5-dist/';
$this->CI->load->vars($dataX);
}
}
on your views
<title><?php echo $titlePage; ?></title>
<!-- Bootstrap core CSS -->
<link href="<?php echo $urlBootstrap; ?>css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap theme -->
<link href="<?php echo $urlBootstrap; ?>css/bootstrap-theme.min.css" rel="stylesheet">
If this is not an Variable(value keep changing) then I would suggest to create a constant in the constant.php file under the config directory in the apps directory, if it's an variable keep changing then I would suggest to create a custom controller in the core folder (if not exist, go ahead an create folder "core") under apps folder. Need to do some changes in other controller as mentioned here :
extend your new controller with the "CI_Controller" class. Example
open-php-tag if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class LD_Controller extends CI_Controller {
}
close-php-tag
Here LD_ is my custom keyword, if you want to change you can change it in config.php file under line# 112 as shown here : $config['subclass_prefix'] = 'LD_';
and extend this class in all your controllers as "class Mynewclass extends LD_Controller..
And in LD_controller you've to write the method in which you want to define the variable/array of values & call that array in all over the application as shown here :
defining variable :
var $data = array();
Method to get values from db through the Model class:
function getbooks()
{
$books = $this->mybooks_model->getbooks(); //array of records
$this->data = array('books'=>$books);
}
to call this variable in the views : print_r($this->data['books']);); you will get all the array values... here we've to make sure atleast one "$data" parameter needs to be passed if not no problem you can define this $data param into the view as shown here :
$this->load->view('mybookstore',$data);
then it works absolutely fine,,, love to share... have a fun working friends
you can use $this->load->vars('varname', $data);[ or load data at 1st view only] onse and use in any loaded views after this
Use sessions in your controllers
$this->session->set_userdata('data');
then display them in your view
$this->session->userdata('data');
Or include a page in base view file e.g index.php
include "page.php";
then in page.php,
add $this->session->userdata('data'); to any element or div
then this will show on all your views
I read all answers, but imho the best approch is via hook:
Create hook, let's get new messages for example:
class NewMessages {
public function contact()
{
// Get CI instance CI_Base::get_instance();
$CI = &get_instance(); // <-- this is contoller in the matter of fact
$CI->load->database();
// Is there new messages?
$CI->db->where(array('new' => 1));
$r = $CI->db->count_all_results('utf_contact_requests');
$CI->load->vars(array('new_message' => $r));
}
}
Attach it to some of the flow point, for example on 'post_controller_constructor'. This way, it will be loaded every time any of your controller is instantiated.
$hook['post_controller_constructor'][] = array(
'class' => 'NewMessages',
'function' => 'contact',
'filename' => 'NewMessages.php',
'filepath' => 'hooks',
'params' => array(),
);
Now, we can access to our variable $new_message in every view or template.
As easy as that :)
You could override the view loader with a MY_loader. I use it on a legacy system to add csrf tokens to the page where some of the forms in views don't use the builtin form generator. This way you don't have to retrospectively change all your controllers to call MY_Controller from CI_Controller.
Save the below as application/core/MY_Loader.php
<?php
class MY_Loader extends CI_Loader {
/**
* View Loader
*
* Overides the core view function to add csrf token hash into every page.
*
* #author Tony Dunlop
*
* #param string $view View name
* #param array $vars An associative array of data
* to be extracted for use in the view
* #param bool $return Whether to return the view output
* or leave it to the Output class
* #return object|string
*/
public function view($view, $vars = array(), $return = FALSE)
{
$CI =& get_instance();
$vars['csrf_token'] = $CI->security->get_csrf_hash();
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return));
}
}
When I try to call
$this->load->database();
yields the following error `"Call to a member function database() on a non-object"
Autoloading the database doesnt help too...
when I try to autoload it.
all calls to database like
$this->db->get('people');
it says get method is undefined...
I have no clue what and where to start..\
anyone ?
Go to autoload.php in application/config/autoload.php and add this
$autoload['libraries'] = array('database'); // add database in array
Make sure your connection settings are fine in application/config/database.php
Than in the library do it like this
Class MyLib
{
function getPeople(){
$CI = &get_instance();
$query = $CI->db->get('people');
return $query->result();
}
}
Use extends CI_Model if not working try extends Model
class User_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
}
You can load the database by two methods:
Method 1:Automatic Connecting
$autoload['libraries']=array('database');
Method 2: Manual Connecting
$this->load>database();
i hope above methods clear your confusion....
You are doing a very common mistake. When you call $this->load->database(); from controller or model it works because controllers and models are child of CI_Controller and CI_Model respectively. But when you are call them from Library which is not a child class of any basic CIclass you cannot load database() or anything else using $this-> key. you must use the help of &get_instance(); to load codeigniter instance and use that instance instead of $this. Which suggests following Code:
$INST=&get_instance();//Store instance in a variable.
$INST->load->database();//If autoload not used.
$INST->db->get('people');//or Your desired database operation.
It is better to keep a field variable to hold the reference to $INSTas you may need to access it in various functions.
Following Code will be more eligent:
class MyLib{
var $INST;
public function __construct()
{
$INST=&get_instance();//Store instance in a variable.
$INST->load->database();//If autoload not used.
}
function getPeople(){
$query = $INST->db->get('people');
return $query->result();
}
}
I have installed Wanwizard's Datamapper (http://datamapper.wanwizard.eu) in an empty codeigniter setup.
I have no problem using datamapper in my controllers, but when I try to call datamapper objects in my libraries.
I get the error: Fatal error: Class 'User' not found.
This is my code for my library:
class Auth {
protected $ci;
public function __construct()
{
$this->ci =& get_instance();
$this->ci->load->library('datamapper');
}
public function signup( $username, $email, $password )
{
$user = new User();
}
}
Does anyone know the correct way to call these datamapper objects within libraries?
You probably have resolved this already. To folks of the future visiting this:
The issue, as WanWizard points out, is either:
You aren't autoloading datamapper in application/config/autoload.php:
$autoload['libraries'] = array('database', 'datamapper');
The application/models folder does not contain a User.php file.
The User.php file does not contain a class User extends Datamapper{}.
Also -- Linux is a case sensitive operating system, be careful to follow the cases used in the Datamapper and CodeIgniter documentation when naming your files.
I am trying to design a user registration form using code igniter 2.1.0. I have used the following code in the regitration.php in controllers to add users.
class Registration extends CI_Controller
{
function __construct() {
parent::__construct();
}
function index()
{
$data['main_content'] = 'registration';
// Checks to see if form validation rules were met an executed properly. If not, will return with registration form.
if ($this->form_validation->run('registration') === FALSE)
{
$data ['title'] = 'Registration';
$this->load->view('include/template', $data);
}
// If validation passes, information will be passed along to the MODEL to be processed and the account will be created.
else
{
$this->load->model('registration_model');
$this->registration_model->addUser();
$this->session->set_flashdata('success', 'Your account has been successfully created');
redirect(uri_string());
}
}
}
But it showed me an error of Call to a member function run() on a non-object. How do i correct that?
Please include
// load 'form' helper
$this->load->helper('form');
// load 'validation' class
$this->load->library('form_validation');
and try now
function __construct() {
// load controller parent
parent::__construct();
// load 'url' helper
$this->load->helper('url');
// load 'form' helper
$this->load->helper('form');
// load 'session'
$this->load->library('session');
// load 'validation' class
$this->load->library('form_validation');
}
It seems like $session class is not initializing correctly.
Check for default_ci_sessions table, if you are using sessions for database.
Check if the constructor is loading sessions library.
Check if session is in autoload.php config
For this "In order to use the Session class you are required to set an encryption key in your config file.".
add this to your config.php
$config['encryption_key'] = 'your_encryption_key_here';