2016-05-02 2 views
0

Ich möchte Formularsatz speichern, wenn amount gleich 0 entspricht und aktualisieren Sie es, wenn amount > 0. Aber ich weiß nicht, wie man das mit Playframework macht. Hier ist mein Code:Playframework: wie zu entscheiden, ob einfügen oder aktualisieren basierend auf einem Feld

Controller-Methode:

public static Result add() { 
    Form<Store> taskData = form(Store.class); 
    Form<Store> tasks = taskData.bindFromRequest(); 
    Store.recharge(tasks.get()); 
    return ok ("Stored successfully"); 
} 

Modelle:

@Entity 
@Table(name = "store") 
public class Store extends Model { 

    @Id 
    public Long id; 

    public int amount; 

    public static Finder<Long, Store> find = new Finder(Long.class, Store.class); 

    public static List<Store> all() { 
     return find.all(); 
    } 

    public static Store findById(Long id) {return (find.ref(id));} 

    public static void add (Store data) { 
     data.save(); 
    } 
} 
+0

Kannst du nicht einfach die 'Store' Modells Menge überprüfen und wenn es> 0, dann rufen Sie einfach' Daten. update() 'anstelle von' save() '? Vielleicht können Sie noch etwas klären. – BatteryAcid

+0

Danke, um meine Frage Claire zu stellen. Ich habe das gemacht, aber funktioniert nicht für mich: 'String Betrag = taskData.bindFromRequest(). Feld (" Betrag "). Value(); int am = Integer.parseInt (Menge); if (am == 0) { Store.recharge (tasks.get()); Rückgabe ok ("erfolgreich gespeichert"); } sonst wenn (am> 0) { Store.update (tasks.get()); Rückkehr ok ("thaks für aktualisiert"); } ' –

Antwort

0

Es scheint, wie Sie nicht das Formular Funktionalität korrekt dargestellt werden kann, ist hier ein komplettes Arbeitsbeispiel:

Route

POST /test @controllers.Application.test()  

Controller:

public Result test() { 
     Form<Store> storeForm = Form.form(Store.class); 
     Store store = storeForm.bindFromRequest().get(); 
     System.out.println(Json.toJson(store)); 

     if (store.getAmount() > 0) { 
      //update 
      System.out.println("perform update"); 
     } else { 
      //save or recharge 
      System.out.println("perform recharge"); 
     } 
     return ok(); 
    } 

Modell

public class Store { 

     private Long id; 
     private int amount; 
     public Long getId() { 
      return id; 
     } 
     public void setId(Long id) { 
      this.id = id; 
     } 
     public int getAmount() { 
      return amount; 
     } 
     public void setAmount(int amount) { 
      this.amount = amount; 
     } 
    } 

Anfrage:

curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" -d 'id=12345&amount=0' "http://localhost:9000/test" 
+0

Vielen Dank Ihre Nachricht ist hilfreich @ BatteryAcid –

+0

Bitte upvote oder markieren Sie richtig, wenn es hilfreich war - danke! – BatteryAcid

Verwandte Themen