tags:

views:

981

answers:

4
+1  Q: 

cakephp contollers

There are two buttons in my cakephp page,one for registering new users and the other one for login. Can both the button's action be directed to the same function in the controller and have the same view.ctp file?? if yes,how can I do it?

A: 

Well, yes, why not? Isn't this only a matter of setting the appropriate URL in your form actions? Or am I missing something?

dr Hannibal Lecter
A: 

You can use a hidden form value to denote which action it is.

$form->create('User', array('action' => 'process');
$form->hidden('User.signup', array('value' => '1'));
$form->end('Signup');

$form->create('User', array('action' => 'process');
$form->hidden('User.login', array('value' => '1'));
$form->end('Login');

It isn't exactly clear why you don't want to use 2 functions though. You are basically going to have to manually check which action it is, instead of letting cake do it for you.

In your controller

function process()
{
    if ($this->data['User']['signup'] == 1)
    {
        // process signup
    }
    if ($this->data['User']['login'] == 1)
    {
        // process login
    }
}
Jack B Nimble
This example uses two different functions:signup() and login()
ByteNirvana
Good point. Hmmm.
Jack B Nimble
+1  A: 

Yes, just set the correct URL in your buttons. But I don't know why you would do this. If it is just about re-using the view.ctp then you do not need to use a single action just to use the same view. Example:

<?php
class FoobarController extends AppController
{
    function view()
    {
        // This will render views/foobar/view.ctp because the action
        // is named "view"
    }

    function register()
    {
        // Normally this would render views/foobar/register.ctp but you can
        // call the render() function manually and render something else. The
        // following call will render views/foobar/view.ctp
        $this->render('view');
    }

    function login()
    {
        // Same thing here...
        $this->render('view');
    }
}
?>
Sander Marechal
A: 

I create buttons in my CRUD admin pages that allow either "Confirm (edit/delete/create/etc)" or "Cancel". I do this by creating 2 submit buttons in the form, and giving each a unique name. For example:

View code:

...
$form->submit('Delete', array('name' => 'delete'));
$form->submit('Cancel', array('name' => 'cancel'));
...

Action logic:

function admin_delete( ... ) {

  // Bail if cancel button pressed
  if (isset($this->params['form']['cancel'])) {
    $this->redirect('/');
  }

  // Delete if delete button pressed
  if (isset($this->params['form']['delete'])) {
    // delete stuff
    ...
  }
  ...
}

On the flip side, you're essentially smashing 2 actions into one for the sake of reusing a view. Sander Marechal's solution is better.

drfloob