Posted on 21 February 2011. Tags: codeigniter, php
Much like fashion models, it seems that managing CodeIgniter models can be a little tricky. I always ended up with a massive pile of set_value() calls for each of the elements I wanted to load in. In order to ‘bosh this, I wrote this function to do it automagically.
It will grab all the variables you’ve declared for the model, then try to load them up with submitted data. Nifty.
function load_model() {
$vars = get_class_vars(get_class($this));
unset($vars['_parent_name']);
foreach($vars as $key => $value) {
$this->$key = $this->input->post($key);
}
}
Posted in Code
Posted on 24 March 2010. Tags: codeigniter, php, regex, validation
The Form Validation class in CodeIgniter does a lot of fantastic things. Validating phone numbers isn’t one of them. Here is a script I’ve paraphrased to take in almost any format of U.S. phone number and use regular expressions to return it like this: (555) 555-1212.
function _validate_phone_number($value) {
$value = trim($value);
$match = '/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/';
$replace = '/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/';
$return = '($1) $2-$3';
if (preg_match($match, $value)) {
return preg_replace($replace, $return, $value);
} else {
$this->form_validation->set_message('_validate_phone_number', 'Invalid Phone.');
return false;
}
}
Posted in Code