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?
Your code should already do that, the
setRequired(false)method do what you’re asking for, i.e. if the value is not submitted then validators won’t be run.Do you have any issue with the code you’ve written, some validation error messages or something else?
Update
What is the semantic in
setRequired(true)and allowing the empty string as a valid value? Or better what do you require if the element can be empty?What you’ve asked in the edit is a no sense, because if an element is required it MUST have a value different from the empty string. If you need to accept the empty string as a valid value just use
setRequired(false). When you get form values withZend_Form::getValues()orZend_Form_Element::getValue()you’ll obtain the empty string as result.Anyway here it’s the explanation of
setRequiredandsetAllowEmptyfrom ZF manual: