We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Model validation redirect problem

Hi,

I've this validation on my model:

public function validation()
{
    $this->validate(new PresenceOf(array(
        'field'   => 'autor',
        'message' => 'The name is required'
    )));

    if ($this->validationHasFailed() == true) {
        return false;
    }
}

The user submits a form on a page with this URL: https://www.domain.com/backoffice/authors/edit/4/

When the validation fails, the user is redirected to this URL (notice the "id" parameter name): https://www.domain.com/backoffice/authors/edit/id/4/

How can I change this redirect? Or how can I get the value of the "id" parameter without creating a route rule for this?

Thank you.



98.9k

If you don't want to add a route for this, you could expect the id on both first and second parameter in your action:

public function editAction($p1, $p2=null) {
    if ($p1 == 'id') {
        $id = $p2;
    } else {
        $id = $p1;
    }
    //...
}

Or, You can add a plugin to the dispatcher that fixes the parameters:

//Create/Get an EventManager
$eventsManager = new Phalcon\Events\Manager();

//Attach a listener
$eventsManager->attach("dispatch", function($event, $dispatcher) {
    if ($event->getType() == "beforeExecuteRoute") {
        $parameters = $dispatcher->getParams();
        if (count($parameters) > 1) {
            if ($parameters[0] == 'id') {
                unset($parameters[0]);
            }
            $dispatcher->setParams($parameters);
        }
    }
});

I liked the plugin way.

But I would like to understand the reason why the validation redirects to a different URL. Shouldn't it redirect the user to the referer url?



98.9k

Actually, Phalcon does not add that "id" in the URI, it exactly redirects to the uri passed to redirect:

$this->response->redirect("edit/" . $author->id);

That's odd... what can I be doing wrong to cause this issue?



31.7k
Accepted
answer

Oh, silly me! Please forget this post. I've found the error on my code. Sorry to bother!

Thank you very much for your help. :)



98.9k