1

I have text box in which your adds values in comma separated values. Once the form is post I want to check each of CSV value against database table that if each one of them exist already. If so then I want to throw error message otherwise that is fine.

How can I implement this?

Rajan Rawal
  • 6,171
  • 6
  • 40
  • 62

2 Answers2

4

What you need is a custom validator. you can either do it extending Zend_Validate_Abstract or you can simply use a callback validator.

To do so, you need to add this to your element:

$elem = new Zend_Form_Element_Text('elem_name');
$elem->setLabel('Label Name:')
         ->setRequired(true)
         ->addValidator('callback', true, array('callback' => array($this, 'functionName')));
$this->addElement($elem);

And in the same class (usually your form is in a class that extends Zend_Form), you add this method:

public function functionName($csvString) {
    // stuff here using explode(',', $csvString)
    // foreach() to iterate over the result and match against the db each $value
}

See explode() for more information.

However, if your form element is going to be called more than once, and in different forms, then I don't recommend you to use a callback, but you'd better write your own validator, the theory remains the same though. Take a look here for more information about how to write validators.

Liyali
  • 5,643
  • 2
  • 26
  • 40
  • Your answer is perfect but in my case I need to extract all invalid comma separated values and show all these values as in error as below text area element. So by the method you suggested i can return only true or false for callback validator but can not collect invalid values. So what i did finally is once validating form using $form->isValid($_POST) I explode values and check separately of they are in database I collect then all and generate error msg using $element->addError($invalid_csv.' are invalid'); – Rajan Rawal Apr 03 '12 at 08:56
2

I really doubt that this can be achieved directly just using Zend_Validate_Db_RecordExists. I think the best solution would be to create a custom validator for this purpose. Something that would take your value then explode it based on a , $valueArray = explode(',', $value); and then for each $valueArray check if the element exists in the db. This shouldn't be too hard. If you dont have idea about custom validators this might be helpful.

ro ko
  • 2,906
  • 3
  • 37
  • 58