简体   繁体   中英

How to call a function of a controller from a view?

There is a controller :

use Phalcon\Mvc\Controller;
class ReferentielClientController extends Controller
{

    public function indexAction(){
        // moteur de template pour une View
        $this->view->act_form = 'ReferentielClient/ajouterClient';
        return $this->view->pick("client/listerClient");
    }

    public function ajouterClientAction(){
        $this->view->action_form = 'ajouterClientExec';
        return $this->view->pick("client/ajouterClient");
    }
    ...
}

From a view I want to call the indexAction method of the controller ReferentielClientController . How to do that ?

Short answer: You can't.

You can't since indexAction is not a normal method, it's an action. Actions aren't called by anyone in the usual way that methods are, they are called with routes an url. Let me explain this a little bit further:

Using MVC , we have the following route using : http://www.example.org/a/b/c

a is which we call module. b is which we call controller. And c is which we call action.

Index actions and default modules will not appear in the URL.

So, how to call functions from view? Better not to. Best way to proceed is to do everything in your controller and pass that info to the view. Ie:

public function indexAction(){
    $this->view->myInfo = $allMyInformationInOneObject;
}

And then, in the view (index.phtml):

<p>
    <?php echo $this->myInfo ?>
</p>

Summary: You don't need to call any controller function from the view, just give it that info from the controller.

Added info about redirection

OK, answering to your commentary. What you want is not to call that function but to redirect the browser to that action.

So, I'll suppose you have your route created in your router, if not, please, go to the Zend documentation about routing . It's highly recommended to create routes instead of using the URL itself.

I guess that you will not be able to use the normal redirecting using href on a button or such, so you will need to use the redirector helper. Since you are not in a controller, you are not able to use the helper by using:

$this->_helper->redirector->gotoUrl($url);

So you will need to instance the redirector like this:

$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoUrl($url);

Being this $url, the URL given by your router, as you can read in the link above.

This can be done but I strongly recommend not to redirect from the view but from the controller. It would be good that all the logic remains in the controller.

I hope this helps!

好的,我找到了它:我将href设置为指向控制器: <a href="/resto/ReferentielClient" class="button default">Annuler</a>

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