Update field in multiple columns

Asked

Viewed 391 times

8

I have a list of categories and I would like to sort them all at once, so I created a "sort" field where I can put the order number I want [1] and so by pressing to save [2] as the image:

//Controller: administracao.php
function update_ordenacao(){
        $this->load->model("administracao_model");

        $ordemCat = array (
            // coluna                                   // campo form
            "id_categoria_anuncio"              =>      $this->input->post("id_categoria_anuncio"),
            "page_id_categoria_anuncio"         =>      $this->input->post("ordenacao"),
        );

        $sucesso = $this->administracao_model->ordenacaoCats($ordemCat);

        if($sucesso) {
            $this->session->set_flashdata("success", "Ordem alterada com sucesso!");
            redirect("administracao/ver_cat_anuncios");
        } else {
            $this->session->set_flashdata("danger", "A ordem das categorias não pode ser alterada!");
            redirect("administracao/ver_cat_anuncios");
        }


    }

Model:

// Model: administracao_model.php
function ordenacaoCats($ordemCat){

            $data = array(
                array(
                  'id_categoria_anuncio'            => $ordemCat['id_categoria_anuncio'] ,
                  'page_id_categoria_anuncio'       => $ordemCat['page_id_categoria_anuncio']
                )
            );    

            $this->db->update_batch('categorias_anuncios', $data, 'id_categoria_anuncio'); 
            //echo $this->db->last_query();


    }

View:

//View: ver_cat_anuncios.php

                    <?php echo form_open("administracao/update_ordenacao", array('id' =>'categorias-dos-anuncios')); ?>
                    <table class="table table-striped">
                        <tr>
                            <th>#</th>
                            <th>Nome da Categoria</th>
                            <th>Ordenação <?php  echo form_button(array( "class"      => "btn-ordenacao fa fa-floppy-o",  "content"    => "",  "type" => "submit" )); ?></th>
                            <th>Status</th>
                            <th>Ações</th>
                        </tr>

                        <?php if (count($categorias)) : foreach ($categorias as $categoria) :?>
                        <tr>
                            <td><?=$categoria['id_categoria_anuncio']; ?></td>
                            <?php ($categoria['is_parent_categoria_anuncio'] !== "0") ? $espacamento = " " : $espacamento = "- "; ?>

                            <td><?= anchor('administracao/edit_cat_anuncios/' .$categoria['id_categoria_anuncio'], $espacamento.$categoria['titulo_categoria_anuncio']);?></td>
                            <td>
                                <div class="form-group">
                                    <?= form_hidden('id_categoria_anuncio', $categoria['id_categoria_anuncio']);?>
                                    <?= form_input(array(
                                        "name"          =>  "ordenacao",
                                        "value"         =>  $categoria['page_id_categoria_anuncio'],
                                        "id"            =>  "ordenacao",
                                        "class"         =>  "form-control",
                                        "maxlength"     =>  "3",
                                        "style"         =>  "width: 60px; text-align: center;"
                                    )); ?>
                                </div>
                            </td>
                            <td><?php if($categoria['show_menu_categoria_anuncio'] == 1) {echo "<span style=\"color: #009202; font-weight: bold;\">Ativado</span>";} else {echo "<span style=\"color: #e10707; font-weight: bold;\">Desativado</span>";} ?> </td>
                            <td>
                                <div class="btn-group" role="group" aria-label="Ações">
                                    <?= btn_edit('administracao/edit_cat_anuncios/'. $categoria['id_categoria_anuncio'] );?>
                                    <?= btn_delete('administracao/deleta_cat_anuncios/'. $categoria['id_categoria_anuncio'] );?>                                    
                                </div>                              
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5"><p class="text-info">Não há nenhuma categoria no sistema!</p></td>
                            </tr>

                        <?php endif;?>
                    </table>
                    <?php echo form_close(); ?>

This my code I did taking a look at the documentation of Codeigniter

$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'
   )
);

$this->db->update_batch('mytable', $data, 'title'); 

// Produces: 
// UPDATE `mytable` SET `name` = CASE
// WHEN `title` = 'My title' THEN 'My Name 2'
// WHEN `title` = 'Another title' THEN 'Another Name 2'
// ELSE `name` END,
// `date` = CASE 
// WHEN `title` = 'My title' THEN 'My date 2'
// WHEN `title` = 'Another title' THEN 'Another date 2'
// ELSE `date` END
// WHERE `title` IN ('My title','Another title')

I wonder what I’m doing wrong?

  • You just didn’t say what’s going wrong.

  • Hi! The screen is all white.. I look at the source code and there is nothing.. Actually to see the white screen I had to take the "if($success) ....

  • I didn’t understand what your problem or your mistake! Is there any way to put more details.

  • If you want to submit several elements at once that are equal, you have to put name="ordenacao[]" and capture in the foreach $_POST['ordenacao'].

1 answer

0

From what I understand you are wanting to save the sort you put for each item (category), but the first mistake I see is in your view. You must enter the name and id of the field with []

<?= form_input(array(
    "name"          =>  "ordenacao[]",
    "value"         =>  $categoria['page_id_categoria_anuncio'],
    "id"            =>  "ordenacao[]",
    "class"         =>  "form-control",
    "maxlength"     =>  "3",
    "style"         =>  "width: 60px; text-align: center;"
)); ?>

I don’t know how this data is being sent to the controller, but I imagine that for a js, then you should take this data $this->input->post("ordenacao") and loop that data and then do the update_batch.

The way you did, so you wouldn’t have to change your controller and only your model would look like this:

function ordenacaoCats($ordemCat){

    $data = array();

    foreach ($ordemCat['page_id_categoria_anuncio'] as $ord) {
        $data[] = array(
                'id_categoria_anuncio'      => $ordemCat['id_categoria_anuncio'] ,
                'page_id_categoria_anuncio' => $ord
            );
    }    

    $this->db->update_batch('categorias_anuncios', $data, 'id_categoria_anuncio'); 
    //echo $this->db->last_query();


}

Remember, I can’t test here, but that’s the idea.

  • I guess you’re right, I didn’t know I’d have to run it like an Array, but thinking about it, it’s right your way. There’s just no way I can test it now because I’m out this week. There’s only one thing. The data is being sent normally through a Ubmit which is the button with the number 2 on the side of the image... if you have to send through a Js no longer know how to do.. rs I will check if the code is right when I return and then answer/rate :) But already I want to thank you for the help.

  • Hello Marcelo! All good? Sorry the delay in answering. As said would not be next to the code during the week. I have tested now and unfortunately the code did not work. I don’t know if I’ve done anything wrong yet, but it turns out that I was able to do one for and without update_batch and put a common update... Well, it worked.. Thank you for your time!

  • So Vitor, the bad side of the way you did is that each iteration will run the update and when you have many records to do the update will take a little longer, and you would know to say what did not work in the code?

  • I don’t know if I did it right, but I tried several combinations of variables in the code you gave me. But for the project I’m doing there won’t be many categories. and this will be done in the administrator from time to time and only when you need to put a new category that needs to go somewhere other than last. Anyway... unfortunately I no longer knew the "batch" itself outside of codeigniter, because unfortunately I have little time studying programming... So I’m still slowly learning what I can and cannot do with language. Thanks for the strength once again! :)

Browser other questions tagged

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