简体   繁体   中英

Cakephp calling function from view

I have the following function:

 public function make_order($id = null){
        if($this->request->is('post')){
            if(isset($id)){
                $single_product = $this->Product->find('first', array('Product.id' => $id));
                $this->placeOrder($single_product);
            }else{
                $product_array = $_SESSION['basket'];
                foreach($product_array as $product){
                    $this->placeOrder($product);
                }
            }

        }
}
private function placeOrder($product){
    $order_array = array();

    $order_array['Order']['Product_id'] = $product['Product']['id'];
    $order_array['Order']['lejer_id'] = $this->userid;
    $order_array['Order']['udlejer_id'] = $product['users_id'];
    $this->Order->add($order_array);
}

Now these two function are not "connected" to a view but i still need to call them from within another view

For this ive tried the following:

<?php echo $this->Html->link(__('Bestil'), array('action' => 'make_order')); ?>

However this throws an error saying it couldnt find the view matching make_order and for good reason ( i havnt created one and i do not intend to create one)

My question is how do i call and execute this function from within my view?

At the end of your make_order function, you'll either need to:

a) specify a view file to render, or b) redirect to a different controller and / or action, that does have a view file to render.

a) would look like this:

$this->render('some_other_view_file');

b) might look like this (note: setting the flash message is optional)

$this->Session->setFlash(__('Your order was placed'));
$this->redirect(array('controller' => 'some_controller', 'action' => 'some_action'));

You can turn auto-rendering off by setting $this->autoRender = false; in your controller's action ( make_order() in this case). This way you don't need a view file, and you can output whatever you need.

The problem is that nothing will be rendered on the screen. Therefore, my advice is to have your "link" simply call a controller::action via AJAX. If that's not possible in your situation, then you'll have to either render a view in your make_order() method, or redirect to an action that will render a view.

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