Zend_Filter_Null
- Posted by thomasw at 11:16:41 // //
- Filter
Today I added a new component to Zend Framework which will be available as with release 1.10.
Zend_Filter_Null is a filter which converts special input to null.
Now you may ask, what should this filter do ? I could also unset() the variable.
Well… one reason is database awareness… a second one may be user input.
Let’s see an example, so you understand what I mean:
$filter = new Zend_Filter_Null();
$filter->filter('2'); // returns 2
$filter->filter('0'); // returns null
Now what’s the intention…
Let’s say you have a selectbox with different values.
When someone does not select anything you will get a ‘0′ returned because the selectbox always returns anything. In your database you don’t want to store integer ‘0′ but have a NULL instead to mark that there has not been selected anything.
Before, you had to code an if clause and then store the content different so you had no integer ‘0′ in your database.
Now you can simply attach this filter and get a NULL in return.
Another case could be a textbox… when the user does not enter a text you will get an empty string returned. Attaching Zend_Filter_Null to your textbox you will get NULL instead of an empty string.
Zend_Filter_Null works per default like php’s empty(). This means that when the input is a integer 0, an empty string, an string ‘0′, an empty array or a boolean false, then you will get a NULL from this filter.
Any other input will be returned as is, without changes.
But you can configure the convertion algorithm to return defined types as is.
$filter = new Zend_Filter_Null(Zend_Filter_Null::INTEGER);
$filter->filter('0'); // returns '0' because a string 0 was given
$filter->filter(0); // returns NULLi
This will only detect integer ‘0′ values and return NULL in the case they are given. All other cases (boolean false, empty string and so on), are returned as is, without filtering them.
For more details look into the manual.
Of course it is more convinient to attach the filter directly to the form element.
$element = new Zend_Form_Element_Text('MyText');
$element->addFilter('Null');
But these details you should already know ;-)
When you have a question dont be shy to ask.
More to come from me soon…
Have a good work with Zend Framework.
Greetings
Thomas Weidner
I18N Team Leader, Zend Framework
Zend Framework Advisory Board Member
Zend Certified Engineer for Zend Framework
