我为preUpdate
Post
实体创建事件监听器,触发正常,但是当我尝试更新相关实体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
实体,如我的示例所示?
此answer有效,但仅适用于Post
更改。但我还需要更改Category
实体的某些值,例如:
$entity->getCategory()->setSlug('some-category-slug'); // changes not apply, nothing happens with Category entity.
答案 0 :(得分:1)
我猜方法setNewValue仅适用于已更改的字段。也许您的类别已经是NULL。这就是它抛出错误的原因。以下是documentation的示例代码。
/**
* 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())
));
}