Search code examples
phpzend-frameworkfilterzend-framework3zend-inputfilter

Register custom Filter via Factory


I am trying to register my custom filter and use in getInputFilter() method, but constantly getting the error:

A plugin by the name "myCustomFilter" was not found in the plugin manager ZendFilterFilterPluginManager

$inputFilter = new \Zend\InputFilter\InputFilter;
$inputFilter->add([
    'name'       => 'inputname',
    'required'   => true,
    'filters'    => [
        [
            'name' => 'myCustomFilter'
        ]
    ],
]);

And register it in module.config.php

return [
    'filters' => [
        'aliases'   => [
            'myCustomFilter' => Test\Filter\MyCustomFilter::class,
        ],
        'factories' => [
            Test\Filter\MyCustomFilter::class => Test\Filter\MyCustomFilterFactory::class,
        ],
    ],
];

Also in application.config.php I registered

'modules' => [
    ...
    'Zend\Filter',
    'Zend\InputFilter',
    'Zend\Validator',
 ],

Note that I am using ZF3, so is there anything else to setup/configure?

I can use the filter without the factory but create filter via factory is required.


Solution

  • After creating an instance of InputFilter we need to update the default FilterManager

    $inputFilter->getFactory()->getDefaultFilterChain()->setPluginManager(
        $container->getServiceLocator()->get('FilterManager')
    );
    

    Of course it's better to inject "FilterManager" this is only a test code.