SonataAdminBundle 提供 3 个Saving hooks
. 直接来自文档:
new object : prePersist($object) / postPersist($object)
edited object : preUpdate($object) / postUpdate($object)
deleted object : preRemove($object) / postRemove($object)
所以,你感兴趣的是preUpdate()
为了实现您想要的,您必须non-mapped
在表单中添加新字段:
// This is needed to check the checkbox if the message has been already approved
$approved = false;
$review = $this->getSubject();
if ($review->getApprovedAt()) {
$approved = true;
}
[..]
$builder->add('approve', 'checkbox',
array(
// We don't need this as property in our entity.
'mapped' => false,
// The field should not be required, so that you can skip approving specific comment at the time
'required' => false,
'data' => $approved
)
);
现在,您所要做的就是读取更新时的值并设置日期时间(如果选中):
public function preUpdate($object) {
/* @var $isApproved boolean */
$isApproved = $this->getForm()->get('approve')->getData();
if( $isApproved ) {
$object->setApprovedAt( new \DateTime('now') );
}
}
这应该可以解决问题。文档中的章节 -这里。