adamst85 adamst85 - 1 year ago 63
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')

The Filter/Validator setup:

$enquiryType = new Input('enquiryType');
->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',
'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'
'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 Source

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');
        ->addByName('InArray', array('haystack' => array_keys(
         ->attach(new Filter\StringToLower())

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...)