3

In ZF1 it was possible to mark the form invalid using the code:

$form->fieldname->addError('error message');

How can I do it in ZF2? I tried

$form->get('elementName')->setMessages(array('error message'));

but it doesn't make the form invalid.

Alexey Kosov
  • 3,010
  • 2
  • 23
  • 32
  • I think this will be of great help for you http://stackoverflow.com/questions/13476164/zend-framework-2-custom-validators-for-forms also this link http://www.ivangospodinow.com/simple-form-validator-for-zend-framework-2-forms/ – Programmer man Oct 06 '14 at 13:59
  • not sure.. but I think there is $form->setValid(bool); – peterpeterson Oct 06 '14 at 15:06
  • @peterpeterson The Form class doesn't have "setValid" method. Where did you get it? – Alexey Kosov Jul 17 '15 at 12:12
  • just trying to guess as all method in ZF2 that are things like is....() they usually have the set....() method. but it doesn't seem to in this case – peterpeterson Jul 19 '15 at 06:58

1 Answers1

1

I wonder the same question and I dont know how to do it easy too with default Zend 2 forms.

I have no idea why it was necessary to hide manual form state manipulating and break obvious addError functionality too.

But may be it's appropriate to you to use proxy-way like this:

  1. Create own form basic class (may be write it better later):

    class BasicForm extends Form
    {
        protected _isValid = null;
    
        public function isValid()
        {
            return isset($this->_isValid) ? $this->_isValid : parent::isValid();
        }
    
        public function setValid($value)
        {
            $this->_isValid = isset($value) ? (bool)$value : null;
            return $this;
        }
    
    }
    
  2. Instantiate your real forms from this custom form class intead of default Zend Form class:

    class SomeYourForm extends BasicForm
    ...
    

So you will be able to set this form valid state to true or false by overlaying of this property.

May be it helps for someone too.

FlameStorm
  • 944
  • 15
  • 20