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 use custom filters inside model

Hi,

I created a custom filter inside my bootstrap:

use Phalcon\Filter;

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

    $filter->add('commatodot', function ($value) {
        return preg_replace('/\./', ',', $value); 
    });

    return $filter;
});

I'm trying to access it through the static function getDefault():

$test = Di::getDefault()->getService('filter');

But hot can I use my specific filter?



77.7k
Accepted
answer
edited Jul '16

https://docs.phalcon.io/en/latest/reference/filter.html#creating-your-own-filters

https://docs.phalcon.io/en/latest/reference/models.html#validating-data-integrity

class SomeModel extends \Phalcon\Mvc\Model
{
    protected $column;
    public function setColumn($value)
    {
        $value = $this->getDI()->getShared('filter')->sanitize($value, 'commatodot');
        $this->column = $value;
        return $this;
    }
}


3.1k

I did something very similar, created a custom filter class and use it in the bootstrap.

use Phalcon\Filter;

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

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

    return $filter;
});

But i want to use my filter 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); // TODO: Change the autogenerated stub
    }

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