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

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

A view:

$form->get('valor')

print_r () of the form value:

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] => 
   ) 

?

    
asked by anonymous 29.04.2014 / 15:31

1 answer

0

You should set this value in the controller:

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

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

In case you want to set a default value, instead of putting 'value' inside the options, put within the attributes:

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