0

One of my forms has some required fields and some not, lets say 'name' is required but 'note' is not:

class Form_CompanyForm extends Zend_Form{
public function init(){
    // add element: ID textbox
    $ID = $this->createElement('hidden', 'id');
    $this->addElement($ID);

    // add element: name textbox
    $name = $this->createElement('text', 'name');
    $name->setLabel('name:');
    **$name->setRequired(TRUE);**
    $name->setAttrib('size',100);
    $name->setAttrib('maxlength',255);
    $name->addFilters(array(new Zend_Filter_StringTrim()));
    $this->addElement($name);

        // add element: note text area
    $note = $this->createElement('textarea', 'note');
    $note->setLabel('note:');
    **$note->setRequired(FALSE);**
    $note->setAttrib('cols',50);
    $note->setAttrib('rows',4);
    $note->addFilters(array(new Zend_Filter_StringTrim()));     
    $this->addElement($note);       

...

One of my controllers calls this form and uses all its fields. This is working fine and the validation of the name field takes place.

BUT... another controller uses the same form, only to change the note... For this I use removeElement() to remove the name from the form:

public function editcompanynoteAction(){
    $mod = new Model_Company();
    $frm = new Form_CompanyForm();
    $frm->removeElement('name');        
    $frm->setAction('/companyland/editcompany');
    $frm->setMethod('post');
    if($this->getRequest()->isPost()){
        if($frm->isValid($_POST)){

...

The form displays properly, only the note field is present, as expected

BUT upon saving the form, the validation fails because the 'name' field is required...

I am new to Zend, I do not understand why a form validation would fail... on an element that was... removed.

There are examples on the web about using removeElement... I tried clearValidators() without success and looked at Zend form validation

The comment says "You should remove the validator BEFORE calling $form->isValid()."

But how?

Any help you could give me will be much appreciated.

Community
  • 1
  • 1
  • There is a bug int the code above, the controller to call should have been '/companyland/editcompanynote' instead of '/companyland/editcompany' this is why I ran into this issue, once corrected the right action was called in the controller and I did not get this issue anymore. – Philippe Huart May 10 '12 at 18:16

1 Answers1

0

Put this line

$frm->getElement('name')->setRequired(false);

before

$frm->removeElement('name');  
Mr Coder
  • 8,169
  • 5
  • 45
  • 74
  • Hi, there was another bug (see comment above), once corrected, I no longer ran into this issue. Thanks for the quick answer! – Philippe Huart May 10 '12 at 18:17