Select(combobox) Dynamic

Asked

Viewed 2,162 times

4

I need to use one select dynamic on my page, in which when selecting the state(UF), it shows me in the next select only the cities of this UF. Likewise the neighborhoods. All this information is already in the database.

I’m using Codeigniter, and I’ve tried several ways, but I couldn’t do it. Could someone give me a tutorial, or give me some instructions?

VIEW

<script type="text/javascript">
        var site_url = '<?php echo site_url() ?>'; 
        function search_cidades(uf){
            var uf = uf;
            $.post(site_url+"/clientes/search_cidades_uf", {
                uf : uf
            },function(data){
                $('#cCidade').html(data);
            });
        }
    </script>
    <div class="col-lg-1">
      <div class="form-group">
        <label for="">UF</label>
        <select style="text-transform:uppercase" name="cUf" class="form-control input cUf" id="cUf" onchange='search_cidades($(this).val())'>
          <option>...</option>
            <?php foreach($ufs_item as $uf):
              if($uf['uf'] == $clientes_item['uf']){ ?>
                <option value="<?= $uf['uf'] ?>" selected><?= $uf['uf']; ?></option>
              <?php } else{ ?>
                <option value="<?= $uf['uf'] ?>"><?= $uf['uf']; ?></option>
              <?php } endforeach;?>
        </select>
      </div>
    </div>
    <div class="col-lg-3">
      <div class="form-group">
        <label for="">CIDADE</label>
        <select style="text-transform:uppercase" name="cCidade" class="form-control input cCidade" id="cCidade">
        </select>
      </div>
    </div>

CONTROLLER

class Clientes extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('clientes_model');
        $this->load->model('cnaes_model');
        $this->load->model('bairros_model');

    }


    public function listar_cliente($codigo) {

        $data['clientes_item'] = $this->clientes_model->get_clientes($codigo);
        $data['cnaes_item'] = $this->cnaes_model->get_cnaes();
        $data['bairros_item'] = $this->bairros_model->get_bairros();
        $data['ufs_item'] = $this->localizacao_model->get_ufs();

        if (empty($data['clientes_item'])) {
            show_404();
        } else {
            $data['codigo'] = $data['clientes_item']['codigo'];
            $this->load->view('inc/header_view', $data);
            $this->load->view('clientes/listar_cliente', $data);
        }
    }

    public function search_cidades_uf(){

        $this->load->model("localizacao_model");
        $uf = $this->input->post("uf");
        $cidades = $this->localizacao_model->get_cidades_uf($uf);

        $option = "<option value=''></option>";
        foreach($cidades -> result() as $linha) {
            $option .= "<option value='$linha->codigo_cidade'>$linha->cidade</option>";         
        }

        echo $option;
    }
}

MODEL

class Localizacao_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

    public function get_ufs() {
        $this->db->order_by("uf", "asc");
        $query = $this->db->get("tb_conf_ufs");
        return $query->result_array();
    }

     public function get_cidades() {
        $this->db->order_by("cidades", "asc");
        $query = $this->db->get("tb_conf_cidades");
        return $query->result_array();
    }

    public function get_cidades_uf($uf) {


        $this->db->where("uf", $uf);

        $this->db->order_by("cidades", "asc");

        $query = $this->db->get("tb_conf_cidades");
                return $query->result_array();
    }

}

Shupupmagda, my question is: in the line of the code you suggested

$data['clientes_item'] = ['uf'=>'UF_DA_CIDADE_NO_DB'];//Faça seu $this->clientes_model->get_clientes($codigo) //retornar isso seguindo o padrão já visto acima

You ask to do in get_Clientes(Model) the same as you did get_Cidades(Model), but my get_clients have a lot of information, ie:

$data[] = [
                'codigo' => $item['codigo'],
                'data-cadastro' => $item['data-cadastro'],
                'data-atualizacao' => $item['data-atualizacao'],
                'razao-social' => $item['razao-social'],
                'nome-fantasia' => $item['nome-fantasia'],
                'cnpj' => $item['cnpj'],
                'ie' => $item['nome-fantasia'],
                'cnae' => $item['nome-fantasia'],
                'situacao' => $item['nome-fantasia'],
                'data-abertura' => $item['nome-fantasia'],
                'data-baixa' => $item['nome-fantasia'],
                'faturamento' => $item['nome-fantasia'],
                'capital-social' => $item['nome-fantasia'],
                '' => $item['nome-fantasia'],
                'nome-fantasia' => $item['nome-fantasia'],
                'nome-fantasia' => $item['nome-fantasia']

]

Do I really have to describe all fields in the database or does the result_array already do this? Because in your code you used the Result_array and then foreach.

  • 2

    Put it there like you tried to get people to guide you.

  • 1

    Show us what you tried, otherwise we won’t believe you tried a lot of different ways. The community does not usually help those who did not try, but as you tried, just need to post your attempt. I look forward!

  • 1

    Asking in this way (without showing what you tried) is the same as asking me to do it for you. Show what you’ve done so people can help with the rest. Starting from scratch isn’t "helping".

  • Guys, I included the code I’m using... I did a test with the Uf field, and when selecting it shows through ALERT, which state I’m sending via post. As I said, the field of cities does not appear in any city, even marking the UF.

1 answer

2

My suggestion: As his select will use pre-registered data do this without request. The simple creation of a checkbox should not require multiple requests and queries to the bank (is what I think).

Understand: The request would be interesting if you needed, for example, the user to register new states and cities at the time of use of form, and that the field needs to be constantly updated, which does not seem to be the case.

Make your model load the data into a ARRAY:

public function get_cidades() {
  $data = [];
  $this->db->order_by("cidades", "asc");
  $query = $this->db->get("tb_conf_cidades");
  //The cat's leap: crie um array igual ao que eu pus na resposta
  foreach($query->result_array() as $item){
    $data[] = [
      'uf' => $item['UF_DA_CIDADE_NO_DB'],
      'nome' => $item['NOME_DA_CIDADE_NO_DB']
    ];
  }
  return $data;
}

OBS: what was done with get_cidades() can be done with get_ufs().

Make your controller load the data into view:

function combo($codigo){
        $data['title'] = 'Combobox Dinâmico';
        # Supondo que 'cidades' e 'ufs_item' são os dados do banco
        $data['ufs_item'] = $this->localizacao_model->get_ufs();
        $data['cidades'] = $this->localizacao_model->get_cidades();
        $data['clientes_item'] = $this->clientes_model->get_clientes($codigo);
        $this->template->load('templates/default/index', 'pages/combo', $data);
    }

Make your view use the loaded data to create and manipulate the fields:

<script type="text/javascript">
    //Dados passados pelo controller
    $estados = <?=json_encode($ufs_item)?>;//Todos os estados
    $cidades = <?=json_encode($cidades)?>;//Todas as cidades
    $clientUf = '<?=$clientes_item['UF_DO_CLIENTE']?>';//Cidade do cliente 
    //Manipulação do DOM
    $(function(){
        //Checa o valor de 'clientUf' e preenche 'cCidade' ao carregar
        search_cidades($clientUf);
        // Cria as OPTIONS de #cUf
        $('<option>').val('').text('').appendTo('#cUf');
        $.each($estados, function(key,val){
            //Checa o valor de 'clientUf'
            if($clientUf === val.uf){ $selected = true;}
            else {$selected = false; }
            //Cria o combo com os dados de 'estados' checando 'clientUf'
            $('<option>').val(val.uf).text(val.uf).attr('selected',$selected).appendTo('#cUf');
        });
        // Comportamento do SELECT ao mudar de uf
        $('#cUf').change(function(){
            search_cidades(this.value);
        });
    });
    // Captura as cidades de cada UF
    function search_cidades(uf){
        $('#cCidade').find('option').remove();
        $.each($cidades, function(key,val){
            if(uf === val.uf){
                //Substitui as OPTIONS do 'cCidade'
                $('<option>').val(val.uf).text(val.nome).appendTo('#cCidade');
            }
        });
    }
</script>
<div class="col-lg-1">
    <div class="form-group">
        <label for="">UF</label>
        <select id="cUf" style="text-transform:uppercase" name="cUf" class="form-control input cUf"></select>
    </div>
</div>
<div class="col-lg-3">
    <div class="form-group">
        <label for="">CIDADE</label>
        <select id="cCidade" style="text-transform:uppercase" name="cCidade" class="form-control input cCidade"></select>
    </div>
</div>

Everything is commented on JavaScript, and you should have no difficulty to implement.

  • Thanks friend, I will implant your observations and if you have any questions I will return to post.

  • How best to generate this array using the data I already have in the database?

  • In the Codeigniter the best way is by using a model.

  • Following the line that 'Shutupmagda' suggested, I wanted to know how to generate this list in the code itself (Array), just as he did. It would abandon the consultation in the bank for this feature. I want to create this in the code automatically: $data['cities']=[ 0 => ['Uf'=>'SP','name'=>'City SP 1'], 1 => ['Uf'=>'SP','name'=>'City SP 2'], 2 => ['Uf'=>'SP','name'=>'City SP 3'], ];

  • Mano, the model already gives you that ready, just you use the result of get_cities()...

  • Shtupupmagda, two things I didn’t understand: $data['clientes_item'] = ['Uf'=>'Uf'];//Make your $this->clientes_model->get_clients($code) return this by following the pattern already seen above When you make get_Clients, I have to foreach and put every field you have in the comics on customers,?

  • It is not necessary. If you pay attention to view in my answer you will see that what matters is the value of $clientUf. I will edit the answer (again) to be clearer for you...

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.