This is my custom validation function. It uses geocoding from a Google Maps CodeIgniter library to check if a location exists.
public function address_check($str)
{
$this->load->library('GMap');
$this->gmap->GoogleMapAPI();
// this method checks the cache and returns the cached response if available
$geocodes = $this->gmap->getGeoCode("{$str}, United States");
$this->form_validation->set_message('address_check', 'The %s field contains an invalid address');
if (empty($geocodes))
{
return FALSE;
}
else
{
return TRUE;
}
}
If I place the function above inside my Controller along with the following rule, it works perfectly well.
$this->load->library('form_validation');
$this->form_validation->set_rules('location', 'Location', 'callback_address_check');
Now I simply want to move it out of my Controller. So I'm trying to extend my CodeIgniter Form Validation library as per this SO answer and the CI documentation.
I created a file here: /codeigniter/application/libraries/MY_Form_validation.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct()
{
parent::__construct();
}
public function address_check($str)
{
$this->load->library('GMap');
$this->gmap->GoogleMapAPI();
// this method checks the cache and returns the cached response if available
$geocodes = $this->gmap->getGeoCode("{$str}, United States");
$this->form_validation->set_message('address_check', 'The %s field contains an invalid address');
if (empty($geocodes))
{
return FALSE;
}
else
{
return TRUE;
}
}
}
And from within my controller, I am setting the rule like this...
$this->load->library('form_validation');
$this->form_validation->set_rules('location', 'Location', 'address_check');
The first problem I found and solved myself was that nothing was happening because that SO answer incorrectly specified the file name to be My_Form_validation.php where it should have been MY_Form_validation.php
Now that the function is being called, the new problem is that I am getting the following error:
Message: Undefined property: MY_Form_validation::$load
Filename: libraries/MY_Form_validation.php
Line Number: 12
This is line 12:
$this->load->library('GMap');
I can't access a library from within a library? What's the proper way to fix this? I'd prefer not to auto-load the GMap library since I won't be using it all the time. Any other problems within my method?
Use this:
$CI =& get_instance();
$CI->load->library('GMap');
And then use it like:
$CI->gmap->GoogleMapAPI();
You have to do it that way, because Form Validation is not like CI Model or Controller class, it's only library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With