phalconphalcon-routing

How to append a GET parameter to all urls using Phalcon


Given a page retrieved at for example:

http://myapp.dev/path/subfolder?param=abc

Whenever the additional GET parameter called param is present it should be added automatically to all subsequent links in my navigation as constructed in the .volt template. For example:

<a href="{{ url('path/subfolder2') }}">Go to subfolder 2</a>

I.e. based on this .volt link the the goal is to generate:

<a href="http://myapp.dev/path/subfolder2?param=abc">Go to subfolder 2</a>

Solution

  • If you want to append Query string parameters only for given links you can go with Luke's solution. However I think you want to achieve something a bit different and it involves custom logic. For this to happen we should create a custom Volt function.

    Custom function definition:

    public static function urlFor($params, $queryStringParams = [])
    {
        $di = \Phalcon\DI::getDefault();
        if ($di->getRequest()->has('param')) {
            $queryStringParams['param'] = $di->getRequest()->get('param');
        }
        return $di->getUrl()->get($params, $queryStringParams);
    }
    

    The above function acts the same as url() function in Phalcon, it just allows us to write a bit of custom logic before passing the parameters to url(). In your case we check if URL contains desired query param and we add it to every URL generated on the current request. In my case the above function is in Helper file so I can use it anywhere I need to.

    This is our View service definition:

    $di->set('view', function() use ($di) {
        $view = new \Phalcon\Mvc\View();
        ...
        $view->registerEngines([
            '.phtml' => function($view, $di) {
                $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
                $options = [
                    'compiledPath' => $di->getConfig()->site->path->cache . 'volt/frontend/',
                    'compiledExtension' => '.php',
                    'compileAlways' => $di->getConfig()->debug,
                ];
                $volt->setOptions($options);
    
                ...
                
                // IMPORTANT PART: Overwriting default url() function in Volt
                $compiler = $volt->getCompiler();
                $compiler->addFunction('url', function($resolvedArgs, $exprArgs){
                    return 'Helpers\Common::urlFor(' . $resolvedArgs . ')';
                });
                return $volt;
            }
        ]);
        return $view;
    });
    

    Please note the IMPORTANT PART comment in the above code block.

    Let us finish with example:

    User is on this address: http://myapp.dev/path/subfolder?param=abc

    But somewhere in your code you want to generate a link to News page:

    <a href="{{ url('news/list') }}">News</a>
    

    Our code will catch the param in the URL and will generate the following address:

    http://myapp.dev/news/list?param=abc