2014-04-02 17 views
0

創建事件偵聽器Post實體preUpdate,觸發很好,但是當我嘗試更新相關實體Category,它拋出一個錯誤:如何使用EventListener更新相關實體?

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 

如何更新此Category實體在這個EvenetListener中與Post實體一樣在我的例子中?

This answer work,but only for Post changes。但我也需要改變Category實體的一些值,比如:

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

難道你不能簡單地做'$ entity-> setCategory(null)'? –

+0

@AlbertoFernández是的,我可以,但它什麼都不做。順便說一下,'$ entity-> setSlug('new-slug')'也無能爲力。對於它的工作,我需要使用'setNewValue',但與相關的實體它不會工作。 –

回答

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()) 
     )); 
    } 
+0

不,我檢查這個值,它不'NULL'。我想'setNewValue'方法只適用於靜態字段(整數,字符串等),而不是相關的實體。但是我現在需要改變一個相關的實體。 –

+1

我很困惑。也許你可以試試這個[主題](http://stackoverflow.com/questions/19884440/change-not-changed-property-in-the-doctrine-event-listener)(查看鏈接到另一個主題的投票評論)。 – Debflav

+1

謝謝,[本](http://stackoverflow.com/questions/8930062/how-do-i-change-a-fields-value-in-preupdate-event-listener/8930276#8930276)工作!但僅適用於「Post」更改。如果我嘗試更改'Category'實體的某些值,例如:'$ entity-> getCategory() - > setSlug('some-category-slug')' - 沒有任何反應。 –