nesta_bg
nesta_bg

Reputation: 141

Zend Form Element Select - how to return integer?

Is there any way to configure Zend\Form\Element\Select to return integer? If I have a Form with a Select Element something like this (this is the common way to configure Select Element according to documentation and my internet research):

$this->add(array(
        'name' => 'category_id',
        'type' => 'Zend\Form\Element\Select',
        'options' => array(
            'label' => 'Category',
            'value_options' => array(
                '1' => 'Gold',
                '2' => 'Silver',
                '3' => 'Diamond',
                '4' => 'Charm'    
        ),
        'attributes' => array(
            'class' => 'form-control',
        ),
    ));       

I thought If I change value option like this:

$this->add(array(
        'name' => 'category_id',
        'type' => 'Zend\Form\Element\Select',
        'options' => array(
            'label' => 'Category',
            'value_options' => array(
                1 => 'Gold',
                2 => 'Silver',
                3 => 'Diamond',
                4 => 'Charm'     
        ),
        'attributes' => array(
            'class' => 'form-control',
        ),
    ));  

the integer will be returned but I was wrong. In both cases string is returned. My php code write this form values to a db table where category_id is defined as int.

Upvotes: 0

Views: 347

Answers (1)

Garry
Garry

Reputation: 1485

In ZF2 use the Zend\Filter\Int or Zend\Filter\ToInt depending on which version of ZF2 you are using, Zend\Filter\Int became deprecated in ZF2.4.

In your form, assuming you are using the Zend\InputFilter\InputFilterProviderInterface use:

public function getInputFilterSpecification()
{
    return array(
        'category_id' => array(
            'required' => TRUE,
            'filters' => array(
                array('name' => 'Int'),
            ),
            'validators' => array(
                // Your validators here
            ),
        ),
    );
}

Upvotes: 1

Related Questions