Welcome Guest, Not a member yet? Register   Sign In
Error trying to load a library inside the view
#1

[eluser]Ricardo SDL[/eluser]
I'm lost here. I created a library (one simple class) and used it in the controller with no problems. Then I tried to load it in the view just to call one method of the class. The constructuor of the class get called but the reference of the class stays as null.
Some code:
This works (controller):
Code:
$this->load->library('search_vehicle_params_manager');
$this->search_vehicle_params_manager->search_vehicle_params = $search_params;
$this->search_vehicle_params_manager->save_params();
return $this->search_vehicle_params_manager;
This doesn't work (view):
Code:
$this->load->library('search_vehicle_params_manager');
$params_manager = $this->search_vehicle_params_manager;
$search_vehicle_type = $params_manager->get_param_value(Search_vehicle_params_manager::VEHICLE_TYPE);
I get this error message:
Quote:A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_Loader::$search_vehicle_params_manager

Filename: views/header.php

Line Number: 64

I'm using CI 1.7.2 and this is the php version information:
PHP 5.2.6-2ubuntu4.3 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 21 2009 20:36:27)
Copyright © 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright © 1998-2008 Zend Technologies

The only piece of code executed inside the library constructor is this onde:
Code:
$this->ci = & get_instance();
I've checked that in the view this code is executed. Probably is a dumb mistake, any ideas?
Thanks!
#2

[eluser]Jamie Rumbelow[/eluser]
The simple answer here is don't! It's never a good idea to call libraries within your views - that's what your controllers and models are for. Instead of loading and referencing the library within your view, load it and get the data you need in your controller then pass that to the view to display it. A quick example:

Code:
//Controller
$this->load->library('search_vehicle_params_manager');

$data['search_vehicle_type'] = $this->search_vehicle_params_manager->get_param_value(Search_vehicle_params_manager::VEHICLE_TYPE);
$this->load->view('header', $data);

Then, in your view, you can access the data as a variable:

Code:
<p>Type: &lt;?=$search_vehicle_type?&gt;</p>

By convention you won't ever want to call libraries in your views - it clogs them up and makes them messy. Instead move this functionality into the controller or model and clean up the view, minimising logic and making the view nice and pretty.

Jamie
#3

[eluser]Ricardo SDL[/eluser]
Thanks for the tips Jamie Rumbelow! I changed the code to not have to load the library. So, is there any way to load libraries in views or it is not allowed do this in CI?




Theme © iAndrew 2016 - Forum software by © MyBB