浏览代码

[Form] Automatically setting "data_class" option if objects are passed at the creation of a form

    $form = $this->get('form.factory')->create(new PostType(), $post);
Bernhard Schussek 14 年之前
父节点
当前提交
e790587dc2
共有 1 个文件被更改,包括 9 次插入2 次删除
  1. 9 2
      src/Symfony/Component/Form/Extension/Core/Type/FieldType.php

+ 9 - 2
src/Symfony/Component/Form/Extension/Core/Type/FieldType.php

@@ -101,8 +101,15 @@ class FieldType extends AbstractType
             'label' => null,
         );
 
-        if (!empty($options['data_class'])) {
-            $class = $options['data_class'];
+        $class = isset($options['data_class']) ? $options['data_class'] : null;
+
+        // If no data class is set explicitely and an object is passed as data,
+        // use the class of that object as data class
+        if (!$class && isset($options['data']) && is_object($options['data'])) {
+            $defaultOptions['data_class'] = $class = get_class($options['data']);
+        }
+
+        if ($class) {
             $defaultOptions['empty_data'] = function () use ($class) {
                 return new $class();
             };