Problema na hora de editar, com combobox aninhado + json + Vraptor [RESOLVIDO]

30 respostas
well

Pessoal tenho um combobox aninhado, funciona perfeitamente na hora de inserir dados no BD, porem uma hora eu tenho que alterar algo(editar), ai o problema,

quando chamo o editar, ele traz as informações do banco certo, e a UF do combo correta, porem o municipio nao consigo trazer o correto, tipo, meu cadastro esta assim:

UF: RJ cidade: PETROPOLIS

ele traz

UF: RJ cidade: ARAIAL - no caso a primeira.

NA UF esta assim

<label>Estado:</label>
                 <select name="uf.nome" id="estadoDropdown" > 
                  <option value="${bci.municipioEntrega.uf.id}">${bci.municipioEntrega.uf.nome}</option> // chamo aki para preencher corretamente .. OK
                    <c:forEach var="u" items="${ufs}">    
                        <option value="${u.id}">${u.nome}</option>    
                    </c:forEach>    
                </select>

e municipio assim:

<label for="municipio">municipio:</label> 
				<select name="bci.municipioEntrega.id" id="municipio">
			</select>

Tem como eu inserir o correto sendo o primeiro???

vlw

30 Respostas

Lucas_Cavalcanti

tem sim… o jeito mais fácil é fazer isso via javascript…

depois que ele carregar o combo de municípios, faça (supondo q vc usa jQuery):

$('#municipio').val('${bci.municipioEntrega.id}');

esse código dentro de alguma tag script, dentro da jsp.

lembrando que isso tem q rodar depois q o combo foi carregado

well

Não funcionou, coloquei la no fim da jsp. o que será que ta de errado? :frowning:

Lucas_Cavalcanti

tem certeza que isso tá acontecendo depois que o combo de municipios está populado?

well

Ta populado sim, fiz uma alteracao aqui: coloquei um option assim:

<label for="municipio">municipio:</label> 
				<select id="municipio" name="bci.municipioEntrega.id">	
				<option selected="selected" value="${bci.municipioEntrega.id}">${bci.municipioEntrega.nome}</option>// nao precisa disso para popular mas fiz um teste.
			</select>

apos abri o fonte no navegador.

label for="municipio">municipio:</label> 

				<select id="municipio" name="bci.municipioEntrega.id">

				

				<option selected="selected" value="6670">BANQUETE</option>// no fonte aparece correto mas no navegador aparece abarracamento q é o primeiro da lista

		

			</select>

Que coisa nao?

well

Depois que coloquei o OPTION chega dar uma piscada no combo com o valor correto porem muda para o promeiro da lista. vou tentar umas modificacoes aki…

well

Não consegui ainda :frowning: , tem alguma outra sugestão Lucas?

Lucas_Cavalcanti

qual é o código que vc está usando pra popular o combo de municipios?

well

Vou postar todos:

dao

@SuppressWarnings("unchecked")
	public List<Municipio> listaUfMunicipio(Long uf) {
		Session session = (Session) em.getDelegate();
		return session.createCriteria(Municipio.class)
				.add(Restrictions.like("uf.id", uf)).list();
	}

controller

@Get
	@Path("/municipios/buscaMunicipios.json")
	public void loadMunicipios(Long uf) {
		List<Municipio> municipios = dao.listaUfMunicipio(uf);
		result.use(Results.json()).withoutRoot().from(municipios).serialize();
	}

JS

(function($) {
  $.fn.emptySelect = function() {
    return this.each(function(){
      if (this.tagName=='OPTION') this.options.length = 0;
    });
  }

  $.fn.loadSelect = function(data) {
    return this.emptySelect().each(function(){
      if (this.tagName=='OPTION') {
        var selectElement = this;
   
        $.each(data,function(index,optionData){
       
                var option = new Option(optionData.nome,
                    optionData.id);
               
          if ($.browser.msie) {
            selectElement.add(option);
          }
          else {
            selectElement.add(option,null);
          }
        });
      }
    });
  }
})(jQuery);

JS

function adjustMunicipioDropdown() {
        var estadoValue = $('#estadoDropdown').val();
        var dropdownSet = $('#municipio');
        if (estadoValue.length == 0)
        {
                dropdownSet.attr("disabled", true);
                dropdownSet.emptySelect();
        }
                else
        {
                dropdownSet.attr("disabled", false);

                $.getJSON('/webgeo/municipios/buscaMunicipios.json', {
                        uf : estadoValue
                }, function(q) {
                        dropdownSet.loadSelect(q);
                });
        }
}

JSP

label for="municipio">municipio:</label> 
				<select id="municipio" name="bci.municipioEntrega.id"></select>

Ta tudo ai…

Lucas_Cavalcanti

vc deve ter em algum lugar a chamada:

adjustMunicipioDropdown();

se isso estiver na jsp, faça:

adjustMunicipioDropdown();
$('#municipio').val('${bci.municipioEntrega.id}');

se não funcionar, tenta trocar de .id pra .nome

well
Lucas fiz o que falou:
<script type="text/javascript">
$(function(){
 
   $('#loading').hide();
   $('#estadoDropdown').change(function(){
       adjustMunicipioDropdown();
       $('#municipio').val('${bci.municipioEntrega.id}');// olhei pelo firebug e esta pegando o id corretamente
     }).change();
   $('#loading').ajaxStart(function() {
       $(this).show();
   });
   $('#loading').ajaxStop(function(){
       $(this).hide();
   });
 });

</script>
e não funcionou, porem fiz um teste aqui: se eu tirar o
name="bci.municipioEntrega.id"[/quote] do select não faz diferença na listagem,  não salva nada na hora de alterar.

Provavelmente por isso que não esta funcionando.
mas não consigo ver uma solução.

Lucas_Cavalcanti

move o código do val pra dentro do ajaxStop (o getJSON é assincrono, por isso não deve estar funcionando)…

pra evitar que ele faça sempre, coloque uma var booleana pra que ele só faça uma vez

well

Opa, deu resultado fiz parte do que falou, eu acho:

<script type="text/javascript"> $(function(){ $('#loading').hide(); $('#estadoDropdown').change(function(){ adjustMunicipioDropdown(); }).change(); $('#loading').ajaxStart(function() { $(this).show(); }); $('#loading').ajaxStop(function(){ adjustMunicipioDropdown(); $('#municipio').val('${bci.municipioEntrega.id}'); }).change(); $(this).hide(); }); </script>

porem ficou em um loop infinito, não da para selecionar outro município agora, como fazer essa var booleana, nao saco nada de JS quase. :frowning:

Lucas_Cavalcanti

não coloque o adjust, só o val:

var loaded = false
$('#loading').ajaxStop(function(){  
       if (!loaded) {
         loaded = true;
         $('#municipio').val('${bci.municipioEntrega.id}');  
       }
       $(this).hide();  
});
well

Mantive o ajust de cima.
ficou assim:$(function(){ $('#loading').hide(); $('#estadoDropdown').change(function(){ adjustMunicipioDropdown(); }).change(); $('#loading').ajaxStart(function() { $(this).show(); }); var loaded = false; $('#loading').ajaxStop(function(){ if (!loaded) { loaded = true; $('#municipio').val('${bci.municipioEntrega.id}'); } $(this).hide(); });

porem agora nao aparece nada no combo. :frowning:

Lucas_Cavalcanti

coloque isso como primeira linha dentro do seu $(function(){

if ('${bci.municipioEntrega.id}')
    adjustMunicipioDropdown();

daí ele já preenche os municípios com o que foi colocado na edição

well

Ve se eu coloquei do jeito que vc falou, acho que eu deve ter feito algo errado pois nao deu certo :frowning: :

$(function(){
	if ('${bci.municipioEntrega.id}')
	    adjustMunicipioDropdown();
   $('#loading').hide();
   $('#estadoDropdown').change(function(){
       adjustMunicipioDropdown();
     }).change();
   $('#loading').ajaxStart(function() {
       $(this).show();
   });
   var loaded = false
   $('#loading').ajaxStop(function(){  
          if (!loaded) {
            loaded = true;
            $('#municipio').val('${bci.municipioEntrega.id}');  
          }
          $(this).hide();  
   });
Lucas_Cavalcanti

o combo de municipios veio preenchido? o estado está selecionado?

well

sim o do estado já vem selecionado. mais o do municipio nao esta populando. :frowning:

Lucas_Cavalcanti

ele tava populando antes? se sim talvez tenha algum erro de javascript =/

instala o firebug no firefox e vê se acusa algum erro

well

isso aki que o firebug me mostra

$(function(){
if ('6668')
adjustMunicipioDropdown();
$('#loading').hide();
$('#estadoDropdown').change(function(){
adjustMunicipioDropdown();
}).change();
$('#loading').ajaxStart(function() {
$(this).show();
});
var loaded = false
$('#loading').ajaxStop(function(){
if (!loaded) {
loaded = true;
$('#municipio').val('6668');
}
$(this).hide();
});
Lucas_Cavalcanti

blz, mas aparece que deu algum erro na página?

well

Não diz nada… pelo menos nao vi… quando o codigo estava assim:

<script type="text/javascript">
$(function(){
   $('#loading').hide();
   $('#estadoDropdown').change(function(){
       adjustMunicipioDropdown();
     }).change();
   $('#loading').ajaxStart(function() {
       $(this).show();
   });
   $('#loading').ajaxStop(function(){
	   adjustMunicipioDropdown();
       $('#municipio').val('${bci.municipioEntrega.id}');
     }).change();
       $(this).hide();
   });
</script>

Populava todos, e deixava o o do bd como primeiro, tudo certo… menos pelo simples motivo de ter um loop, que ficava deixando o do banco como principal. nao possibilitando a alteracao. nessa historia tem um detalhe faltando. :confused:

well

Vou parar um pouco, mas tarde eu volto. isso tem que sair, não é possível… ta faltando pouco… obrigado por enquanto Lucas… mais nao desista nao … se nao Lascou. =(. vlw

Lucas_Cavalcanti

tenta assim:

<script type="text/javascript">  
$(function(){  
   $('#loading').hide();  
   $('#estadoDropdown').change(function(){  
       adjustMunicipioDropdown();  
     }).change();  

   if ('${bci.municipioEntrega.id}') {
       function selectMunicipio() {
           if ($('#municipio option[value=${bci.municipioEntrega.id}]').length == 0) {
              setTimeout(selectMunicipio, 100); //pra esperar o select carregar
           } else {
               $('#municipio').val('${bci.municipioEntrega.id}');
           }
       }
   } 

   $('#loading').ajaxStart(function() {  
       $(this).show();  
   });  
   $('#loading').ajaxStop(function(){  
       $(this).hide();  
   });  
</script>
well

Assim nem preencheu o combo, ai adicionei a seguinte linha:

<script type="text/javascript">  
$(function(){  
   $('#loading').hide();  
   $('#estadoDropdown').change(function(){  
       adjustMunicipioDropdown();  
     }).change();  

   if ('${bci.municipioEntrega.id}') {
       function selectMunicipio() {
           if ($('#municipio option[value=${bci.municipioEntrega.id}]').length == 0) {
              setTimeout(selectMunicipio, 100); //pra esperar o select carregar
           } else {
               $('#municipio').val('${bci.municipioEntrega.id}');
           }
       }
   } 

   $('#loading').ajaxStart(function() {  
       $(this).show();  
   });  
   $('#loading').ajaxStop(function(){ 
	   
   }).change();// adicione essa aki, ai preencheu porem nao populou o municipio correto. :(
       $(this).hide();  
   });  
</script>
Lucas_Cavalcanti

estranho, se vc deixasse só isso:

$('#estadoDropdown').change(function(){    
       adjustMunicipioDropdown();    
     }).change();

ele deveria popular os municípios, não?

well

vou tentar isso mais consegui um avanço aki… agora esta populando correto e nao fica em loop, porem quando eu troco o estado funciona legal tb, porem o gif fica aparecendo e nao para mesmo depois de ter carregado os municipios… ma se de tudo nao tiver jeito tiro o gif… olha o codigo:

<script type="text/javascript">  
$(function(){  
   $('#loading').hide();  
   $('#estadoDropdown').change(function(){  
       adjustMunicipioDropdown();  
     }).change();  

   if ('${bci.municipioEntrega.id}') {
       function selectMunicipio() {
           if ($('#municipio option[value=${bci.municipioEntrega.id}]').length == 0) {
              setTimeout(selectMunicipio, 10); //pra esperar o select carregar
           } else {
               $('#municipio').val('${bci.municipioEntrega.id}');
           }
       }
   } 

   $('#loading').ajaxStart(function() {  
       $(this).show();  
   });  
   $('#loading').ajaxStop(function(){ 
	   $('#municipio').val('${bci.municipioEntrega.id}');// coloquei o value aki... pois o change que faz preencher o combo...
   }).change();
       $(this).hide();  
   });  
</script>
Lucas_Cavalcanti

mova o $(this).hide() uma linha pra cima, antes do change()

well

Caraca Lucas vlw uhulll saiu \O/ viva… dei até uma reduzida no codigo… ehhhhhh.
caraca Vc é fera… estávamos próximo da acerto fazia tempo… ganhei o dia…

aki o codigo…

<script type="text/javascript">  
$(function(){  
   $('#loading').hide();  
   $('#estadoDropdown').change(function(){  
       adjustMunicipioDropdown();  
     }).change();  

   $('#loading').ajaxStart(function() {  
       $(this).show();  
   });  
   $('#loading').ajaxStop(function(){ 
	   $('#municipio').val('${bci.municipioEntrega.id}');
	   $(this).hide(); 
   }).change();       
   });  
</script>

Vlw lucas… Pow cara estive no caelum day aki do rio… gostaria de saber se vc tem intencao e previsao de dar uma palestra sobre Vraptor… No rio ou em SP… vlw abração…

Lucas_Cavalcanti

=D

dou palestras de vez em qdo sobre o VRaptor, mas não sei qdo vai ser a próxima…

[]'s

Criado 6 de julho de 2011
Ultima resposta 7 de jul. de 2011
Respostas 30
Participantes 2