PHP + Codeigniter - Persist query parameter in pagination

Asked

Viewed 350 times

3

Dear friends

I resort to help in PHP+Codeigniter. I am new to Codeigniter and I have the following question.

I would like to Persist the Pagination Search parameter that I’m not getting. After choosing the customer category, for example: Individual or Legal, I would like the pagination not to lose its parameter.

Note: When I make the total pagination, there is no error. The error only occurs after choosing the meter.

Below is my source code I’m using.

=====Model=====

class Clientes_model extends CI_Model {

function __construct() {
    parent::__construct();
}


function get($table,$fields,$where='',$perpage=0,$start=0,$one=false,$array='array'){

    $this->db->select($fields);
    $this->db->from($table);        
    $this->db->order_by('idClientes','asc');
    $this->db->limit($perpage,$start);
    if($where){
        $this->db->where($where);
    }        

    $query = $this->db->get();

    $result =  !$one  ? $query->result() : $query->row();
    return $result;
}

function getById($id){
    $this->db->where('idClientes',$id);
    $this->db->limit(1);
    return $this->db->get('clientes')->row();
}

function add($table,$data){
    $this->db->insert($table, $data);         
    if ($this->db->affected_rows() == '1')
    {
        return TRUE;
    }

    return FALSE;       
}

function edit($table,$data,$fieldID,$ID){
    $this->db->where($fieldID,$ID);
    $this->db->update($table, $data);

    if ($this->db->affected_rows() >= 0)
    {
        return TRUE;
    }

    return FALSE;       
}

function delete($table,$fieldID,$ID){
    $this->db->where($fieldID,$ID);
    $this->db->delete($table);
    if ($this->db->affected_rows() == '1')
    {
        return TRUE;
    }

    return FALSE;        
}

function count($table) {
    return $this->db->count_all($table);
}

public function getOsByCliente($id){
    $this->db->where('clientes_id',$id);
    $this->db->order_by('idOs','desc');
    $this->db->limit(10);
    return $this->db->get('os')->result();
}

}

=====Controller=====

class Clientes extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if((!$this->session->userdata('session_id')) || (!$this->session->userdata('logado'))){
          redirect('siscom/login');
        }

        $this->load->model('clientes_model','',TRUE);
        $this->data['menuClientes'] = 'clientes';
        $this->load->helper(array('codegen_helper'));            
}   

public function index(){
   $this->gerenciar();
}

public function gerenciar(){
    if(!$this->permission->checkPermission($this->session->userdata('permissao'),'vCliente')){
       $this->session->set_flashdata('error','Você não tem permissão para visualizar clientes.');
       redirect(base_url());
    }


    $busc = '';
    $tipPes = $this->input->get('tipPes');

    // busca todos os lançamentos
    if(! isset($tipPes) || $tipPes == 'todas'){                  
        $busc = ''; 
        } else {
        if($tipPes == 'fisica'){
            $busc = 'tipoPessoa = "fisica"'; 
        } else {
            if($tipPes == 'juridica'){
                $busc = 'tipoPessoa = "juridica"';
            }
        }
    }   


    $this->load->library('table');
    $this->load->library('pagination');


    $config['base_url'] = base_url().'index.php/clientes/gerenciar/';
    $config['total_rows'] = $this->clientes_model->count('clientes');
    $config['per_page'] = 10;
    $config['next_link'] = 'Próxima';
    $config['prev_link'] = 'Anterior';
    $config['full_tag_open'] = '<div class="pagination alternate"><ul>';
    $config['full_tag_close'] = '</ul></div>';
    $config['num_tag_open'] = '<li>';
    $config['num_tag_close'] = '</li>';
    $config['cur_tag_open'] = '<li><a style="color: #2D335B"><b>';
    $config['cur_tag_close'] = '</b></a></li>';
    $config['prev_tag_open'] = '<li>';
    $config['prev_tag_close'] = '</li>';
    $config['next_tag_open'] = '<li>';
    $config['next_tag_close'] = '</li>';
    $config['first_link'] = 'Primeira';
    $config['last_link'] = 'Última';
    $config['first_tag_open'] = '<li>';
    $config['first_tag_close'] = '</li>';
    $config['last_tag_open'] = '<li>';
    $config['last_tag_close'] = '</li>';

    $this->pagination->initialize($config);     

    $this->data['results'] = $this->clientes_model->get('clientes','idClientes,nomeCliente,documento,tipoPessoa,telefone,celular,email,rua,numero,bairro,cidade,estado,cep',$busc,$config['per_page'],$this->uri->segment(3));

    $this->data['view'] = 'clientes/clientes';
    $this->load->view('tema/header',  $this->data);
    $this->load->view('tema/footer');


}

public function autonomo() {
    if(!$this->permission->checkPermission($this->session->userdata('permissao'),'aCliente')){
       $this->session->set_flashdata('error','Você não tem permissão para adicionar clientes.');
       redirect(base_url());
    }

    $this->load->library('form_validation');
    $this->data['custom_error'] = '';

    if ($this->form_validation->run('clientes') == false) {
        $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">' . validation_errors() . '</div>' : false);
    } else {
        $data = array(
            'nomeCliente' => set_value('nomeCliente'),
            'documento' => set_value('documento'),
            'tipoPessoa' =>   $this->input->post('tipoPessoa'),
            'telefone' => set_value('telefone'),
            'celular' => $this->input->post('celular'),
            'email' => set_value('email'),
            'rua' => set_value('rua'),
            'numero' => set_value('numero'),
            'bairro' => set_value('bairro'),
            'cidade' => set_value('cidade'),
            'estado' => set_value('estado'),
            'cep' => set_value('cep'),
            'dataCadastro' => date('Y-m-d')
        );

        if ($this->clientes_model->add('clientes', $data) == TRUE) {
            $this->session->set_flashdata('success','Cliente adicionado com sucesso!');
            redirect(base_url() . 'index.php/clientes/autonomo/');
        } else {
            $this->data['custom_error'] = '<div class="form_error"><p>Ocorreu um erro.</p></div>';
        }
    }
    $this->data['view'] = 'clientes/adicionarFisica';
    $this->load->view('tema/header',  $this->data);
    $this->load->view('tema/footer');

}

public function empresa() {
    if(!$this->permission->checkPermission($this->session->userdata('permissao'),'aCliente')){
       $this->session->set_flashdata('error','Você não tem permissão para adicionar clientes.');
       redirect(base_url());
    }

    $this->load->library('form_validation');
    $this->data['custom_error'] = '';

    if ($this->form_validation->run('clientes') == false) {
        $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">' . validation_errors() . '</div>' : false);
    } else {
        $data = array(
            'nomeCliente' => set_value('nomeCliente'),
            'documento' => set_value('documento'),
            'tipoPessoa' => $this->input->post('tipoPessoa'),
            'telefone' => set_value('telefone'),
            'celular' => $this->input->post('celular'),
            'email' => set_value('email'),
            'rua' => set_value('rua'),
            'numero' => set_value('numero'),
            'bairro' => set_value('bairro'),
            'cidade' => set_value('cidade'),
            'estado' => set_value('estado'),
            'cep' => set_value('cep'),
            'dataCadastro' => date('Y-m-d')
        );

        if ($this->clientes_model->add('clientes', $data) == TRUE) {
            $this->session->set_flashdata('success','Cliente adicionado com sucesso!');
            redirect(base_url() . 'index.php/clientes/empresa/');
        } else {
            $this->data['custom_error'] = '<div class="form_error"><p>Ocorreu um erro.</p></div>';
        }
    }
    $this->data['view'] = 'clientes/adicionarJuridica';
    $this->load->view('tema/header',  $this->data);
    $this->load->view('tema/footer');

}


public function editar() {
    if(!$this->permission->checkPermission($this->session->userdata('permissao'),'eCliente')){
       $this->session->set_flashdata('error','Você não tem permissão para editar clientes.');
       redirect(base_url());
    }
    $this->load->library('form_validation');
    $this->data['custom_error'] = '';

    if ($this->form_validation->run('clientes') == false) {
        $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">' . validation_errors() . '</div>' : false);
    } else {
        $data = array(
            'nomeCliente' => $this->input->post('nomeCliente'),
            'documento' => $this->input->post('documento'),
            'tipoPessoa' => $this->input->post('tipoPessoa'),
            'telefone' => $this->input->post('telefone'),
            'celular' => $this->input->post('celular'),
            'email' => $this->input->post('email'),
            'rua' => $this->input->post('rua'),
            'numero' => $this->input->post('numero'),
            'bairro' => $this->input->post('bairro'),
            'cidade' => $this->input->post('cidade'),
            'estado' => $this->input->post('estado'),
            'cep' => $this->input->post('cep')
        );

        if ($this->clientes_model->edit('clientes', $data, 'idClientes', $this->input->post('idClientes')) == TRUE) {
            $this->session->set_flashdata('success','Cliente editado com sucesso!');
            redirect(base_url() . 'index.php/clientes/editar/'.$this->input->post('idClientes'));
        } else {
            $this->data['custom_error'] = '<div class="form_error"><p>Ocorreu um erro</p></div>';
        }
    }


    $this->data['result'] = $this->clientes_model->getById($this->uri->segment(3));
    $this->data['view'] = 'clientes/editarCliente';
    $this->load->view('tema/header',  $this->data);
    $this->load->view('tema/footer');

}

public function visualizar(){

    if(!$this->permission->checkPermission($this->session->userdata('permissao'),'vCliente')){
       $this->session->set_flashdata('error','Você não tem permissão para visualizar clientes.');
       redirect(base_url());
    }

    $this->data['custom_error'] = '';
    $this->data['result'] = $this->clientes_model->getById($this->uri->segment(3));
    $this->data['results'] = $this->clientes_model->getOsByCliente($this->uri->segment(3));
    $this->data['view'] = 'clientes/visualizar';
    $this->load->view('tema/header',  $this->data);
    $this->load->view('tema/footer');


}

public function excluir(){

        if(!$this->permission->checkPermission($this->session->userdata('permissao'),'dCliente')){
           $this->session->set_flashdata('error','Você não tem permissão para excluir clientes.');
           redirect(base_url());
        }


        $id =  $this->input->post('id');
        if ($id == null){

            $this->session->set_flashdata('error','Erro ao tentar excluir cliente.');            
            redirect(base_url().'index.php/clientes/gerenciar/');
        }

        //$id = 2;
        // excluindo OSs vinculadas ao cliente
        $this->db->where('clientes_id', $id);
        $os = $this->db->get('os')->result();

        if($os != null){

            foreach ($os as $o) {
                $this->db->where('os_id', $o->idOs);
                $this->db->delete('servicos_os');

                $this->db->where('os_id', $o->idOs);
                $this->db->delete('produtos_os');


                $this->db->where('idOs', $o->idOs);
                $this->db->delete('os');
            }
        }

        // excluindo Vendas vinculadas ao cliente
        $this->db->where('clientes_id', $id);
        $vendas = $this->db->get('vendas')->result();

        if($vendas != null){

            foreach ($vendas as $v) {
                $this->db->where('vendas_id', $v->idVendas);
                $this->db->delete('itens_de_vendas');


                $this->db->where('idVendas', $v->idVendas);
                $this->db->delete('vendas');
            }
        }

        //excluindo receitas vinculadas ao cliente
        $this->db->where('clientes_id', $id);
        $this->db->delete('lancamentos');



        $this->clientes_model->delete('clientes','idClientes',$id); 

        $this->session->set_flashdata('success','Cliente excluido com sucesso!');            
        redirect(base_url().'index.php/clientes/gerenciar/');
}

}

=====View=====

<?php if($this->permission->checkPermission($this->session->userdata('permissao'),'aCliente')){ ?>
<div class="span5" style="margin-left: 0; margin-bottom: 10px;">
<a href="<?php echo base_url();?>index.php/clientes/empresa" class="btn btn-success"><i class="icon-plus icon-white"></i> Pessoa Jurídica</a>    
<a href="<?php echo base_url();?>index.php/clientes/autonomo" class="btn btn-primary"><i class="icon-plus icon-white"></i> Pessoa Física</a>    

<?php $tipPes = $this->input->get('tipPes'); ?>
<div class="span7" style="margin-left: 0px; margin-top: -17px;">
<form action="<?php echo current_url(); ?>" method="get" >
    <div class="span4" style="margin-left: 0px;">
                <label><strong>Situação</strong> <i class="icon-info-sign tip-top" title="Selecione o Tipo de Pessoa."></i></label>
                <select id="tipPes" name="tipPes" class="span12" style="margin-top: -4px;">
                    <option selected disabled class="text-hide">Selecione uma opção...</option>                     
                    <option value="todas">Todas</option>
                    <option value="fisica" <?php if($tipPes == 'fisica'){ echo 'selected';} ?>>Fisica</option>
                    <option value="juridica" <?php if($tipPes == 'juridica'){ echo 'selected';} ?>>Jurídica</option>
                </select>
    </div>    

    <div class="span4" style="margin-top: 0px;">
       &nbsp <button type="submit" class="span12 btn btn-warning"><i class="icon-search"></i> Pesquisar</button>
    </div>

</form>
</div>
 <div class="widget-box">
    <div class="widget-title">
        <span class="icon">
            <i class="icon-user"></i>
        </span>
        <h5>Clientes</h5>

    </div>

    <div class="widget-content nopadding">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Nome</th>
                    <th>CPF/CNPJ</th>
                    <th>Telefone</th>
                    <th>Pessoa</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td colspan="5">Nenhum Cliente Cadastrado</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<?php } else { ?>

<div class="widget-box">
 <div class="widget-title">
    <span class="icon">
        <i class="icon-user"></i>
     </span>
    <h5>Clientes</h5>

 </div>

 <thead>
    <tr>
        <th>#</th>
        <th>Nome</th>
        <th>CPF/CNPJ</th>
        <th>Telefone</th>
        <th>Pessoa</th>
        <th>Ações</th>
    </tr>
 </thead>
 <tbody>
    <?php foreach ($results as $r) {

        //Comando para mudar a cor do texto - Pessoa Física e Jurídica
        if($r->tipoPessoa == 'juridica'){ $text = 'success'; } else { $text = 'info'; }

        echo '<tr>';
        echo '<td style="text-align: center">'.$r->idClientes.'</td>';
        echo '<td>'.$r->nomeCliente.'</td>';
        echo '<td style="text-align: center">'.$r->documento.'</td>';
        echo '<td style="text-align: center">'.$r->telefone.'</td>';
        echo '<td style="text-align: center; font-size: 13px;">
                  <strong class="text text-'.$text.'">'.ucfirst($r->tipoPessoa).'</strong></td>';  
        echo '<td style="text-align: center">';
        if($this->permission->checkPermission($this->session->userdata('permissao'),'vCliente')){
            echo '<a href="'.base_url().'index.php/clientes/visualizar/'.$r->idClientes.'" style="margin-right: 1%" class="btn tip-top" title="Ver mais detalhes"><i class="icon-search"></i></a>'; 
        }
        if($this->permission->checkPermission($this->session->userdata('permissao'),'eCliente')){
            echo '<a href="'.base_url().'index.php/clientes/editar/'.$r->idClientes.'" style="margin-right: 1%" class="btn btn-info tip-top" title="Editar Cliente"><i class="icon-pencil icon-white"></i></a>'; 
        }
        if($this->permission->checkPermission($this->session->userdata('permissao'),'dCliente')){
            echo '<a href="#modal-excluir" role="button" data-toggle="modal" cliente="'.$r->idClientes.'" style="margin-right: 1%" class="btn btn-danger tip-top" title="Excluir Cliente"><i class="icon-remove icon-white"></i></a>'; 
        }


        echo '</td>';
        echo '</tr>';
    }?>
    <tr>

    </tr>
 </tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links();}?>




<!-- Modal -->
<div id="modal-excluir" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <form action="<?php echo base_url() ?>index.php/clientes/excluir" method="post" >
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h5 id="myModalLabel">Excluir Cliente</h5>
  </div>
  <div class="modal-body">
    <input type="hidden" id="idCliente" name="id" value="" />
    <h5 style="text-align: center">Deseja realmente excluir este cliente e os dados associados a ele (OS, Vendas, Receitas)?</h5>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Cancelar</button>
    <button class="btn btn-danger">Excluir</button>
  </div>
  </form>
</div>


<script type="text/javascript">
$(document).ready(function(){


   $(document).on('click', 'a', function(event) {

        var cliente = $(this).attr('cliente');
        $('#idCliente').val(cliente);

    });

});

</script>

Please, could you help me with this question.

Grateful,

Renato

2 answers

0

<nav aria-label="Page navigation">

  <ul class="pagination justify-content-center pagination-md">
  <?php
  $anterior=$pagina-1;
  $classAnterior=$pagina==1 ? "disabled" : "";
?>
    <li class="page-item <?php echo $classAnterior; ?>">
      <a class="page-link" href="index.php?pagina=<?php echo $anterior; ?>" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
        <span class="sr-only">Previous</span>
      </a>
    </li>

    <?php
    $inicio = $pagina > $itens_por_pagina ? $pagina - $itens_por_pagina + 1 : 1;

    //$final= $pagina > $itens ? $pagina : $itens > $numero_paginas ? $numero_paginas : $itens;

    if($pagina > $itens_por_pagina){
      $final=$pagina;
    }else{

      if($itens_por_pagina > $numero_paginas){
        $final=$numero_paginas;
      }else{
        $final=$itens_por_pagina;
      }
    }

    for( $i=$inicio; $i<=$final; $i++) { ?>

        <li class="page-item"><a class="page-link" href="index.php?pagina=<?php echo $i; ?>"><?php echo $i; ?></a></li>

   <?php } ?>


   <?php
  $proximo=$pagina+1;
  $classProximo=$pagina == $numero_paginas ? "disabled" : "";
?>
    <li class="page-item <?php echo $classProximo; ?>">
      <a class="page-link" href="index.php?pagina=<?php echo $proximo; ?>" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
        <span class="sr-only">Next</span>
      </a>
    </li>

  </ul>
</nav>

link to google drive with full design

  • Be clearer in your answer. Just presenting the code may not help, because in addition to the user other people who have similar problem will also look for this question in the future. Also don’t leave the answer code in link even more for virtual driver.

0

In your paging configuration, try to put this:

$config["base_url"] = site_url('clientes/gerenciar/page');
$config['first_url'] = site_url('clientes/gerenciar/page/1').(!empty($this->input->get()) ? '?'.http_build_query($this->input->get()) : ''); 
$config["uri_segment"] = 4;
$config['use_page_numbers'] = TRUE;
$config["reuse_query_string"] = TRUE;
  • Dear friend. I thank you for your attention, but unfortunately it did not work, still losing the focus of the search.

Browser other questions tagged

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