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 add a custom filter to a form ?

Hi,

I have a custom filtering class following https://docs.phalcon.io/en/latest/reference/filter.html#creating-your-own-filters :

class EmptyToNullFilter {

  public function filter($value) {
    if($value == '') {
      return NULL;
    } else {
      return $value;
    }
  }

}

Which I'd like to add to a form element, but I don't know how to use it, since the Phalcon\Forms\Element->addFilter requires a string :

$field_date = new Date('end_contract_date');
$field_date->addValidator(new DateTimeValidator())->addFilter(new EmptyToNullFilter());

=> Object of class EmptyToNullFilter could not be converted to string

So I tried, referencing it in a new filter, and obviously comes the same error :

$filter = new Phalcon\Filter();
$filter->add('empty', new EmptyToNullFilter());
$field_date->addValidator(new DateTimeValidator())->addFilter($filter);

Last try :

$filter = new Phalcon\Filter();
$filter->add('empty', new EmptyToNullFilter());
$field_date->addValidator(new DateTimeValidator())->addFilter('empty');

=> 'Sanitize filter 'empty' is not supported'

Which seems legit since the filter has been added to an instance of Phalcon\Filter and the form probably creates its own new instance, unrelated to the previous one.

I feel I missed something here, how could I add such a filter to a form ?

edited Dec '15

I might have the begining of an answer by watching this https://github.com/phalcon/cphalcon/blob/master/phalcon/validation.zep#L428

It would be about to specify a filter service in the DI, which is the one where my EmptyToNullFilter is to be added, isn't it ?



5.7k
Accepted
answer
edited Dec '15

Here is the way to register it :

$di->setShared('filter', function() {

  $filter = new \Phalcon\Filter();

  $filter->add('emptytonull', function ($value) {
    if($value === '') {
      return NULL;
    } else {
      return $value;
    }
  });

  return $filter;

});

Then, like the core ones, it can be added to the form :

$field_date->addFilter('emptytonull')->addValidator(new DateTimeValidator());

( self-accepted answer ;) )