我为Post
实体的preUpdate
创建了事件侦听器,触发正常,但是当我尝试更新相关实体Category
时,它抛出了一个错误:
Field "category" is not a valid field of the entity "BW'BlogBundle'Entity'Post" in PreUpdateEventArgs.
我的事件侦听器代码是:
public function preUpdate(PreUpdateEventArgs $args) {
$entity = $args->getEntity();
$em = $args->getEntityManager();
if ($entity instanceof Post) {
$args->setNewValue('slug', $this->toSlug($entity->getHeading())); // work fine
$args->setNewValue('category', NULL); // throw an error
// other code...
我的帖子实体代码是:
/**
* Post
*
* @ORM'Table(name="posts")
* @ORM'Entity(repositoryClass="BW'BlogBundle'Entity'PostRepository")
*/
class Post
{
/**
* @var string
*
* @ORM'Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* @var integer
*
* @ORM'ManyToOne(targetEntity="'BW'BlogBundle'Entity'Category")
* @ORM'JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
// other code
如何更新此 EvenetListener 中的此Category
实体以及Post
实体,如我的示例所示?
此答案有效,但仅适用于Post
更改。但我还需要更改Category
实体的一些值,例如:
$entity->getCategory()->setSlug('some-category-slug'); // changes not apply, nothing happens with Category entity.
我想方法setNewValue仅适用于已更改的字段。也许您的类别已经为空。这就是它抛出错误的原因。下面是文档中的示例代码。
/**
* Set the new value of this field.
*
* @param string $field
* @param mixed $value
*/
public function setNewValue($field, $value)
{
$this->assertValidField($field);
$this->entityChangeSet[$field][1] = $value;
}
/**
* Assert the field exists in changeset.
*
* @param string $field
*/
private function assertValidField($field)
{
if ( ! isset($this->entityChangeSet[$field])) {
throw new 'InvalidArgumentException(sprintf(
'Field "%s" is not a valid field of the entity "%s" in PreUpdateEventArgs.',
$field,
get_class($this->getEntity())
));
}