Created
June 4, 2013 14:07
-
-
Save jonatanfroes/5706203 to your computer and use it in GitHub Desktop.
Helper para gerar dropdown automaticamente a partir de uma consulta ao banco de dados (active record). #codeigniter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* returns an array w/ key => value to populate a select | |
* | |
* @access public | |
* | |
* @param object active record result | |
* @param string field name that will be displayed | |
* @param string field name that will be used as option value | |
* @param array Add a value before result from db | |
* @param mixed remove a value from list | |
* | |
* @return string | |
*/ | |
function auto_dropdown($obj, $val = 'name', $key = 'id', $empty = array(), $ignore = FALSE) | |
{ | |
$return = array(); | |
//Add a value before result from db | |
if($empty) | |
{ | |
$k = key($empty); | |
$v = $empty[$k]; | |
$return[$k] = $v; | |
} | |
//test if we have a valid result (you must pass ->result() from Active Record | |
if ( ! isset($obj->row_data) || $obj->row_data == NULL) | |
{ | |
return $return; | |
} | |
foreach($obj as $res) | |
{ | |
//in case we have to ignore something | |
if ($ignore && $res->{$key} == $ignore) | |
{ | |
continue; | |
} | |
else | |
{ | |
//add value to return array | |
$return[$res->{$key}] = $res->{$val}; | |
} | |
} | |
return $return; | |
} | |
/* EXEMPLO DE USO */ | |
// ------------------------------------------------------------------------ | |
/* CONTROLLER */ | |
//seleciona os dados no banco | |
$paises = $this->paises_model->get()->result(); | |
$estados = $this->estados_model->get()->result(); | |
$cidades = $this->cidades_model->get()->result(); | |
//retonra um array p/ o form_dropdown: | |
$dados['paises'] = auto_dropdown($paises, 'pais', 'id', array(0 => 'Selecione um País')); | |
$dados['estados'] = auto_dropdown($cidades, 'estado', 'id', array(0 => 'Selecione um Estado')); | |
$dados['cidade'] = auto_dropdown($estados, 'cidade', 'ide', array(0 => 'Selecione uma Cidade')); | |
// ------------------------------------------------------------------------ | |
/* VIEW */ | |
echo form_label('País', 'paises_id'); | |
echo form_dropdown('paises_id', $paises. 'id="paises_id"'); | |
echo form_label('Estado', 'estados_id'); | |
echo form_dropdown('estados_id', $estados. 'id="estados_id"'); | |
echo form_label('Cidade', 'cidades_id'); | |
echo form_dropdown('cidades_id', $cidades. 'id="cidades_id"'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment