Reputation: 1648
I'm creating a custom form using Symfony2. I created the "first part" of the form using Symfony as the following code:
class TelemedidaMecanicaLecturaType extends AbstractType{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('fecha')
->add('valor')
;
}
}
Then, in the Twig template I need to add three extra fields: the submit button and two hidden inputs that I need to get some important information. I tried to do that:
<form method="post" id="FormLec{{um.id}}">
{{ form_widget(formLecArr[um.um]) }}
<input type="hidden" name="um" value="{{um.id}}"/>
<input type="hidden" name="telemedidaMecanica" value="{{telemedidaMecanica.id}}"/>
<input type="submit" value="Crear"/>
</form>
But when I send the form, and I try to get data from the controller, I only get "fecha" and "valor" values. It is strange, because missing fields are displayed in the HTML text (using inspect code utility in chrome) and the submit button works correctly. Where is the "um" and "telemedidaMecanica" values? What I am doing wrong?
Thank you! Isaac.
Upvotes: 0
Views: 1717
Reputation: 1919
What you need to do is pass all form fields to the FormType when you are creating the form. The submit button only posts the values which were generated from the Formbuilder.
You can do something like this:
class TelemedidaMecanicaLecturaType extends AbstractType{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('fecha')
->add('valor')
->add('um','hidden')
->add('telemedidaMecanica','hidden')
;
}
}
Alternatively, if you don't have access to these variables in your Entity itself, you can pass the values when you instantiate your FormBuilder from your Controller itself.
Something like this in your controller would work:
$form = $this->createForm(new TelemedidaMecanicaLecturaType($um, $telemedidaMecanica);
and then in your FormBuilder you can take advantage of data property of the form. Do this:
class TelemedidaMecanicaLecturaType extends AbstractType{
private $um;
private $telemedidaMecanica;
public function __construct($um, $telemedidaMecanica)
{
$this->um= $um;
$this->telemedidaMecanica= $telemedidaMecanica;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('fecha')
->add('valor')
->add('um','hidden', array('data' => $this->um, 'mapped' => false))
->add('telemedidaMecanica','hidden', array('data' => $this->telemedidaMecanica, 'mapped' => false))
;
}
}
This will post hidden values too when you click Submit.
Upvotes: 1