/backend/sosmessage-admin/app/controllers/Categories.scala

https://github.com/troger/sosmessagedecarte · Scala · 57 lines · 45 code · 12 blank · 0 comment · 0 complexity · 8a1df8e39667773f7c7373fdad693b39 MD5 · raw file

  1. package controllers
  2. import play.api._
  3. import data._
  4. import play.api.mvc._
  5. import com.mongodb.casbah.commons.MongoDBObject
  6. import com.mongodb.casbah.MongoConnection
  7. import org.bson.types.ObjectId
  8. import java.util.Date
  9. import com.mongodb.DBObject
  10. object Categories extends Controller {
  11. val DataBaseName = "sosmessage"
  12. val CategoriesCollectionName = "categories"
  13. val mongo = MongoConnection()
  14. val categoriesCollection = mongo(DataBaseName)(CategoriesCollectionName)
  15. val categoryForm = Form(
  16. "name" -> text(minLength = 1)
  17. )
  18. def index = Action { implicit request =>
  19. val categoryOrder = MongoDBObject("name" -> 1)
  20. val categories = categoriesCollection.find().sort(categoryOrder).foldLeft(List[DBObject]())((l, a) =>
  21. a :: l
  22. ).reverse
  23. Ok(views.html.categories.index(categories, categoryForm))
  24. }
  25. def save = Action { implicit request =>
  26. categoryForm.bindFromRequest().fold(
  27. f => {
  28. Redirect(routes.Categories.index)
  29. },
  30. v => {
  31. val builder = MongoDBObject.newBuilder
  32. builder += "name" -> v
  33. builder += "createdAt" -> new Date()
  34. categoriesCollection += builder.result
  35. Redirect(routes.Categories.index).flashing("actionDone" -> "categoryAdded")
  36. }
  37. )
  38. }
  39. def delete (id: String) = Action { implicit request =>
  40. val oid = new ObjectId(id)
  41. val o = MongoDBObject("_id" -> oid)
  42. categoriesCollection.remove(o)
  43. Redirect(routes.Categories.index).flashing("actionDone" -> "categoryDeleted")
  44. }
  45. }