我有一个包含评论的实体。它有一个非常简单的结构
sent_at | DateTime
comment_author | Text
comment_text | Text
approved_at | DateTime (null when the comments is inserted)
我已经设置了奏鸣曲,我现在可以管理评论了。
“编辑”页面有一组下拉菜单,用于设置字段的日期和时间approved_at
我想要做的是在“编辑”页面中选中一个复选框,如果选中在approved_at
我该怎么做?
答案 0 :(得分:1)
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') );
}
}
这应该可以解决问题。文档中的章节 - here.