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

Custom filter in request

Hi I'm using Phalcon 3.4. I created a custom filter class and added it in the bootstrap.

use Phalcon\Filter;

$di->setShared('filter', function() {
    $filter = new Filter();

    $filter->add('nullFilter', new NullFilter());

    return $filter;
});

i want to use my filter in requests added as a default, overriding Phalcon\HttpRequest::getPost and similar functions.

public function getPost($name = null, $filters = null, $defaultValue = null, $notAllowEmpty = false, $noRecursive = false)
    {
        if ($filters === null)
            $filters = [];
        elseif (!is_array($filters))
            $filters = [$filters];

        $filters[] = 'nullFilter';

        return parent::getPost($name, $filters, $defaultValue, $notAllowEmpty, $noRecursive);
    }

But it doesn't work, I don't know how to add custom filter to be usable in request. Any advice?

What's your end goal? Are you wanting to do something like this:

$posted_value = $this->request->getPost('field_name','nullFilter')

?

Also fyi, if you add the language name after the three backticks for a code block, you'll get syntax highlighting. I've updated your initial post.



3.1k
edited Aug '20

What's your end goal? Are you wanting to do something like this:

$posted_value = $this->request->getPost('field_name','nullFilter')

?

Also fyi, if you add the language name after the three backticks for a code block, you'll get syntax highlighting. I've updated your initial post.

My end goal is to use the filter without the need to write it explicitly. Having the same effect as your example $posted_value = $this->request->getPost('field_name','nullFilter') by writing only $posted_value = $this->request->getPost('field_name')

Ah, gotcha. I guess in hindsight your goal was pretty obvious.

Everything looks to be in order. My only guess is maybe you're not overriding the right service?

What happens if you put an exit() in the bootstrap function? Just to verify that is indeed the service?