Best approach on excluding fields from a validator

2019-07-19 00:36发布

I create my forms via extending Zend_Form. And I use one Form for addAction() and editAction(). When I want to remove Elements within the editing process I can do so easily via $form->removeElement('x').

But what would be the best approach on removing a field from the validator?

1) Removing and Adding the newly set validator

//Controllers editAction()
$form->removeValidator('Db_NoRecordExists');
$form->addValidator('Db_NoRecordExists', true, array(
  'table'=>'table', 
  'field'=>'field',
  'exclude'=>array(
    'field'=>'id',
    'value'=>$this->_getParam('id')
  )
));

2) Injecting editing ID into the Form

//Forms Contstructor
public function __construct($idToEdit=0, $options=null)
{
   $this->setIdToEdit($idToEdit);
   parent::__construct($options);
}

//within init()
$formField->addValidator('Db_NoRecordExists', true, array(
  'table'=>'table', 
  'field'=>'field',
  'exclude'=>array(
    'field'=>'id',
    'value'=>$this->getIdToEdit()
  )
));

//Controller calling the form like this:
$form = new Custom_Form($this->_getParam('id'), $options);

3) Something else? Maybe there is even something else I am missing, to me though somehow both ideas don't look too well to me.

1条回答
forever°为你锁心
2楼-- · 2019-07-19 01:07

For a cleaner use of SO here the answer as a post

//SOLUTION Okay, so while browsing to Zends Sourcecode (should have done that before asking...) i found the best solution (i guess). The Abstract DB Validation classes got a function setExclude() so we can then use it in a nice flow:

//Inside Controller before valling $form->isValid()
$form->getElement('x')->getValidator('Db_NoRecordExists')->setExclude(array(
  'field'=>'some_id',
  'value'=>$idToEdit
))
查看更多
登录 后发表回答