0

我正在构建一个 API,用户可以在其中更新包含集合的实体。如果我自始至终都使用表单,这很好用,但我正在构建 API。我的实体如下所示:

<?php
class MyEntity {
    // ...

    /**
     * @ORM\OneToMany(targetEntity="TitleEntity", mappedBy="entityID", cascade={"persist"})
     */
    protected $myTitles;

    public function getMyTitles() {
        return $this->myTitles;
    }

    public function setMyTitles($titles) {
       foreach($titles as $key => $obj) { $obj->setEntity($this); }
       $this->myTitles = $collection;
    }

    public function addMyTitle($obj) {
        $obj->setEntity($this);
        $this->myTitles[] = $obj;
    }

    public function removeMyTitle($obj) {
        $this->myTitle->removeElement($obj);
    }
}

是一个实体,它有一个 ID、它所附加到的myTitles实体的 ID,然后是一个标题。

对于 API,我将 JSON 内容主体作为对 MyEntity 对象的 PUT 请求传回,因此我最终得到了一个标题数组,并且我正在准备将它们绑定到表单以进行验证:

$myTitles = array();
foreach($titles as $key => $title) {
    $titleObj = new TitleEntity();
    $titleObj->setTitle($title);
}
$myEntity->setTitles($titles);

但它抱怨:

The form's view data is expected to be of type scalar, array or an instance of
\ArrayAccess, but is an instance of class stdClass. You can avoid this error by 
setting the &quot;data_class&quot; option to "stdClass" or by adding a view 
transformer that transforms an instance of class stdClass to scalar, array or 
an instance of \ArrayAccess

看起来这是因为我getMyTitles()在将实体绑定到我用来验证的表单之前调用。

我正在使用数组绑定到表单:

$form = $this->createForm(new AddEntity(), $myEntity);
$data = array( // Set all my data );
$form->bind($data);
if($form->isValid() {
// ...

如果我createForm()先打电话,然后添加标题,我会得到:

Call to a member function removeElement() on a non-object

这发生在里面removeMyTitle()

我该如何处理?

编辑

这是AddEntity()类型:

<?php
class AddEntity extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('title', 'text')
        ->add('subheading', 'text')
        ->add('description', 'textarea')
        ->add('myTitles', 'collection', array(
            'type' => new AddMyTitles(), // Basic type to allow setting the title for myTitle entities
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'by_reference' => false,
            'options' => array(
                'required' => false,
            ),
        ));
}

public function getName()
{
    return 'addEntity';
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'My\TestBundle\Entity\Entity',
    ));
}
4

1 回答 1

0

这里需要数据转换器。

http://symfony.com/doc/2.0/cookbook/form/data_transformers.html

基本上,您已经告诉表单它正在获取一个数组,并且您已经给了它其他东西。变压器应该处理这个问题。

如果您需要更多帮助,我需要更多信息。

此外,有点令人费解的是,您在散文中引用了“myCollections”,但在代码中没有显示它。^^^^^^^^^ 由编辑修复。

于 2013-02-22T23:28:41.163 回答