Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

how to add a custom filter to a form ?

Hi,

I have a custom filtering class following https://docs.phalconphp.com/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 ?



1.5k
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 ;) )