In ZF2 how to set a value in a Zend Form Element Text in the view?

Asked

Viewed 420 times

0

The Form:

$this->add(array(
            'name' => 'valor',
            'type' => 'Text',
            'attributes' => array(
                    'required' => true,
                    'class' => 'form-control',
                    'maxlength' => '100'
            ),
            'options' => array(
                          'value' => 10, //Coloquei este valor de propósito
            )
    ));

The view:

$form->get('valor')

print_r() of the value form:

Zend\Form\Element\Text Object ( 
  [attributes:protected] => Array ( 
        [type] => text 
        [name] => valor 
        [required] => 1      
        [class] => form-control [maxlength] => 100 
   ) 
   [label:protected] => [labelAttributes:protected] => Array ()                        
   [labelOptions:protected] => Array ( ) 
   [messages:protected] => Array ( ) 
   [options:protected] => Array ( [value] => 10 ) [value:protected] => 
   ) 

?

1 answer

0


You must set this value in the controller:

$form->setData(['valor' => 'meu valor']);

And despite being a gambiarra, you can use this code above before the $form->prepare in the view.

If you want to set a default value, instead of putting 'value' inside the options, put it inside the attributes:

$this->add(array(
    'name' => 'valor',
    'type' => 'Text',
    'attributes' => array(
        'required' => true,
        'class' => 'form-control',
        'maxlength' => '100',
        'value' => 10
    ),
    'options' => array(
    )
));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.