2011-08-12 71 views
4

我的表單中有兩個對象,一個是Scene及其Background。大部分頁面是新的Scene的表單,我有一個角落裏有一個縮略圖和一個文件輸入字段。每當文件字段發生變化時,它就會將圖像上傳到服務器,在該服務器上創建並保留一個實體Background。然後它返回實體的Id,我將其存儲在表單的隱藏字段中。Symfony2表單嵌入實體問題

當我提交這個,它告訴我,我試圖存儲一個字符串在Scene#setBackground方法。如果我從SceneType表單類中的background字段中刪除hidden屬性,則會呈現<select>框並且一切正常。我添加hidden屬性,併發布相同的數據,我得到上述錯誤。

SceneType:

class SceneType extends AbstractType { 
    public function getName() { 
     return 'scene'; 
    } 

    public function buildForm (FormBuilder $builder, array $options) { 
     $builder->add('name'); 
     $builder->add('description'); 
     $builder->add('panoramic', null, array('required' => false)); 
     $builder->add('revealable', null, array('required' => false)); 
     $builder->add('left', 'hidden'); 
     $builder->add('right', 'hidden'); 
     $builder->add('background', 'hidden'); 
    } 
} 

Relevant section of Entity\Scene:

class Scene { 
    /** 
    * @ORM\OneToOne(
    *  targetEntity="Company\ProductBundle\Entity\Scene\Background", 
    *  inversedBy="scene" 
    *) 
    * @ORM\JoinColumn(
    *  name="scene_background_id", 
    *  referencedColumnName="id", 
    *  nullable=false, 
    *  onDelete="cascade", 
    *  onUpdate="cascade" 
    *) 
    */ 
    protected $background; 
    public function getBackground() { 
     return $this->background; 
    } 
    public function setBackground (Background $background) { 
     $this->background = $background; 
    } 
} 

Error message:

Catchable Fatal Error: Argument 1 passed to 
Company\ProductBundle\Entity\Scene::setBackground() must be an instance of 
Company\Company\Entity\Scene\Background, string given, called in 
/srv/http/symulator/vendor/symfony/src/Symfony/Component/Form/Util/PropertyPath.php 
on line 346 and defined in 
/srv/http/symulator/src/Noinc/SimulatorBundle/Entity/Scene.php line 143 

回答

2

我在我的形式兩個對象,一個場景和背景。 頁面的大部分是新場景的形式,並且我有一個 角落,其中有縮略圖和文件輸入字段。只要 文件字段發生更改,它就會將映像上載到創建並保留背景實體的服務器。場景然後獲取與該背景關聯的 。現在,隨着背景設置,我只需要 需要擔心通過窗體修改我的場景的屬性。

我不認爲在窗體中傳遞隱藏的id是必要的;你應該能夠在表單之外堅持這種關聯。希望你考慮這種方法。

如果你必須用你的方式,你需要做一個BackgroundType形式,那麼形式添加到場景類型形式:

$builder->add('background', new BackgroundType()); 

我承擔BackgroundType()將呈現一個隱藏的id字段,然後。