【问题标题】:How can I use EventListener for update related Entity?如何使用 EventListener 更新相关实体?
【发布时间】:2014-04-02 12:02:14
【问题描述】:

我为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

如何像我的示例一样更新此 EventetListener 中的 Category 实体和 Post 实体?

此answer 有效,但仅适用于Post 更改。但我还需要更改Category实体的一些值,例如:

$entity->getCategory()->setSlug('some-category-slug'); // changes not apply, nothing happens with Category entity.

【问题讨论】:

  • 你不能简单地做$entity->setCategory(null)吗?
  • @AlbertoFernández 是的,我可以,但它什么也没做。顺便说一句,$entity->setSlug('new-slug') 也无能为力。为了让它工作,我需要使用setNewValue,但是对于相关实体它不起作用。

标签: php symfony doctrine-orm entity event-listener


【解决方案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())
         ));
     }

【讨论】:

  • 不,我检查了这个值,它没有NULL。我猜setNewValue 方法仅适用于静态字段(整数、字符串等),而不适用于相关实体。但此时我需要更改相关实体。
  • 我很困惑。也许你可以试试这个topic(查看链接到另一个主题的投票评论)。
  • 谢谢,this 工作!但仅适用于 Post 更改。如果我尝试更改 Category 实体的某些值,例如:$entity->getCategory()->setSlug('some-category-slug') - 没有任何反应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多