Update cart codeigniter

1

I'm having a problem updating the quantity in a shopping cart using codeigniter, because whenever I update and the cart has for example 3 items, the cart only updates the last item and does not update the first 2.

View code

<?php echo form_open('shop/update_car'); ?>


    <?php foreach ($this->cart->contents() as $item): ?>
        <tr>
            <td><?php echo $item['name']; ?></td>
            <td>
                <?php if ($this->cart->has_options($item['rowid'])) {
                    foreach ($this->cart->product_options($item['rowid']) as $option => $value) {
                        echo $option . ": <em>" . $value . "</em>";
                    }

                } ?>
            </td>

            <td><?php echo form_input(array('name' => 'qtde[]', 'value' => $item['qty'], 'size' => '2')); ?></td>
             <?php echo form_hidden('rowid[]', $item['rowid']); ?>
            <td>R$ <?php echo number_format($item['price'],2,',','.'); ?></td>
            <td>R$ <?php echo number_format($item['subtotal'],2,',','.'); ?></td>
            <td class="remove">
                <?php echo anchor('shop/remove/'.$item['rowid'],'X'); ?>
            </td>
        </tr>
    <?php endforeach; ?>
    <tr class="total">
        <td colspan="3"></td>
        <td><?php echo form_submit('', 'atualizar carrinho');?></td>

        <td><strong>Total</strong> R$ <?php echo number_format($this->cart->total(),2,',','.'); ?></td>
    </tr>
    </table>        
</div>

code controller shop

function update_car(){

    $value    = $this->input->post('rowid');
    $quantity = $this->input->post('qtde');

    foreach($value as $values){

        foreach($quantity as $quantitys){

            $update = array(

            'rowid' => $values,
            'qty' => $quantitys 

            );      

        }

    }



    $this->cart->update($update);

    redirect('shop');       
} 
    
asked by anonymous 14.09.2016 / 17:45

1 answer

0

Problem:

As update() is out of foreach only the last item will be updated see that the assignment to $update is redone with every second foreach loop.

Solution

It seems that $value and $quantity has the same number of elements and are related, in that case it is better to change the foreachs by a normal for.

function update_car(){
    $value    = $this->input->post('rowid');
    $quantity = $this->input->post('qtde');

    $total = count($quantity);

    for($i=0; $i<$total; $i++){
        $update = array('rowid' => $value[$i], 'qtde' => $quantity[$i]);
        $this->cart->update($update);
    }
    redirect('shop');  
}
    
14.09.2016 / 19:11