Deploy dependent Select with AJAX and Jquery in Zend

Asked

Viewed 465 times

2

I am new to programming and am putting together a small system for a specific collection control. But I need to fill in some fields without reloading the page (AJAX) and others when the select is set, but I have no idea how to do it.

I am posting the code below and I will explain my goal: I need to make the "Previous Balance" field be filled dynamically after the select "Municipality" be set (taking the id of the municipality and consulting the movement table to fetch the balance).

Model:

class Application_Model_Movimento extends Zend_Db_Table {

protected $_name = 'tb_movimento';
protected $_primary = 'id';

public function inserir($table, $array_dados, $return = null) {
    try {
        return $this->getAdapter()->insert($table, $array_dados);
    } catch (Exception $ex) {
        throw $ex;
    }
}

public function editar($table, $array_dados, $where) {
    try {
        $this->getAdapter()->update($table, $array_dados, $where);
    } catch (Exception $ex) {
        throw $ex;
    }
}

public function excluir($table, $where) {
    try {
        return $this->getAdapter()->delete($table, $where);
    } catch (Exception $ex) {
        throw $ex;
    }
}

public function findMovimento($table, $where) {
    $select = $this->fetchRow($this->select()->setIntegrityCheck(false)->from($table)->where($where));
    return $select->toArray();
}

public function buscar($table) {
    $select = $this->fetchAll($this->select()->setIntegrityCheck(false)->from($table));
    return $select->toArray();
}

}

Controller:

public function salvarMovimentoAction() {
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout->disableLayout();

    $model = new Application_Model_Movimento();
    $util = new Recursos_Util();

    $dados = $this->_getAllParams();
    $id = $dados['id'];
    $where = "id=" . $id;

    //Pegando dados da Tabela Associação
    $resultado_associacao = $model->buscar('tb_associacao');

    //Formatação de Dados para grava no banco
    $id_associacao = $resultado_associacao[0]['id'];
    $valor_bruto_icms = $util->formataNumero($dados['valor_bruto_icms']);
    $valor_saldo_ant = 0;
    $valor_recolher_icms = 0;
    $valor_total = $valor_saldo_ant + $valor_recolher_icms; //Valor da soma total que deve ser recolhida com os lançamentos diários, semanais ou mensais.
    $valor_rec_total = 0; //Valor dos lançamentos acumulados
    $valor_saldo_prox = $valor_total - $valor_rec_total;

    //## Inserindo os Dados ##
    $array_dados = array(
        "id_municipio" => $dados['id_municipio'],
        "data_abertura" => $dados['data_abertura'],
        "data_encerramento" => $dados['data_encerramento'],
        "valor_saldo_ant" => $valor_saldo_ant, //Valor dos saldo de movimentos anteriores que estão pendentes de recolhimento
        "valor_bruto_icms" => $valor_bruto_icms, //Valor do ICMS total do município no período, é digitado pelo usuário
        "valor_recolher_icms" => $valor_recolher_icms,
        "valor_rec_total" => $valor_rec_total,
        "valor_saldo_prox" => $valor_saldo_prox,
        "id_associacao" => $id_associacao
    );

    $table = "tb_movimento";

    if ($id == null) {
        $model->inserir($table, $array_dados);
    } else {
        $model->editar($table, $array_dados, $where);
    }
    return $this->_helper->redirector('index');
}

phtml:

<div><b>Movimentação Financeiro da Associação</b></div>
<form id="incluir-municipio" action="<?php echo $this->url(array('controller' => 'movimento', 'action' => 'salvar-movimento'), null, true) ?>" method="post" class="form-group" role="form">
<div class="form-group">
    <table class="table table-responsive table-striped table-condensed">
        <tr>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="id_municipio">Município</label>
                <select <?= $this->disabled ?> id="id_municipio" name="id_municipio" class="form-control" value="<?= $this->id_municipio ?>" required="required">
                    <option>Selecione um Município</option>

                    <?php foreach ($this->todos_municipios as $municipios) { ?>

                        <option value="<?php echo $municipios['id'] ?>"><?php echo $municipios['nome']; ?></option>

                    <?php } ?>

                </select>
            </td>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="data_abertura">Data de Abertura do Movimento</label>
                <input id="data_abertura" name="data_abertura" class="form-control calendario" value="<?= $this->codigo ?>" placeholder="Selecione a data de abertura" required="required" type="date" maxlength="10" pattern="[0-9]{2}\/[0-9]{2}\/[0-9]{4}$"/>
            </td>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="data_encerramento">Data de Encerramento do Movimento</label>
                <input id="data_encerramento" name="data_encerramento" class="form-control calendario" value="<?= $this->codigo ?>" placeholder="Selecione a data de encerramento" required="required" type="date" maxlength="10" pattern="[0-9]{2}\/[0-9]{2}\/[0-9]{4}$"/>
            </td>
        </tr>
    </table>
    <table class="table table-responsive">
        <tr>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="valor_saldo_ant">Saldo do Movimento Anterior</label>
                <input disabled id="valor_saldo_ant" name="valor_saldo_ant" class="form-control valor_monetario" value="<?= $this->nome ?>" type="text" placeholder="Digite o Nome do Município" required="required">
            </td>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="valor_bruto_icms">Valor Bruto do ICMS do Município</label>
                <input id="valor_bruto_icms" name="valor_bruto_icms" class="form-control valor_monetario" value="<?= $this->nome ?>" type="text" placeholder="Digite o Nome do Município" required="required">
            </td>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="valor_bruto_icms">Valor do ICMS para Associação</label>
                <input disabled id="valor_bruto_icms" name="valor_bruto_icms" class="form-control valor_monetario" value="<?= $this->nome ?>" type="text" placeholder="Digite o Nome do Município" required="required">
            </td>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="valor_recolher_icms">Valor a ser Recolhido</label>
                <input disabled id="valor_recolher_icms" name="valor_recolher_icms" class="form-control valor_monetario" value="<?= $this->nome ?>" type="text" placeholder="Digite o Nome do Município" required="required">
                <p class="help-block" style="font-size: 10px;"><i>Valor ICMS da Associação + Saldo Movimento Anterior</i></p>
            </td>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="valor_rec_total">Valor Recolhido</label>
                <input disabled id="valor_rec_total" name="valor_rec_total" class="form-control valor_monetario" value="<?= $this->nome ?>" type="text" placeholder="Digite o Nome do Município" required="required">
            </td>
            <td class="col-md-3" style="alignment-adjust: central; alignment-baseline: central; width: 200px;">
                <label for="valor_saldo_prox">Saldo para próximo Movimento</label>
                <input disabled id="valor_saldo_prox" name="valor_saldo_prox" class="form-control valor_monetario" value="<?= $this->nome ?>" type="text" placeholder="Digite o Nome do Município" required="required">
            </td>
        </tr>
    </table>
</div>

I know this is done with Jquery + AJAX, but I have no idea how to!

1 answer

0


Jquery code

//Chama assim que você altera o select
$( "#id_municipio" ).change(function() {
    //guarda o value do item selecionado do select
    var id_municipio = $(this).val();

    //Requisição ajax passando o id e a chamando a url do seu action no zend    
    $.get( "localdoaction.php", { id_municipio: "id_municipio"} )
    .done(function( data ) {        
        //a variavel data tem os dados que foram retornado do zend

        //popula o campo com os dados vindos do zend
        $("#valor_saldo_ant").val(data.saldo_anterior);     
    });  
});

This code is for you to get an idea, and in your action you transform the return data into a json using the zend Zend_json function. Take a look at zend and jquery documentation.

Browser other questions tagged

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