Reputation: 12306
I create Event Listener for preUpdate
of Post
entity, that triggered fine, but when I try to update the related entity Category
, it thrown an error:
Field "category" is not a valid field of the entity "BW\BlogBundle\Entity\Post" in PreUpdateEventArgs.
My Event Listener code is:
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...
My Post entity code is:
/**
* 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
How can I update this Category
entity in this EvenetListener together with Post
entity like in my example?
This answer work, but only for Post
changes. But I also need change some values of Category
entity, for example:
$entity->getCategory()->setSlug('some-category-slug'); // changes not apply, nothing happens with Category entity.
Upvotes: 0
Views: 391
Reputation: 1151
I guess the method setNewValue only works for a field that has changed. Maybe your category is already NULL. That's why it's throw the error. Here's the sample code from 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())
));
}
Upvotes: 1