-
-
Save aaoliveira/7774477 to your computer and use it in GitHub Desktop.
Lista cidade estado cakephp
This file contains 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
<?php | |
//Primeiramente o controller usuarios, que é onde vou utilizar os selects de cidades e estados | |
class UsuariosController extends AppController { | |
public function cadastro() { | |
$this->set('estados', $this->Estado->find('list')); | |
} | |
} | |
//No controller CidadesController: | |
public function listar_cidades_json() { | |
$this->layout = false; | |
if ($this->RequestHandler->isAjax()) { | |
$this->set('cidades', $this->Cidade->find('list', array('conditions' => | |
array('Cidade.estado_id' => $this->params['url']['estadoId']), | |
'recursive' => -1) | |
)); | |
} | |
} | |
//Na view Cidades listar_cidades_json.ctp | |
if(isset($cidades)) { | |
echo $this->Js->object($cidades); | |
} | |
//Agora na view de Usuarios cadastro.ctp: | |
echo $this->Html->script('views/cidades/listar_cidades.js', array('inline' => true)); | |
echo $this->Form->create('Usuario', array('action' => 'cadastro','method' => 'post','enctype' => 'multipart/form-data')); | |
echo $this->Form->input('estado_id', array('empty' => 'Selecione um estado', 'options' => $estados, 'id' => 'estado-nome', 'label' => '* Estado')); | |
echo $this->Form->input('cidade_id', array('type' => 'select', 'empty' => 'Selecione uma cidade', 'id' => 'cidade-nome', 'label' => '* Cidade')); | |
?> | |
//Agora no arquivo js/views/cidades/listar_cidades.js | |
$(document).ready(function() { | |
if($('#estado-nome').val().length != 0) { | |
$.getJSON("../cidades/listar_cidades_json",{ | |
estadoId: $('#estado-nome').val() | |
}, function(cidades) { | |
if(cidades != null) | |
popularListaDeCidades(cidades, $('#id-cidade').val()); | |
}); | |
} | |
$('#estado-nome').live('change', function() { | |
if($(this).val().length != 0) { | |
$.getJSON("../cidades/listar_cidades_json",{ | |
estadoId: $(this).val() | |
}, function(cidades) { | |
if(cidades != null) | |
popularListaDeCidades(cidades); | |
}); | |
} | |
}); | |
}); | |
function popularListaDeCidades(cidades, idCidade) { | |
var options = ''; | |
$.each(cidades, function(index, cidade){ | |
if(idCidade == index) | |
options += '<option selected="selected" value="' + index + '">' + cidade + '</option>'; | |
else | |
options += '<option value="' + index + '">' + cidade + '</option>'; | |
}); | |
$('#cidade-nome').html(options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment