Search code examples
phpzend-frameworkzend-formzend-validate

Zend Validation Db_NoRecordExists and exclude option


I'm trying to use the "exclude" option for a Db_NoRecordExists validator, cause when I'm "editing" the element it always return me back a "duplicated" error, as usual.

What I aim to is to tell to the form to keep back the value passed to the form itself from the Controller...

This is the Controller:

public function editAction()
{
$id = $this->getRequest()->getParam('id');
$pagesMapper = new Application_Model_PagesMapper();
$form = new Application_Form_PageEdit();
$form->populate($pagesMapper->fetchId($id, true));
if ($this->getRequest()->isPost()) {
    if ($form->isValid($this->getRequest()->getPost())) {
        //... cut ...
    }
}
$this->view->form = $form;
}

This is the Form:

class Application_Form_PageEdit extends Zend_Form
{
public function init()
{
$commonFilters      = array('StringTrim');
$commonValidators = array('NotEmpty');
    $this->setMethod('post')->setAction('/admin-page/edit');

$id = new Zend_Form_Element_Hidden('id');
$pid = new Zend_Form_Element_Hidden('pid');

$keyname = new Zend_Form_Element_Text('keyname');
$keyname->setLabel('Keyname')
    ->setRequired(true)
    ->addFilters($commonFilters)
    ->addFilter('StringToLower')
    ->addFilter('Word_SeparatorToDash')
    ->addValidator('Db_NoRecordExists', false, array(
        'table'     => 'pages',
        'field'     => 'keyname',
        'exclude'   => array(
            'field' => 'id',
            'value' => $this->getValue('id)
        )
        )
    );

//... cut ...

Some advices?


Solution

  • I had a similar problem. My solution was to move the validator from the init to the isValid function.

    public function isValid($data)
    {
      $this->getElement('keyname')
           ->addValidator(
               'Db_NoRecordExists',
               false,
               array(
                   'table'     => 'pages',
                   'field'     => 'keyname',
                   'exclude'   => array(
                       'field' => 'id',
                       'value' => $this->getValue('id')
                   )
               )
           );
      return parent::isValid($data);
    }