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

How to get uri parameter from index controller [SOLVED]

Hello, I have a group class which is receiving a parameter in the uri but I don't know how to get to it.

This is my url: https://local.myapp.com/group/6

Thanks!



419
Accepted
answer
edited Oct '14

The default behavior for routing in Phalcon is: /{controller}/{action}/{parameters} For the example you want, you should have a GroupControll.php with an indexAction that receives the "6" as the action parameter. To do this, without having to set the request as "/group/index/6" to respect the default route, you have to create a new route so that you can keep the uri the way you want.

You can create a new route like this:

public/index.php

    //Set routes
    $di->set('router', function(){
        $router = new \Phalcon\Mvc\Router();
        $router->add(
                '/{controller}/{id:\d+}',
            array(
                "action"         => "index",
            )
        );

        return $router;
    });

and in you GroupController.php:

class GroupController extends \Phalcon\Mvc\Controller
{

    public function indexAction($id=null){
       $this->view->disable();
       echo "Group Controller; IndexAction; ID $id";
    }
}


18.9k

Thanks Vasco, it worked perfectly :D



18.9k

One more related question please... I'm trying to make it accept numbers and text but I get errors for everything I tried. This is the code:

         $router->add(
                //'/{controller}/{id:\d+}',
                '/{controller}/{id:\([a-z\-]+)}',
            array(
                "action" => "index",
            )
        );

How should it be? Thanks.

You can improve the regular expression to allow letters and numbers like this:

        //Define a route
        $router->add(
                '/{controller}/{id:[a-zA-Z0-9]+}',
            array(
               "action"         => "index",
            )
        );

or if you want to allow everything as the parameter, you also can simple do this:

        //Define a route
        $router->add(
                '/{controller}/{id}',
            array(
               "action"         => "index",
            )
        );


18.9k

Vasco, thanks again! :D