Darrin's Tech Ramblings

Zend Form — validate an array of data

Advertisements

Using Zend Framework v 1.12, we can validate an array of data using a subForm.
In this example, we want to validate up to 10 transaction_ids passed in an array.
The validation for each will used Zend_Validate_Db_RecordExists to make sure the transaction_id exists in the database and is for the currently logged in seller_id.


    $form = new Zend_Form();

    // add validations for the 'simple', non Array elements
    $form->addElement( ................. ); 
    $form->addElement( ................. ); 
    $form->addElement( ................. ); 

    // add validations for the 'transaction_id' input field
    // Input: transaction_id[0] = 'value'
    //        transaction_id[1] = 'value'
    //               ...
    //        transaction_id[9] = 'value'
    $this->createTransactionIdSubForm($form, 10);
 
    /**
     * createTransactionIdSubForm creates a form element that handles an array of
     * transaction_ids.  Each will be validated to exist in the database and be
     * valid for our current seller_id.
     *
     * @param  Zend_Form $form
     * @param  integer $nbr_of_ids defines the number of subForm element to build
     */
    public function createTransactionIdSubForm($form, $nbr_of_ids)
    {
        $subForm = new Zend_Form_SubForm();

        // Create a validator for each array element of the transaction_id array
        for($i=0; $i < $nbr_of_ids; $i++) {
            $subForm->addElement('text', (string) $i, array(
                'required'   => false,
                'filters'    => array('Digits'),
                'validators' => array(
                    array('Db_RecordExists', true, array(
                        'transaction',
                        'transaction_id',
                        '(select seller_id 
                          from activity 
                          where activity_id = transaction.activity_id
                         ) = '.$this->getSellerId()
                        ))
            )));
        }
        $form->addSubForm($subForm, 'transaction_id');
    }
Advertisements