@@ -230,7 +230,7 @@ of the ``$product`` object. This all happens via the ``bindRequest()`` method.
230
230
$product = new Product();
231
231
$product->name = 'Test product';
232
232
233
- $product->bindRequest($this->get('request'));
233
+ $product->bindRequest($this->get('request'), $product );
234
234
echo $product->name;
235
235
236
236
The above statement will echo ``Foo ``, because ``bindRequest `` ultimately
@@ -619,13 +619,6 @@ that will house the logic for building the product form:
619
619
$builder->add('name');
620
620
$builder->add('price', 'money', array('currency' => 'USD'));
621
621
}
622
-
623
- public function getDefaultOptions(array $options)
624
- {
625
- return array(
626
- 'data_class' => 'Acme\StoreBundle\Entity\Product',
627
- );
628
- }
629
622
}
630
623
631
624
This new class contains all the directions needed to create the product form.
@@ -640,11 +633,35 @@ It can be used to quickly build a form object in the controller:
640
633
641
634
public function indexAction()
642
635
{
643
- $form = $this->get('form.factory')->create(new ProductType());
636
+ $product = // ...
637
+ $form = $this->get('form.factory')->create(new ProductType(), $product);
644
638
645
639
// ...
646
640
}
647
641
642
+ .. note ::
643
+ You can also set the data on the form via the ``setData() `` method:
644
+
645
+ .. code-block :: php
646
+
647
+ $form = $this->get('form.factory')->create(new ProductType());
648
+ $form->setData($product);
649
+
650
+ If you use the ``setData `` method - and want to take advantage of field
651
+ type guessing, be sure to add the following to your form class:
652
+
653
+ .. code-block :: php
654
+
655
+ public function getDefaultOptions(array $options)
656
+ {
657
+ return array(
658
+ 'data_class' => 'Acme\StoreBundle\Entity\Product',
659
+ );
660
+ }
661
+
662
+ This is necessary because the object is passed to the form after field
663
+ type guessing.
664
+
648
665
Placing the form logic into its own class means that the form can be easily
649
666
reused elsewhere in your project. This is the best way to create forms, but
650
667
the choice is ultimately up to you.
@@ -672,6 +689,13 @@ when the form is valid:
672
689
return $this->redirect($this->generateUrl('store_product_success'));
673
690
}
674
691
692
+ If, for some reason, you don't have access to your original ``$product ``
693
+ object, you can fetch it from the form:
694
+
695
+ .. code-block :: php
696
+
697
+ $product = $form->getData();
698
+
675
699
For more information, see the :doc: `Doctrine ORM chapter</book/doctrine/orm> `.
676
700
677
701
The key thing to understand is that when the form is bound, the submitted
0 commit comments