Zend-framework-Accessing other form fields in zf2 filter

99 Views Asked by At

I have a problem in Zend-Framework2 where I need to read/write the value of a different field in one field's filter.

I have a form which gets the address data from a user: street, number, numberAddition, zipcode, city.

I need to separate number and numberAddition, because I have some strict constraints when I further process this data. Number has to be numeric (int) and numberAddition can be a string.

Example user input:
number: 47a
numberAddition: [empty]

Should be filtered to:
number: 47
numberAddition: a

I'd like to implement this as a filter: if numberAddition is empty and number is not int then split number into number and numberAddition.

Is there a way to do this with filters or is there a better approach?

1

There are 1 best solutions below

2
On

That is not a proper solution

In both the FilterInterface and the ValidatorInterface we can not see any $context variable passed in, so the solution below does not guarantee any forward compatibility (basically someone can remove the $context and your code won't work anymore, no need to wait a major version to do that as it already isn't part of the interfaces).

In your code, you can still use the $context as now you know what you are doing ;p

So basically :

class MyFilter implements \Zend\Filter\FilterInterface
{ 
    public function filter($value, array $context = null)
    {
        if ($array && isset($context['fieldName'])) {
            // do whatever
        }
        return $valueFiltered;
    }
}