从视图中调用 Cakephp 函数


Cakephp calling function from view

我有以下函数:

 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);
}

现在这两个函数没有"连接"到一个视图,但我仍然需要从另一个视图中调用它们

为此,我尝试了以下方法:

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

但是,这抛出了一个错误,说它找不到与make_order匹配的视图,并且有充分的理由(我没有创建一个,我不打算创建一个)

我的

问题是如何从我的视图中调用和执行此函数?

make_order 函数结束时,您需要:

a) 指定要渲染的视图文件,或b) 重定向到具有要渲染的视图文件的其他控制器和/或操作。

a) 看起来像这样:

$this->render('some_other_view_file');

b) 可能看起来像这样(注意:设置闪光消息是可选的)

$this->Session->setFlash(__('Your order was placed'));
$this->redirect(array('controller' => 'some_controller', 'action' => 'some_action'));
您可以通过在

控制器的操作中设置$this->autoRender = false;来关闭自动渲染(在本例中为make_order())。这样,您就不需要视图文件,并且可以输出所需的任何内容。

问题是屏幕上不会呈现任何内容。因此,我的建议是让你的"链接"通过 AJAX 简单地调用控制器::action。如果在您的情况下无法做到这一点,则必须在make_order()方法中呈现视图,或重定向到将呈现视图的操作。