我有一个列出已注册活动的表格,可以删除每个活动。该表如下所示:
<table class="table-striped table-condensed table-hover">
<tr>
<th>Date</th>
<th>Activity</th>
<th>Steps</th>
<th></th>
</tr>
@for(a <- activities) {
@helper.form(routes.DashboardController.deleteUA(a.id)) {
<tr>
<td style="width:30%">@a.date.format("dd MMM")</td>
<td style="width:30%">@a.activity.name</td>
<td style="width:30%">@a.steps</td>
<td>
<button type="submit" style="background-color:#FF6666"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
}}
</table>
删除UserActivity对象的方法如下所示:
public static Result deleteUA(Long id) {
UserActivity.find.ref(id).delete();
return dashboard();
}
删除对象后,该方法将使用dashboard()方法再次呈现页面:
@Security.Authenticated(Secured.class)
public static Result dashboard() {
User user = User.find.byId(request().username());
return ok(dashboard.render(user, Tips.all(), 0.0 , getGoals(user), updateLeaderboards(), getRecentUA()));
}
当我提交表单并调用deleteUA()时,对象将按预期删除,但是当我要使用dashboard()呈现页面时,我收到此错误:
[NullPointerException:id为null]
从这一行:
User user = User.find.byId(request()。username());
如果我通过调用url(以这种方式调用dashboard()方法)返回仪表板,一切似乎都很好,删除的活动从列表中消失。
我无法理解为什么删除UserActivity对象与在会话中查找用户ID有关。有什么想法吗?
更新! UserActivity如下所示:
package models;
import java.util.*;
import play.db.ebean.*;
import javax.persistence.*;
@Entity
public class UserActivity extends Model {
@Id
public Long id;
@ManyToOne
public User belongsTo;
@ManyToOne
public Activity activity;
public int intensity;
public double steps;
public Date date;
public static Finder<Long,UserActivity> find = new Finder<Long,UserActivity>(
Long.class, UserActivity.class
);
}
答案 0 :(得分:0)
如何尝试使用redirect(...)
方法而不是仅仅调用控制器的操作。
我假设您的routes
文件有一些像这样的条目
GET /dashboard controllers.Application.dashboard()
然后在你的deleteUA
方法中你可以写
public static Result deleteUA(Long id) {
UserActivity.find.ref(id).delete();
return redirect(controllers.Application.dashboard());
}