Álvaro González
Álvaro González

Reputation: 146450

Process post action with another action within controller

I have a terribly designed app where the index action displays a form in a JavaScript-based dialogue that's submitted to process action and then redirects to index (either on success or on error). The process action does not even have a view:

class UnicornsController
{
    public function index($foo, $bar)
    {
        $this->set(
            array(
                'unicorn' => $this->Unicorn->findByFooAndBar($foo, $bar);
            )
        );
    }

    public function process()
    {
        $this->Unicorn->save($this->request->data);
        $this->redirect(
            array(
                'action' => 'index',
                $this->request->data['Unicorn']['foo'],
                $this->request->data['Unicorn']['bar'],
            )
        );
    }
}

I'm adding proper error reporting. I'm trying to change the this->redirect() part so $this->request->data is not lost and I have a chance to display it again in the form generated in index.ctp but I can't get it right: both $this->requestAction() and $this->index() try to render process.ctp anyway. Am I using them incorrectly or I'm missing the right approach?

Upvotes: 0

Views: 59

Answers (1)

ndm
ndm

Reputation: 60463

If you want to run a different action, you can use Controller::setAction(), it changes the action parameter in the request, sets the template to render accordingly, and returns the possible return value of the invoked action.

public function process()
{
    // ....

    $this->setAction(
        'index',
        $this->request->data['Unicorn']['foo'],
        $this->request->data['Unicorn']['bar']
    );
}

See also

Upvotes: 1

Related Questions