Zend framework – how to allow empty field for form element

zend-formzend-framework

I'm using this construction for my element:

$freetext = $this->CreateElement('textarea', 'freetext')
            ->setLabel('Comments')
            ->setAttrib('class','input-textarea')
            ->setOptions(array('rows' => '2', 'cols'=>'30'))
            ->addValidator('StringLength', false, array(0,500))
            ->addFilter('HtmlEntities')
            ->addFilter('StripTags')
            ->setRequired(true);

I want to add an "allowEmpty" to this but can't find the correct syntax. I was hoping for something like:

...    ->addValidator('allowEmpty', false, true)

But this does not work.

Edit: I've changed the setRequired() to true – I want to allow empty string as an acceptable value on a require field.

Regardless of usage, how do I add this option to my element?

Best Answer

->setRequired(false);

this is enough if you want to allow an empty string and save an empty string to database.

if you want the field to be optional and keep null value in database if nothing is given, add:

->addFilter(new Zend_Filter_Null)
Related Topic