简体   繁体   中英

form_open in codeigniter

I have a url that looks like this:

http://localhost/store/mens/category/t-shirts/item/at-shirt

I have a class called store and at this point in my application the item function has been called and some data about a product has been output on the page.

I need to allow a user to add the item to a basket. I know CI provides a library to help with this and I've built a simple class that will interact with this library to create the shopping cart functionality. Problem is I don't understand how I'm supposed to get the form to submit to my shopping cart class and then return to the current url with all the parameters intact like above. Using:

<?= form_open('cart/addItem',array('class' => 'basketForm')); ?>

submits to the correct class but then I have no mechanism to get back to the product page afterwards.

The only way I can think to do it is to send the url along to the cart class and redirect once the cart stuff is done....or use AJAX...but both seem like hacks to get this working.

Is there a clean way to do this?

Redirect to the referrer page with one of two approaches:

1. In the Controller only:

<?php
class Cart extends CI_Controller {
    public function addItem()
    {
        // ... add to cart here
        redirect($_SERVER['HTTP_REFERER']);
    }
}

2. From the view, tell the controller where you want it to go after:

<!-- Form view //-->
<?= form_open('cart/addItem',array('class' => 'basketForm')); ?>
<?= form_hidden('next_URI', current_url()); // requires URL_helper ?>
...
<?= form_submit('', 'Add to Cart'); ?>
<?= form_close(); ?>


<?php
// Controller
class Cart extends CI_Controller {
    public function addItem()
    {
        // ... add to cart here
        redirect($this->input->post('next_URI'));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM