Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
MiPnamic Avatar asked Mar 21 '11 14:03

MiPnamic


1 Answers

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);
}
like image 189
Richard Parnaby-King Avatar answered Sep 30 '22 12:09

Richard Parnaby-King