FUEL CMS User Guide : Version 1.5.2


My Model Class

An extension of the Model class to map data operations to a table. Depends upon the Validator library, date helper and the string helper.

Inspired from this post here Developer13: http://codeigniter.com/forums/viewthread/88769/.

This class extends the CI_Model class.

Properties Reference

Property Default Value Description
public
auto_validate 1 Use auto-validation before saving
return_method auto Object, array, query, auto
auto_validate_fields
array('email|email_address' => 'valid_email', 'phone|phone_number' => 'valid_phone', )
fields to auto validate
required
array()
An array of required fields. If a key => val is provided, the key is name of the field and the value is the error message to display
default_required_message Please fill out the required field '%1s' The default required validator message
auto_date_add
array('date_added', 'entry_date')
Field names to automatically set the date when the value is NULL
auto_date_update
array('last_modified', 'last_updated')
Field names to automatically set the date on updates
date_use_gmt none Determines whether to use GMT time when storing dates and times
default_date none Default date value that get's passed to the model on save. Using 0000-00-00 will not work if it is a required field since it is not seen as an empty value
auto_trim 1 Will trim on clean
auto_encode_entities 1 Determines whether to automatically encode html entities. An array can be set instead of a boolean value for the names of the fields to perform the safe_htmlentities on
xss_clean none Determines whether automatically run the xss_clean. An array can be set instead of a boolean value for the names of the fields to perform the xss_clean on
readonly none Sets the model to readonly mode where you can't save or delete data
hidden_fields
array()
Fields to hide when creating a form
unique_fields
array()
Fields that are not IDs but are unique. Can also be an array of arrays for compound keys
linked_fields
array()
Fields that are linked meaning one value helps to determine another. Key is the field, value is a function name to transform it. (e.g. array('slug' => 'title'), or array('slug' => array('name' => 'strtolower')));
serialized_fields
array()
Fields that contain serialized data. This will automatically serialize before saving and unserialize data upon retrieving
default_serialization_method json The default serialization method. Options are 'json' and 'serialize'
boolean_fields
array()
Fields that are tinyint and should be treated as boolean
suffix _model The suffix used for the data record class
foreign_keys
array()
Map foreign keys to table models
has_many
array()
Keys are model, which can be a key value pair with the key being the module and the value being the model, module (if not specified in model parameter), relationships_model, foreign_key, candidate_key
belongs_to
array()
Keys are model, which can be a key value pair with the key being the module and the value being the model, module (if not specified in model parameter), relationships_model, foreign_key, candidate_key
representatives
array()
An array of fields that have arrays or regular expression values to match against different field types (e.g. 'number'=>'bigint|smallint|tinyint|int')
custom_fields
array()
An array of field names/types that map to a specific class
formatters
array()
An array of helper formatter functions related to a specific field type (e.g. string, datetime, number), or name (e.g. title, content) that can augment field results
protected
db N/A
table_name N/A
key_field N/A Usually the tables primary key(s)... can be an array if compound key
normalized_save_data N/A The saved data before it is cleaned
cleaned_data N/A Data after it is cleaned
dsn N/A The DSN string to connect to the database... if blank it will pull in from database config file
has_auto_increment N/A Does the table have auto_increment?
record_class N/A The name of the record class (if it can't be determined)
friendly_name N/A A friendlier name of the group of objects
singular_name N/A A friendly singular name of the object
rules N/A Validation rules
fields N/A Fields in the table
use_common_query N/A Include the _common_query method for each query
validator N/A The validator object
clear_related_on_save N/A Clears related records before saving
_tables N/A An array of table names with the key being the alias and the value being the actual table
_last_saved N/A A reference to the last saved object / ID of record;
_nested_errors N/A Used for capturing errors when saving multiple records (an array of records) on a single save method call

Function Reference [+]

$this->example_model->initialize(['$table'=NULL], [$params=array()])

Initialize the user preferences. Accepts an associative array as input, containing display preferences.

Returns

void

Parameters

(string) $table the table name
(array) $params config preferences

$this->example_model->set_db('$db')

Sets the database object for a model.

Returns

array

Example


	$db = $CI->db;
	$this->examples_model->set_db($db); 
	

$this->example_model->db()

Returns the database object.

Returns

array

Example


	$db = $this->examples_model->db(); 
	

$this->example_model->short_name(['$lower'=FALSE], ['$record_class'=FALSE])

Gets the short name minus the suffix.

Returns

array

Parameters

(boolean) $lower lower case the name (optional)
(boolean) $record_class return the record class name (optional)

Example


	echo $this->examples_model->short_name(TRUE); 
	// examples
	

$this->example_model->friendly_name(['$lower'=FALSE])

Gets the name of the model object. By default it will be the same as the short_name(FALSE, FALSE) if no "friendly_name" value is specified on the model.

Returns

array

Parameters

(boolean) $lower lower case the name (optional)

Example


	echo $this->examples_model->friendly_name(TRUE); 
	// examples
	

$this->example_model->singular_name(['$lower'=FALSE])

Gets the singular name of the model object. By default it will be the same as the short_name(FALSE, TRUE) if no "singular_name" value is specified on the model.

Returns

array

Parameters

(boolean) $lower lower case the name (optional)

Example


	echo $this->examples_model->singular_name(TRUE); 
	// example
	

$this->example_model->table_name()

Get the table name.

Returns

array

Example


	echo $this->examples_model->table_name(); 
	// examples
	

$this->example_model->has_auto_increment()

Returns whether the model uses auto_increment or not.

Returns

boolean

Example


	echo $this->examples_model->has_auto_increment(); 
	// TRUE
	

$this->example_model->set_tables($tables)

Sets the aliases to table(s) that you can use in your queries.

Returns

void

Parameters

(array) $tables an array of tables

Example


	$my_tables = array('mytable' => 'my_table');
	$this->examples_model->set_tables($my_tables); 
	

$this->example_model->tables(['$table'=NULL])

Gets the table(s) name based on the configuration.

Returns

string|array|null

Parameters

(string) $table the table name (optional)

Example


	$table_name = $this->examples_model->tables('my_table'); 
	

$this->example_model->key_field()

Get the key field(s).

Returns

array

Example


	$fields = $this->examples_model->key_field(); 
	

$this->example_model->fields()

Get the fields of the table.

Returns

array

Example


	 $fields = $this->examples_model->fields(); 
	 foreach($fields as $field)
	{
		echo $field; // field name
	}
	

$this->example_model->get(['$force_array'=TRUE], ['$return_method'=NULL], ['$assoc_key'=NULL], ['$use_common_query'=NULL])

Get the results of the query.

Returns

array

Parameters

(boolean) $force_array return multiple records (optional)
(string) $return_method method return type (object, array, query, auto) (optional)
(string) $assoc_key the column to use for an associative key array (optional)
(boolean) $use_common_query determine whether to use the _common_query method in the query (optional)

Example


	$rows = $this->examples_model->get(TRUE, 'object', FALSE); 
	foreach($rows->result() as $row)
	{
	    echo $row->name;
	}
	
	// The third parameter is the column name to be used as the array key value (if <dfn>$force_array</dfn> is set to <dfn>TRUE</dfn>)
	$rows = $this->examples_model->get(TRUE, 'object', 'id'); 
	foreach($rows->result() as $id => $row)
	{
	    echo $id;
	}
	

$this->example_model->map_query_records('$query', ['$assoc_key'=NULL])

Maps a query result object to an array of record objects.

Returns

array

Parameters

(object) $query the query object
(string) $assoc_key the field name to be used the key value (optional)

Example


	...
	$query = $this->db->query('SELECT FROM USERS');
	$users = $this->examples_model->map_query_records($query, 'id');
	foreach($users as $id => $user)
	{
	    echo $user->name;
	}
	

$this->example_model->map_to_record_class($row, ['$fields'=NULL])

Maps an associative record array to a record object.

Returns

array

Parameters

(array) $row field values
(array) $fields all the fields available for the object (optional)

Example


	$my_user['id'] = 1;
	$my_user['name'] = 'Darth Vader';
	$my_user['email'] = 'darth@deathstar.com';
	$my_custom_record = $this->examples_model->map_to_record_class($my_user); 
	echo $my_custom_record->name;
	

$this->example_model->find(['$find'='all'], ['$where'=NULL], ['$order'=NULL], ['$limit'=NULL], ['$offset'=NULL], ['$return_method'=NULL], ['$assoc_key'=NULL])

Get the results of the query.

Returns

array

Parameters

(string) $find the type of find to perform. Options are "key", "one", "options", "all" and find_"{your_method}". By default it will perform a find_all (optional)
(mixed) $where an array or string containing the where parameters of a query (optional)
(string) $order the order by of the query (optional)
(int) $limit the number of records to limit in the results (optional)
(int) $offset the offset value for the results (optional)
(string) $return_method return type (object, array, query, auto) (optional)
(string) $assoc_key the column to use for an associative key array (optional)

Example


	$examples = $this->examples_model->find_all(array('published' => 'yes'), 'date_added desc'); 
	

$this->example_model->find_by_key('$key_val', ['$return_method'=NULL])

Get one record result based on the key value.

Returns

array

Parameters

(string) $key_val the key value to find a single record
(mixed) $return_method return type (object, array, query, auto) (optional)

Example


	$id = 1;
	$example = $this->examples_model->find_by_key($id, 'object'); 
	

$this->example_model->find_one([$where=array()], ['$order_by'=NULL], ['$return_method'=NULL])

Get one record result.

Returns

array

Parameters

(mixed) $where an array or string containing the where parameters of a query (optional)
(string) $order_by the order by of the query (optional)
(string) $return_method return type (object, array, query, auto) (optional)

Example


	$example = $this->examples_model->find_one(array('published' => 'yes'), ''asc');
	

$this->example_model->find_one_array('$where', ['$order_by'=NULL])

Get one record result as an array.

Returns

array

Parameters

(mixed) $where an array or string containing the where parameters of a query
(string) $order_by the order by of the query (optional)

Example


	$examples = $this->examples_model->find_one_array(array('published' => 'yes'), 'date_added desc'); 
	

$this->example_model->find_all([$where=array()], ['$order_by'=NULL], ['$limit'=NULL], ['$offset'=NULL], ['$return_method'=NULL], ['$assoc_key'=NULL])

Get the results of the query.

Returns

array

Parameters

(mixed) $where an array or string containing the where parameters of a query (optional)
(string) $order_by the order by of the query (optional)
(int) $limit the number of records to limit in the results (optional)
(int) $offset the offset value for the results (optional)
(string) $return_method return type (object, array, query, auto) (optional)
(string) $assoc_key the column to use for an associative key array (optional)

Example


	$examples = $this->examples_model->find_all(array('published' => 'yes'), 'date_added desc');
	

$this->example_model->find_all_array([$where=array()], ['$order_by'=NULL], ['$limit'=NULL], ['$offset'=NULL])

Get the results of the query as an array.

Returns

array

Parameters

(mixed) $where an array or string containing the where parameters of a query (optional)
(string) $order_by the order by of the query (optional)
(int) $limit the number of records to limit in the results (optional)
(int) $offset the offset value for the results (optional)

Example


	$examples = $this->examples_model->find_all_array(array('published' => 'yes'), 'date_added desc'); 
	

$this->example_model->find_all_assoc(['$assoc_key'='id'], [$where=array()], ['$order_by'=NULL], ['$limit'=NULL], ['$offset'=NULL])

Get the results of the query returned as a keyed array of objects.

Returns

array

Parameters

(string) $assoc_key the column to use for an associative key array (optional)
(mixed) $where an array or string containing the where parameters of a query (optional)
(string) $order_by the order by of the query (optional)
(int) $limit the number of records to limit in the results (optional)
(int) $offset the offset value for the results (optional)

Example


	$examples = $this->examples_model->find_all_assoc(array('published' => 'yes'), 'date_added desc'); 
	

$this->example_model->find_all_array_assoc(['$assoc_key'='id'], [$where=array()], ['$order_by'=NULL], ['$limit'=NULL], ['$offset'=NULL])

Get the results of the query returned as a keyed array of arrays.

Returns

array

Parameters

(string) $assoc_key the column to use for an associative key array (optional)
(mixed) $where an array or string containing the where parameters of a query (optional)
(string) $order_by the order by of the query (optional)
(int) $limit the number of records to limit in the results (optional)
(int) $offset the offset value for the results (optional)

Example


	$examples = $this->examples_model->find_all_assoc(array('published' => 'yes'), 'date_added desc'); 
	

$this->example_model->find_within('$group', [$where=array()], ['$limit'=NULL], ['$offset'=NULL], ['$return_method'=NULL], ['$assoc_key'=NULL])

Get the results of a query from within a select group of key field values. Results are sorted by the order from within the group.

Returns

array

Parameters

(group) $group an array of keys to limit the search results to
(mixed) $where an array or string containing the where parameters of a query (optional)
(int) $limit the number of records to limit in the results (optional)
(int) $offset the offset value for the results (optional)
(string) $return_method return type (object, array, query, auto) (optional)
(string) $assoc_key the column to use for an associative key array (optional)

Example


	$examples = $this->examples_model->find_within(array(1, 2, 3, 4), array('published' => 'yes'), 'date_added desc'); 
	

$this->example_model->query([$params=array()], ['$exec'=TRUE])

This method takes an associative array with the key values that map to CodeIgniter active record methods and returns a query result object. For more advanced, use CI Active Record. Below are the key values you can pass:

  • select
  • from
  • join
  • where
  • or_where
  • where_in
  • or_where_in
  • where_not_in
  • or_where_not_in
  • like
  • or_like
  • not_like
  • or_not_like
  • group_by
  • order_by
  • limit
  • offset

Returns

array

Parameters

(array) $params an array of parameters to create a query (optional)
(boolean) $exec determines whether to execute the query and return the results or not

Example


	$where['select'] = 'id, name, published';
	$where['where'] = array('published' => 'yes');
	$where['order_by'] = 'name asc';
	$where['limit'] = 10;

	$query = $this->examples_model->query($where); 
	$results = $query->result(); 
	

$this->example_model->options_list(['$key'=NULL], ['$val'=NULL], [$where=array()], ['$order'=TRUE])

Get the results of a query as an associative array... good for form option lists.

Returns

array

Parameters

(string) $key the column to use for the value (optional)
(string) $val the column to use for the label (optional)
(mixed) $where an array or string containing the where parameters of a query (optional)
(mixed) $order the order by of the query. Defaults to TRUE which means it will sort by $val asc (optional)

Example


	$where['published'] = 'yes'; 
	$order = 'name, desc'; 
	$examples_list = $this->examples_model->options_list('id', 'name', $where, $order); 
	

$this->example_model->record_exists('$where')

Determine if a record exists in the database.

Returns

boolean

Parameters

(mixed) $where an array or string containing the where parameters of a query

Example


	$where['type'] = 'A'; 
	if ($this->examples_model->record_exists($where))
	{
		echo 'record exists';
	} 
	

$this->example_model->create([$values=array()])

Create a new record if a custom record object exists.

Returns

boolean

Parameters

(mixed) $values the record oject associated with this class (optional)

Example


	$example = $this->examples_model->create($_POST); // Be sure to always clean your $_POST variables before using them
	

$this->example_model->find_or_create([$values=array()])

Will first look for a record with the past values and if it doesn't exist, will create a new one.

Returns

boolean

Parameters

(array) $values an array of values to first search for and if they don't exist, will create a new record

Example


	$example = $this->examples_model->find_or_create(array('slug' => 'the-force'));
	

$this->example_model->clean([$values=array()], ['$run_hook'=FALSE])

Clean the data before saving.

Returns

array

Parameters

(mixed) $values an array of values to be saved (optional)
(boolean) $run_hook run on_before_clean hook or not (optional)

Example


	$cleaned_data = $this->examples_model->clean($_POST); // Be sure to always clean your $_POST variables before using them
	

$this->example_model->encode_and_clean('$val', '$k', ['$key'=NULL])

$this->example_model->cleaned_data()

Get the cleaned data.

Returns

array

Example


	$cleaned_data = $this->examples_model->cleaned_data();
	

$this->example_model->record_count([$where=array()])

Returns number of query results.

Returns

int

Parameters

(mixed) $where where condition (optional)

Example


	$where['published'] = 'yes';
	echo $this->examples_model->record_count($where); // displays the number of records
	

$this->example_model->total_record_count()

Returns number of records in the table.

Returns

int

Example


	$total_count = $this->examples_model->total_record_count();
	

$this->example_model->save(['$record'=NULL], ['$validate'=TRUE], ['$ignore_on_insert'=TRUE], ['$clear_related'=NULL])

Saves record object, or array of data to the database.

Returns

mixed

Parameters

(mixed) $record an array or object to save to the database
(boolean) $validate validate the data before saving
(boolean) $ignore_on_insert ignore duplicate records on insert

Example


	$this->examples_model->save($_POST, TRUE, TRUE); // Be sure to always clean your $_POST variables before using them
	

$this->example_model->saved()

Returns the last saved record.

Returns

object

Example


	 $this->examples_model->save($values);
	 $record = $this->saved();
	

Save related data to a many to many table. To be used in on_after_save hook.

Returns

boolean

Parameters

(mixed) $model the model to save to
(array) $key_field key is the column name, and value is the value to save
(array) $data key is the column name, and the array of data to iterate over and save

Example


	$this->examples_model->save_related('examples_to_categories', array('example_id' => $obj->id), array('categories_id' => $_POST['categories']));
	

Handles grabbing of the related data's keys.

Returns

array

Parameters

(array) $related_field $related_field
(array) $values $values
(string) $related_model $related_model
(string) $mode $mode, has_many or belongs_to (optional)
(string) $rel_config $rel_config which provides information on the relationship table but will use built in fuel_relationships by default (optional)

Example


	

$this->example_model->insert('$values')

Performs a simple insert to the database record.

Returns

boolean

Parameters

(mixed) $values an array or object to save to the database

Example


	$values['name'] = 'Darth Vader'; 
	$values['email'] = 'dvader@deathstar.com'; 
	$this->examples_model->insert($values);
	

$this->example_model->update('$values', [$where=array()])

Performs a simple update to the database record based on the $where condition passed.

Returns

boolean

Parameters

(mixed) $values an array or object to save to the database
(mixed) $where where condition

Example


	$where['id'] = 1;
	$this->examples_model->update($_POST, $where); // Be sure to always clean your $_POST variables before using them
	

$this->example_model->delete('$where')

Deletes database record(s) based on the $where condition passed. Does execute before and after delete hooks.

Returns

void

Parameters

(mixed) $where where condition

Example


	$where['id'] = 1; 
	$this->examples_model->delete($where);
	

Delete related data. To be used in on_before/on_after delete hooks.

Returns

boolean

Parameters

(string) $model 
(string) $key_field 
(mixed) $where 

Example


	$obj = $this->examples_model->create();
	$obj->name = 'Darth Vader';
	$obj->save();
	$this->examples_model->delete_related('examples_to_categories', 'example_id', $obj);
	

$this->example_model->truncate()

Truncates the data in the table.

Returns

void

Example


	$this->examples_model->truncate();
	

$this->example_model->is_new('$val', '$key')

Creates a where condition and queries the model's table to see if the column ($key) already contains the $val value. Usually used for validation to check if a unique key already exists.

Returns

array

Parameters

(string) $val value to be checked
(string) $key column name to check

Example


	$this->examples_model->is_new('location', 'id');
	

$this->example_model->is_editable('$val', '$key', '$id')

Creates a where condition and queries the model's table to see if the column ($key) already contains the $val value but compares it to the tables key column with the $id value. Usually used for validation. The example below uses this method to validate on the model before saving. The is_new and is_editable methods are usually used during the models validation process as shown in the example.

Returns

array

Parameters

(string) $val value to be checked
(string) $key column name to check
(mixed) $id the key field value to check against. May also be the complete array of values if the key value is also an array (for compound unique keys)

Example


	public function on_before_validate($values) 
	{ 
	    if (!empty($values['id'])) 
	    { 
	        $this->add_validation('location', array(&$this, 'is_editable'), 'The location value already exists.' , array('location', $values['id'])); 
	    } 
	    else 
	    { 
	        $this->add_validation('location', array(&$this, 'is_new'), 'The location value already exists.', 'location'); 
	    } 
	    return $values; 
	} 
	

$this->example_model->validate('$record', ['$run_hook'=FALSE])

Validate the data before saving. Can pass either a custom record object or an associative array of table column values. Will run all validation rules, including required and autovalidation (if auto_validation is set on the model) and return TRUE if it passes validation and FALSE if it fails. The run_hook parameter will run the model's on_before_validate hook if set to TRUE (default is FALSE);.

Returns

array

Parameters

(mixed) $record object or array of values
(boolean) $run_hook run on_before_validate hook or not (optional)

Example


	// Using an array of values
	$values['name'] = 'Mr. Jones';
	$values['email'] = 'jones@example.com';
	$values['active'] = 'yes';
	$this->examples_model->validate($values);
	
	// Using a custom record
	$example = $this->examples_model->create();
	$example->name = 'Mr. Jones';
	$example->email = 'jones@example.com';
	$example->active = 'yes';
	$this->examples_model->validate($example);
	
	// you can also just call the validate method on the custom record object
	$example->validate();
	

$this->example_model->field_type('$field')

Returns a field type of string, number, date, datetime, time, blob, enum

Returns

array

Parameters

(string) $field field

Example


	$type = $this->examples_model->field_type('email');
	echo $type; // string
	

$this->example_model->is_valid()

Returns a boolean value if all validation rules that have been run have passed.

Returns

boolean

Example


	$values['name'] = 'Mr. Jones';
	$values['email'] = 'jones@example.com';
	$values['active'] = 'yes';
	$this->examples_model->validate($values);
	if ($this->examples_model->is_valid($values))
	{
	    echo 'We are valid!';
	}
	

$this->example_model->add_validation('$field', '$rule', '$msg')

Add a validation rule.

Returns

void

Parameters

(string) $field field name
(mixed) $rule function name OR array($object_instance, $method)
(string) $msg error message to display

Example


	$this->examples_model->add_validation('email', 'valid_email', 'The email is invalid.', 'jones@example.com'); 
	

$this->example_model->add_error('$msg', ['$key'=NULL])

Add an error to the validation to prevent saving.

Returns

void

Parameters

(string) $msg error message
(string) $key key value of error message (optional)

Example


	$this->examples_model->add_error('There was an error in processing the data.', 'my_key'); 
	

$this->example_model->has_error()

Returns a TRUE if the model has any errors associated with it and FALSE otherwise.

Returns

boolean

Example


	if ($this->examples_model->has_error())
	{
		return FALSE;
	}
	

$this->example_model->remove_validation('$field', ['$rule'=NULL])

Remove a validation rule from the validator object.

Returns

array

Parameters

(string) $field field name
(string) $rule function name (optional)

Example


	$this->examples_model->remove_validation('my_field', 'my_func');
	

$this->example_model->add_required('$field')

Add a required field.

Returns

void

Parameters

(string) $field field name

Example


	$this->examples_model->add_required('my_field'); 
	

$this->example_model->get_validation()

Gets the validation object.

Returns

object

Example


	$validation = $this->examples_model->get_validation(); 
	if ($validation->is_valid())
	{
	    echo 'YEAH!'; 
	}
	

$this->example_model->register_to_global_errors('$register')

Sets the validation to register to the global scope.

Returns

object

Example


	$this->examples_model->register_to_global_errors(TRUE); 

	...// code goes here

	$errors = get_errors(); // validator_helper function to get global errors
	foreach($errors as $error) 
	{ 
	    echo $error; 
	    // There was an error in processing your data 
	} 
	

$this->example_model->get_errors()

Returns the errors found in the validator object.

Returns

array

Example


	$errors = $this->examples_model->get_errors(); 

	foreach($errors as $error) 
	{ 
	    echo $error; 
	    // There was an error in processing your data 
	} 
	

$this->example_model->remove_all_validation(['$remove_required'=FALSE])

Removes all the validation.

Returns

void

Parameters

(boolean) $remove_required determines whether to remove required validation as well as other validation rules

Example


	$this->examples_model->remove_all_validation(TRUE);
	

$this->example_model->field_info('$field')

Returns an associative array of a specific field's meta information which includes the following:.

  • name - the name of the field
  • type - the type of field (e.g. int, varchar, datetime... etc)
  • default - the default value of the field
  • options/max_length - if it is an enum field, then the enum options will be displayed. Otherwise, it will show the max length of the field which may not be relevant for some field types.
  • primary_key - the primary key column
  • comment - the comment
  • collation - the collation method
  • extra - extra field meta information like auto_increment
  • null - a boolean value if the field is NULL or not

Returns

array

Example


	$field_meta = $this->examples_model->field_info('email'); 

	echo $field_meta['name']; // email 
	echo $field_meta['type']; // varchar 
	

$this->example_model->table_info()

Returns an associative array of table field meta information with each key representing a table field.

Returns

array

Example


	$table_meta = $this->examples_model->table_info(); 

	echo $table_meta['id']['type']; // int 
	echo $table_meta['id']['primary_key']; // 1 (TRUE) 
	echo $table_meta['email']['type']; // varchar 
	echo $table_meta['first_name']['type']; // varchar 
	echo $table_meta['description']['type']; // text 
	echo $table_meta['active']['type']; // enum 
	print_r($table_meta['active']['options']); // array('yes', 'no') 
	

$this->example_model->comment()

Returns the table's comment.

Returns

boolean

Example


	 $model->comment();
	

$this->example_model->form_fields([$values=array()], [$related=array()])

Returns an array of information that can be used for building a form (e.g. Form_builder). Somewhat similar to the table_info method with difference being that the returned array has information for creating a form. The related parameter is used to conveniently map other model information with this form to create a many to many multi-select form element. This method is usually used with the Form_builder class.

Returns

array

Parameters

(array) $values array of values to pass to the form fields
(array) $related an array of info about related models that create multiselects

Example


	$form_info = $this->examples_model->form_fields(); 

	echo $form_info['id']['type']; // hidden 
	echo $form_info['email']['type']; // text 
	echo $form_info['email']['required']; // 1 (TRUE) 
	echo $form_info['first_name']['type']; // text 
	echo $form_info['description']['type']; // textfield 
	echo $form_info['active']['type']; // select or enum 
	echo $form_info['date_added']['type']; // datetime (a special field type in the form_builder class) 
	

$this->example_model->csv(['$data'=NULL], ['$display_headers'=TRUE], ['$delim'=','], ['$newline'=' '], ['$enclosure'='"'])

Outputs the data passed to in into a comma separated value (CSV).

Returns

string

Parameters

(boolean) $data Display headers?
(string) $display_headers The delimiter - comma by default
(string) $delim The newline character - \n by default
(string) $newline The enclosure - double quote by default

Example


	$items = $this->find_all();
	$data = $this->csv($items);
	

$this->example_model->record_class_name()

Returns the custom record class name if it exists. If a name does not exist, it will try to intelligently find a class with a singular version of the parent table model's name (e.g. examples_model = example_model).

Returns

string

$this->example_model->set_return_method('$return_method')

Set's the default return method for methods like get(), find_one and find_all. Values can be object, array, query, auto

Returns

void

Parameters

(string) $return_method return type (object, array, query, auto)

Example


	$this->examples_model->set_return_method('object'); 
	$examples = $this->examples_model->find_all(); // an array of custom objects (if a custom object is defined. If not, a standard object will be used) 

	$this->examples_model->set_return_method('array'); 
	$examples = $this->examples_model->find_all(); // an array of associative arrays is returned and will ignore any custom object
	

$this->example_model->get_return_method()

Returns the return method used for querying (object, array, query, auto).

Returns

mixed

Example


	$return_method = $this->examples_model->get_return_method(); // object 
	

$this->example_model->debug_data()

Prints out to the screen the last query results ran by the model.

Returns

mixed

Example


	$this->examples_model->debug_data(); // prints out an array of information to the screen
	

$this->example_model->debug_query(['$hidden'=FALSE], ['$exit'=FALSE], ['$return'=FALSE])

Prints out to the screen the last query SQL ran by the model.

Returns

mixed

Parameters

(boolean) $hidden will hide the echoed output in a comment
(boolean) $exit will exit the script
(boolean) $return returns the output

Example


	$this->examples_model->debug_query(); // prints out the last query run by the model
	

$this->example_model->normalize_save_values(['$record'=NULL])

Normalize the data to be saved so that it becomes an array and can be referenced by the 'normalized_save_data' property.

Returns

array

Parameters

(mixed) $record array of values to be saved (optional)

Example


	$record = $this->examples_model->create(); 
	$record->name = 'John Smith'; 

	$values = $this->examples_model->normalize_save_values($record); 
	echo $values['name'] = 'John Smith';
	

$this->example_model->normalize_data('$data')

Normalizes the data passed to it so that it becomes an array (used by the normalize_save_values).

Returns

array

Parameters

(mixed) $data array of values

Example


	$record = $this->examples_model->create(); 
	$record->name = 'John Smith'; 

	$values = $this->examples_model->normalize_data($record); 
	echo $values['name'] = 'John Smith';
	

$this->example_model->process_linked($values)

Processes $linked_fields and will convert any empty values with their corresponding linked field function.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->process_relationships($id)

Process relationships.

Returns

array

Parameters

(array) $id values to be saved

$this->example_model->process_relationships_delete($id)

Process relationships before delete.

Returns

void

Parameters

(array) $id where condition for deleting

$this->example_model->on_before_clean($values)

Placeholder hook - right before cleaning of data.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_before_validate($values)

Placeholder hook - right before validation of data.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_before_insert($values)

Placeholder hook - right before insertion of data.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_after_insert($values)

Placeholder hook - right after insertion of data.

Returns

void

Parameters

(array) $values values to be saved

$this->example_model->on_before_update($values)

Placeholder hook - right before update of data.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_after_update($values)

Placeholder hook - right after update of data.

Returns

void

Parameters

(array) $values values to be saved

$this->example_model->on_before_save($values)

Hook - right before saving of data.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_after_save($values)

Hook - right after saving of data.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_before_delete($where)

Placeholder hook - right before delete.

Returns

void

Parameters

(array) $where where condition for deleting

$this->example_model->on_after_delete($where)

Placeholder hook - right after delete.

Returns

void

Parameters

(array) $where where condition for deleting

$this->example_model->on_before_post([$values=array()])

Placeholder hook - for right after before processing a post. To be used outside of. the saving process and must be called manually from your own code.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_after_post($values)

Placeholder hook - for right after posting. To be used outside of. the saving process and must be called manually from your own code.

Returns

array

Parameters

(array) $values values to be saved

$this->example_model->on_duplicate($values)

Placeholder hook - to inject extra information to a record object after. duplicating a new record via $rec->duplicate();.

Returns

array

Parameters

(array) $values values to initialize object

$this->example_model->on_create($values)

Placeholder hook - to inject extra information to a record object after. creating a new record via $this->my_model->create();.

Returns

array

Parameters

(array) $values values to initialize object

$this->example_model->load_model('$model')

Load another model.

Returns

string

Parameters

(mixed) $model the name of the model. If an array, the key is the module and the name is the model

Example


	// load model from application directory
	$this->load_model('my_model');
	
	// load model from another module
	$this->load_model(array('my_module' => 'my_model'));
	

Load a related model.

Returns

boolean

Parameters

(string) $related_model the name of the model

$this->example_model->relationship_field_names('$relationship_type', ['$field'=NULL])

Returns an array of the relationship field names to be used.

Returns

array

Parameters

(string) $relationship_type relationship type

$this->example_model->format_model_name('$model')

Format a model's name.

Returns

boolean

Parameters

(string) $model the name of the model

$this->example_model->is_using_relationship_table('$rel_config')

Returns whether the relationship is using a pivot table.

$this->example_model->serialize_field_values('$data')

Serializes field values specified in the $serialized_fields property.

Returns

array

Parameters

(string) $data the field name to unserialize

$this->example_model->serialize_value('$val', ['$method'=NULL])

Serialize a value to be saved.

Returns

array

Parameters

(string) $val the array value to unserialize
(string) $method the unserialization method. If none is specified it will default to the default setting of the model which is 'json'

$this->example_model->unserialize_field_values('$data')

Unserialize a field's value.

Returns

array

Parameters

(mixed) $data the data to unserialize. Can be an array of arrays too

$this->example_model->unserialize_value('$val', ['$method'=NULL])

Unserialize a saved value.

Returns

array

Parameters

(string) $val the array value to unserialize
(string) $method the unserialization method. If none is specified it will default to the default setting of the model which is 'json'

$this->example_model->load_custom_field_classes(['$folder'='libraries/custom_fields'])

Loads custom field classes so they can be instantiated when retrieved from the database.

Returns

void

Parameters

(string) $folder the folder to look into from within either the module or application directory

$this->example_model->add_formatter('$type', '$func', ['$alias'=NULL])

Adds a formatter helper function.

Returns

void

Parameters

(string) $type the field type to apply the function to
(mixed) $func the function
(string) $alias the alias to that function name (e.g. formatted = auto_typography)

$this->example_model->remove_formatter('$type', '$key')

Removes a formatter helper function.

Returns

void

Parameters

(string) $type the field type to apply the function to
(mixed) $key the formatter key

$this->example_model->replace_placeholders('$str', '$values')

Replaces placeholder strings with values in an array.

Returns

boolean

Parameters

(mixed) $str 

$this->example_model->__toString()

What to print when echoing out this object.

Returns

string

Example


	

$this->example_model->__call('$name', $args)

Magically create methods based on the following syntax. find_all_by_{column1}_and_{column2}, find_one_by_{column1}_or_{column2}.

Returns

array

Parameters

(string) $name name of the method called
(array) $args arguments sent to the method call


Data Set Class

This class is instantiated by the Table Class (MY_Model) when a result set is needed. The Data_set class has a few methods to retrieve information about the data set.

Properties Reference

Property Default Value Description
protected
results N/A
force_array N/A

Function Reference [+]

$data_set->result()

Returns the results of the query.

Returns

array

Example


	$single_result_set = $this->examples_model->get(FALSE); 
	$example = $single_result_set->result(); 
	echo $example->name; 
	
	// If multiple result sets are needed, then the result method will return multiple result objects/arrays like so:
	$multiple_result_set = $this->examples_model->get(TRUE); 
	foreach($multiple_result_set as $example) 
	{ 
	    echo $example->name; 
	} 
	

$data_set->num_records()

Determines if there is a key field value in the array of values.

Returns

boolean

Example


	$multiple_result_set = $this->examples_model->get(TRUE); 
	echo $multiple_result_set->num_records();
	

$data_set->debug()

Debug data sets.

Returns

void

Example


	$multiple_result_set = $this->examples_model->get(TRUE); 
	$multiple_result_set->debug();
	

$data_set->__toString()

Debug data sets.

Returns

void

Example


	


Data Record Class

The Data_record class is used to create custom record objects for a Table class (MY_Model). Data_record objects provides a greater level of flexibility with your models by allowing you to create not only methods on your model to retrieve records from your datasource, but also the ability to create derived attributes and lazy load other objects with each record returned. This class is optional. If it it doesn't exist, then the Table Class parent model will use either a standard generic class or an array depending on the return method specified.

Properties Reference

Property Default Value Description
protected
_CI N/A Global CI object
_db N/A Database object
_fields N/A Fields of the record
_objs N/A Nested objects
_parent_model N/A The name of the parent model
_inited N/A Returns whether the object has been initiated or not

Function Reference [+]

$record->initialize('$parent', [$fields=array()])

Initializes the class with the parent model and field names.

Returns

array

Parameters

(object) $parent parent model object
(array) $fields field names

$record->is_initialized()

This method returns either TRUE or FALSE depending on if the record class has been properly initialized.

Returns

boolean

Example


	$record = $this->examples_model->create(); 
	$record->is_initialized(); // Returns TRUE
	

$record->set_fields($fields)

Sets the fields of the oject ignoring those fields prefixed with an underscore.

Returns

void

Parameters

(array) $fields field names

Example


	$fields = array('id', 'name', 'email');
	$record = $this->examples_model->set_fields($fields); 
	

$record->id()

Returns the id field name.

Returns

void

Example


	$record->id(); // Returns id
	

$record->fill([$values=array()])

Sets the values of the fields.

Returns

void

Parameters

(array) $values field values

Example


	$record = $this->examples_model->create(); 
	$record->fill($_POST);  // Be sure to always clean your $_POST variables before using them
	

$record->values(['$include_derived'=FALSE])

Returns an array of the record's values.

Returns

array

Parameters

(boolean) $include_derived Determines whether to include derived attributes (those starting with get_)

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$values = $record->values()
	echo $values['email']; // vader@deathstar.com 
	

$record->duplicate()

Duplicates the record with all it's current values.

Returns

object

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$duplicate_record = $record->duplicate()
	echo $duplicate_record->email; // vader@deathstar.com 
	

$record->save(['$validate'=TRUE], ['$ignore_on_insert'=TRUE], ['$clear_related'=NULL])

Saves all the properties of the object.

Returns

boolean

Parameters

(boolean) $validate validate before saving?
(boolean) $ignore_on_insert ignore on insert

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->email = 'hsolo@milleniumfalcon.com';
	$record->save();
	

$record->validate()

Validates the values of the object to makes sure they are valid to be saved.

Returns

boolean

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->email = 'hsolomilleniumfalcon.com'; // note the invalid email address
	if ($record->validate()) 
	{ 
	    echo 'VALID'; 
	} 
	else 
	{ 
	    echo 'Please fill out a valid email address'; 
	} 
	

$record->is_valid()

Returns TRUE or FALSE depending on if validation has been run and is valid.

The validate method must be called before calling is_valid.

Returns

boolean

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->email = 'hsolomilleniumfalcon.com'; // note the invalid email address
	$record->validate();

	... other code ...

	if ($record->is_valid()) 
	{ 
	    echo 'VALID'; 
	} 
	else 
	{ 
	    echo 'Please fill out a valid email address'; 
	} 
	

$record->errors()

Returns an array of error messages if there were any found after validating. This is commonly called after saving because validation will occur automatically on save.

Returns

array

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->email = 'hsolomilleniumfalcon.com'; // note the invalid email address
	if (!$record->save())
	{ 
	    foreach($record->errors() as $error)
	    {
	        echo $error;	
	    }
	} 
	

$record->add_error('$msg', ['$key'=NULL])

Sets an error on the parent model from within the context of the record model.

Returns

array

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->add_error('Those aren\'t the droids we are looking for');
    foreach($record->errors() as $error)
    {
        echo $error;	
    }
	

$record->delete()

Deletes the record. Similar to the save method, it will call the parent model's delete method passing itself as the where condition to delete.

Returns

boolean

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->delete(); // note the invalid email address
	

$record->refresh()

Refreshes the object from the data source.

Returns

void

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->email = 'hsolo@milleniumfalcon.com';
	$record->refresh();
	echo $record->email; // dvader@deathstar.com
	

$record->lazy_load('$where', '$model', ['$multiple'=FALSE], [$params=array()], ['$cache_key'=''])

Will load another model's record object and is often used in custom derived attributes.

Returns

array

Parameters

(mixed) $where where conditions
(string) $model model name
(boolean) $multiple return 1 or many
(array) $params an array of extra parameters to pass to the query method. Also, can pass assoc_key and return_ (e.g. join, order_by, limit, etc)
(string) $cache_key the key to the _obj property to store the lazy loaded object

Example


	public function get_spaceship()
	{
	    $ship = $this->lazy_load(array('email' => 'hsolo@milleniumfalcon.com'), 'spacehips_model', FALSE);
	    return $ship;
	}
	

$record->parent_model()

Returns the parent model object.

Returns

object

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 

	// Same as above
	$record->parent_model()->find_one(array('email' => 'dvader@deathstar.com');
	

$record->prop_exists('$key')

Tests whether a property exists on the record.

Returns

boolean

Parameters

(key) $key field names

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	if ($record->prop_exists('email')))
	{
	    echo $record->email;
	}
	

$record->is_empty()

Is empty check.

Returns

boolean

Example


	

$record->debug_query()

Prints to the screen the last query run by the parent model. An alias to the parent model's debug_query method.

Returns

array

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->debug_query()))
	

$record->debug_data()

Prints to the screen the property values of the of the object.

Returns

void

Example


	$record = $this->examples_model->find_one(array('email' => 'dvader@deathstar.com')); 
	$record->debug_data()))
	

$record->on_after_insert($values)

Placeholder - executed after insertion of data.

Returns

void

Parameters

(array) $values field values

$record->on_after_update($values)

Placeholder - executed after update of data.

Returns

void

Parameters

(array) $values field values

$record->on_init()

Placeholder - executed after initialization.

Returns

vpod

$record->before_set('$output', '$var')

Placeholder - to execute before a magic method get.

Returns

mixed

Parameters

(string) $output output from get comand
(string) $var field name

$record->after_get('$output', '$var')

Placeholder - to execute after a magic method get.

Returns

mixed

Parameters

(string) $output output from get comand
(string) $var field name

$record->key_field()

Returns the key field of the record.

Returns

string

$record->key_value()

Returns the key value of the record.

Returns

int  (usually and integer)

$record->to_json(['$include_derived'=TRUE])

Returns a JSON encoded string of the record values.

Returns

string

Parameters

(boolean) $include_derived Determins whether to include derived attributes (those starting with get_)

$record->format('$field', [$funcs=array()], [$args=array()])

Will format a particular field given the functions passed to it.

Returns

string

Parameters

(string) $field the field name
(mixed) $funcs an array or string value representing one ore more functions to use for formatting
(array) $args additional arguments to pass to the formatting function. Not applicable when passing multiple formatting functions (optional)

$record->__toString()

String value of this object is it's values in an array format.

Returns

string

$record->__call('$method', $args)

Magic method for capturing method calls on the record object that don't exist. Allows for "get_{field}" to map to just "{field}" as well as "is_{field}"" and "has_{field}".

Returns

array

Parameters

(object) $method method name
(array) $args arguments

$record->__set('$var', '$val')

Magic method to set first property, method, then field values.

Returns

void

Parameters

(string) $var field name
(mixed) $val 

$record->__get('$var')

Magic method to return first property, method, then field values.

Returns

mixed

Parameters

(string) $var field name

$record->__isset('$key')

Magic method to check if a variable is set.

Returns

boolean

Parameters

(string) $key field to check if it is set

$record->__unset('$key')

Magic method for unset.

Returns

void

Parameters

(string) $key field to delete


Data Record Field Class

The Data_record_field class is used to create custom field objects for a Date_record object values. Data_record_field objects provides a greater level of flexibility with your models by allowing associate an object as the value of a field. This class is optional.

Properties Reference

Property Default Value Description
public
field none Actual field value
value none The value of the field
protected
_CI N/A Global CI object
_parent_model N/A The name of the parent model
_inited N/A Returns whether the object has been initiated or not

Function Reference [+]

$record->initialize('$field', '$value', '$parent', [$params=array()])

Initializes the class with the field name, it's value, parent model and any additional parameters needed for the class.

Returns

array

Parameters

(string) $field the name of the field
(mixed) $value the value of the field
(object) $parent parent object
(array) $params initialization parameters

$record->on_init()

Placeholder - executed after initialization.

Returns

vpod

$record->is_initialized()

This method returns either TRUE or FALSE depending on if the field class has been properly initialized.

Returns

boolean

$record->parent_model()

Returns the parent model object.

Returns

object

$record->table_model()

Returns the table model object.

Returns

object

$record->is_empty()

Is empty check.

Returns

boolean

$record->after_get('$output', '$var')

Placeholder - to execute after a magic method get.

Returns

mixed

Parameters

(string) $output output from get command
(string) $var field name

$record->__get('$var')

Magic method to return first property then method.

Returns

mixed

Parameters

(string) $var field name

$record->__toString()

What to print when echoing out this object.

Returns

string

$record->__isset('$key')

Magic method to check if a variable is set.

Returns

boolean

Parameters

(string) $key field to check if it is set

$record->__unset('$key')

Magic method for unset.

Returns

void

Parameters

(string) $key field to delete