【发布时间】:2014-08-05 09:00:07
【问题描述】:
有没有人在使用学说嵌入和 symfony 表单时遇到过这个问题?
如果你不知道 Doctrine Embeddables 是什么,你可以在这里阅读 http://doctrine-orm.readthedocs.org/en/latest/tutorials/embeddables.html
当在表单提交中使用带有 symfony 表单的值对象(在我的例子中为 CategoryType)时(在持久化到 DB 期间),我收到以下警告
警告:ReflectionProperty::getValue() 期望参数 1 是对象,给定字符串
这是因为 symfony 表单返回字符串而不是可嵌入对象。
我现在唯一的解决方法是在 type 字段上使用 mapped => false 并在持久化之前在控制器操作中创建有效的可嵌入对象。但这远非“好”的解决方案,我想避免这种情况。
我的实体、值对象和形式(为提问而简化)
Foo\BarBundle\Entity\CategoryType
<?php
namespace Foo\BarBundle\Entity;
class CategoryType
{
/**
* @var string
*/
protected $value;
public function __toString()
{
return (string) $this->getValue();
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* @param string $value
*
* @return $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
}
Foo\BarBundle\Resources\config\doctrine\CategoryType.orm.yml
CategoryType.orm.yml
Foo\BarBundle\Entity\CategoryType:
type: embeddable
fields:
value:
type: string
Foo\BarBundle\Entity\Category
<?php
namespace Foo\BarBundle\Entity;
class Category
{
/**
* @var integer
*/
protected $id;
/**
* @var string
*/
protected $name;
/**
* @var CategoryType
*/
protected $type;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return \Foo\BarBundle\Entity\CategoryType
*/
public function getType()
{
return $this->type;
}
/**
* @param \Foo\BarBundle\Entity\CategoryType $type
*
* @return $this
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* @return string
*/
public function __toString()
{
return (string) $this->getName();
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
Foo\BarBundle\Resources\config\doctrine\Category.orm.yml
Foo\BarBundle\Entity\Category:
type: entity
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
name:
type: string
embedded:
type:
class: CategoryType
Foo\BarBundle\Form\CategoryType
<?php
namespace Foo\BarBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CategoryType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('type')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'Foo\BarBundle\Entity\Category'
)
);
}
/**
* @return string
*/
public function getName()
{
return 'category_form';
}
}
【问题讨论】:
标签: forms symfony doctrine-orm