简体   繁体   English

从视图中调用Cakephp函数

[英]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) 但是这引发了一个错误,说它找不到与make_order相匹配的视图,这是有充分的理由的(我创建了一个视图,但我不打算创建一个视图)

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: make_order函数的最后,您要么需要:

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)指定要渲染的视图文件,或b)重定向到确实具有要渲染的视图文件的其他控制器和/或操作。

a) would look like this: a)看起来像这样:

$this->render('some_other_view_file');

b) might look like this (note: setting the flash message is optional) b)可能看起来像这样(注意:设置即显消息是可选的)

$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; 您可以通过设置$this->autoRender = false;来关闭自动渲染$this->autoRender = false; in your controller's action ( make_order() in this case). 在控制器的操作中(在这种情况下为make_order() )。 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. 因此,我的建议是让您的“链接”仅通过AJAX调用controller :: action。 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. 如果在您的情况下无法做到这一点,则必须在make_order()方法中呈现视图,或重定向到将呈现视图的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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