adamst85 adamst85 - 7 months ago 26
PHP Question

Zend 2 Form Validator 'InArray' - Complicated array returning invalid

I am trying to implement the 'InArray' validator in Zend 2 on a form and it keeps on returning invalid. Here is the code:

The Form Element setup:

$enquiryType = new Element\Select('enquiryType');
$enquiryType->setLabel('* What is your enquiry about?')
->setLabelAttributes(array('class' => 'sq-form-question-title'))
->setAttribute('class', 'sq-form-field required')
->setValueOptions($enquiryTypes);


The Filter/Validator setup:

$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => $enquiryTypes));


And here is the array that gets passed into $enquiryTypes via the module.config.php file

'enquiryCategories' => array(
'empty_option' => 'Please select an option',
array(
'label' => 'General enquiries',
'options' => array(
'skype' => 'Skype with your library feedback',
'question' => 'Ask a question',
'feedback' => 'Library feedback',
'eresource' => 'Electronic resources (e.g. e-book, e-journal, database)',
'webbridge' => 'WebBridge Problems',
'dro' => 'DRO'
)
),
array(
'label' => 'Application to review',
'options' => array(
'10400' => 'I\'ve returned the item',
'10401' => 'I didn\'t know about overdue points but now I have some',
'10402' => 'Why did I get this invoice?',
'10403' => 'The item I borrowed is lost',
'10404' => 'The item I borrowed has been damaged',
'10405' => 'I never got/had the book',
'10406' => 'Other'
)
)
),


I have tried different variations of this (using the recursive validation also) but have not been able to work this out.

Answer

I finally got a working solution for this. I feel there should be a better solution but I could not find one.

Here is the filter I used:

$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
        ->addByName('InArray', array('haystack' => array_keys(
                                    $enquiryTypes[0]['options']+$enquiryTypes[1]['options']
                                )));
$enquiryType->getFilterChain()
         ->attach(new Filter\StringToLower())
         ->attachByName('StripTags');

Basically I had to disect the array options into a straight associative array. As the array remains static in this instance then this works well.

If the data becomes dynamic then something more would be required (loop through and find the 'option' key, add children to filter array etc...)

Comments