play 2.0 templates html select with if statement in a map - templates

I want to create a <select> without using the helpers (because the select helper is generating a lot of html)
So, I get a list of cities from the Controller like:
public static List<City> getAllSortedByNameAsc() {
List<City> cities = new ArrayList<City>();
cities.addAll(City.find.orderBy("name").findList());
return cities;
}
In my template, I create the options with this code:
#cities.map { city =>
<option value="#city.id">#city.name</option>
}
which works, but I also want to have the chosen city as selected value. I tried several things like this:
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value == city.id){selected}">#city.name</option>
}
But that doesn't work. Can anyone give me a hint?

Configuration File: application.conf
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*"
Controller Class => Application.java
package controllers;
import play.*;
import play.mvc.*;
import models.City;
import play.data.Form;
import views.html.*;
public class Application extends Controller {
final static Form<City> cityForm = form(City.class);
public static Result index() {
City pune=new City();
pune.name="pune";
pune.save();
City mumbai=new City();
mumbai.name="mumbai";
mumbai.save();
City city=City.get(2L);
return ok(index.render(cityForm.fill(city),City.all()));
}
}
Model Class => City.java:
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
import java.util.List;
import com.avaje.ebean.validation.NotNull;
#Entity
public class City extends Model{
#Id
public Long id;
#NotNull
public String name;
public static Finder<Long, City> find = new Finder(Long.class, City.class);
public static City get(Long id){
return find.byId(id);
}
public static List<City> all() {
return find.all();
}
}
Template File => index.scala.html
#(cityForm: Form[City],cities: List[City])
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<div>
<select>
#for(city <- cities){
<option value="#city.id" #{if(city.id.toString().equals(cityForm("id").value)) "selected='selected'"}/>#city.name</option>
}
</select>
</div>
</body>
</html>

I'm not positive about how the type mapping is working, but I would try
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value.equals(city.id)){selected}">#city.name</option>
}
rather than using the == operator.
You should also consider whether the helper has a good reason for generating all that HTML. It's generally a pretty smart framework.

Related

Pass multiple list from controller to view

I MVC c# application which has model
public class lstSearchCriteria
{
public List<lstCampaign> cmpList { get; set; }
public List<lstAgent> agentList { get; set; }
}
public class lstCampaign
{
public string campaignName { get; set; }
}
public class lstAgent
{
public string agentShortName { get; set; }
public string agentFullName { get; set; }
}
& controller which returns lstSearchCriteria. I need to display lstCampaign & lstAgent in dropdown list.
In view I am doing
#using QAApplication.Models
#model QAApplication.Models.lstSearchCriteria
<select id="lstCampaigns" multiple="multiple">
#foreach (var item in Model.cmpList)
{
<option >#item.campaignName</option>
}
</select>
<div id="divlstAgents">
<select id="lstAgents" multiple="multiple">
#foreach (var item in Model.agentList)
{
<option >#item.agentShortName</option>
}
</select>
</div>
I am getting below error :The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[QAApplication.Models.lstSearchCriteria]', but this dictionary requires a model item of type 'QAApplication.Models.lstSearchCriteria'.
what could be the best way to pass multiple list to view from controller. Thanks in advance
You are passing List<lstSearchCriteria>, While Views expected model lstSearchCriteria only.

Why does my nested POJO return null from a form in Play! 1.x

In Play! Framework 1.5.1, why am I getting null back for thingy.Owner ? Shouldn't the automatic binding take care of this?
User class
package models;
#Entity
#Table(name="objtest_user")
public class User extends Model
{
#Required
public String username;
#Password
#Required
public String password;
public String fullname;
public User(String username, String password, String fullname)
{
this.username = username;
this.password = password;
this.fullname = fullname;
}
#Override
public String toString()
{
return this.fullname;
}
}
and this Thingy class that references the User class
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
import play.data.validation.*;
#Entity
public class Thingy extends Model
{
#Required
public String Name;
#ManyToOne
public User Owner;
public Thingy(String name, User owner)
{
this.Name = name;
this.Owner = owner;
}
#Override
public String toString()
{
return Name;
}
}
and this Template form
#{extends 'main.html' /}
#{set title:'Home' /}
<p>Current user = ${currentUser}</p>
#{form #saveThingy(), id:'saveThingy'}
<input type="text" id="thingy.Name" name="thingy.Name"/>
<input type="hidden" id="thingy.Owner" name="thingy.Owner" value="${currentUser}"/>
<input type="submit" id="Save" value="Save"/>
#{/form}
Controller method
public static void saveThingy(Thingy thingy)
{
System.out.println("Name = " + thingy.Name);
System.out.println("Owner = " + thingy.Owner);
thingy.save();
}
Try changing the following line
<input type="hidden" id="thingy.Owner" name="thingy.Owner" value="${currentUser}"/>
To
<input type="hidden" id="thingy.Owner" name="thingy.Owner.id" value="${currentUser.id}"/>
If you check out the docs (https://www.playframework.com/documentation/1.2.x/controllers#params), and look for JPA object binding section, it talks about requiring sub objects to have an id. Play when it finds an ID for an object, it will load the relavent entity via JPA/Hibernate.

model class is not working in laravel project

i am beginner in la-ravel,problem in work on model how be work on project.
firstly used the api.php to link the page
Route::any('/user',['uses'=>'PagesController#my']);
create the controller
public function my(Request $request){
$val=validator::make($request->all(),[
'id'=>'required',
'name'=>'required',
'email'=>'required',
'mobile'=>'required'
]);
//return 'rahul';
return response()->json([$val]);
}
model is link to the controller
use App\rahul;
use Validator;
create the model page design
class rahul extends Model{
protected $table = "display";
public function my($data)
{
$save = new rahul;
$save->id = $data['id'];
$save->name = $data['name'];
$save->email = $data['email'];
$save->mobile = $data['mobile'];
$save->save();
return $save->id;
}
}
and,last step will done it create the database like
enter image description here
database name is lara2 and table name display simple page design
but problem how to model be used
Route::get('first', 'ApiController#first')->name('first');
Route::post('store', 'ApiController#store')->name('store');
using the code in api.php
and next step model is create
php artisan make: model Article
model page
class Article extends Model{ protected $fillable = ['name', 'email'];}
next step create the controller
controller page (apicontroller)
public function first(){
return view('first');
}
public function store(Request $request)
{
$article = Article::create($request->all());
return response()->json($article, 201);
}
blade page web page design
<form method="POST" action="store">
{{csrf_field()}}
<input type="text" name="name">
<input type="email" name="email">
<input type="submit" name="submit"></form>
migration is create Article table name connection
public function up()
{
Schema::create('Articles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Articles');
}

JSF Primefaces selectonemenu page navigation

I am developing a web application using JSF and Primefaces. I want o show the following menu and depending on the choosen option go to one page or another.
XHTML code:
<p:outputLabel for="car" value="Grouping: " />
<p:selectOneMenu id="car" value="#{selectOneMenuView.car}">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{selectOneMenuView.cars}" />
</p:selectOneMenu>
Managed bean code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;
ManagedBean
public class SelectOneMenuView {
private String console;
private String car;
private List<SelectItem> cars;
private String city;
private Map<String,String> cities = new HashMap<String, String>();
private Theme theme;
private List<Theme> themes;
#ManagedProperty("#{themeService}")
private ThemeService service;
#PostConstruct
public void init() {
//cars
SelectItemGroup g1 = new SelectItemGroup("German Cars");
g1.setSelectItems(new SelectItem[] {new SelectItem("BMW", "BMW"), new SelectItem("Mercedes", "Mercedes"), new SelectItem("Volkswagen", "Volkswagen")});
SelectItemGroup g2 = new SelectItemGroup("American Cars");
g2.setSelectItems(new SelectItem[] {new SelectItem("Chrysler", "Chrysler"), new SelectItem("GM", "GM"), new SelectItem("Ford", "Ford")});
cars = new ArrayList<SelectItem>();
cars.add(g1);
cars.add(g2);
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
}
How can I do so that an user navigates to pageBMW.xhtml if he chooses the BMW option from the list or to pagemercedes.xhtml if he chooses the Mercedes option from the list?
I would append an AJAX on change event to the selectOneMenu which calls a method on your bean and redirects through it similar to a combination of the respective accepted answers of selectOneMenu ajax events (AJAX event) and Sending a redirect from inside an ajax listener method (redirect).
You might process the value of car via an AJAX call and redirect the response from your bean class.
<p:selectOneMenu id="car" value="#{selectOneMenuView.car}">
<f:selectItem itemLabel="Select One" itemValue=""
noSelectionOption="true" />
<f:selectItems value="#{selectOneMenuView.cars}" />
<p:ajax listener="#{selectOneMenuView.someAction()"
process="#this" partialSubmit="true" />
</p:selectOneMenu>
And within your bean class something like
public void someAction() {
String location = "page"+car+".xhtml";
FacesContext.getCurrentInstance()
.getExternalContext()
.redirect(location)
;
}
}

Lazy loading in TomEE is not working as expected

Entity's lazy property is always returning null value in TomEE, but working in Glassfish 3 as expected. Is there any listener i am missing to include in web.xml or something else? How to fetch lazy property?
Here is the source code:
AppGroup.java:
package uz.mf.javaee6app;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class AppGroup implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
AppUser.java:
package uz.mf.javaee6app;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
*
* #author ravshan
*/
#Entity
public class AppUser implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
private List<AppGroup> roles;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<AppGroup> getRoles() { return roles; }
public void setRoles(List<AppGroup> roles) { this.roles = roles; }
}
I'm skipping AppUserFacade stateless bean and UserManager CDI bean, there's nothing special. and the last users.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Selected user: #{userManager.selectedUser.name}
<h:dataTable value="#{userManager.selectedUser.roles}" var="role">
<h:column>#{role.name}</h:column>
</h:dataTable>
</h:body>
</html>
UserManager.java:
package uz.mf.javaee6app;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class UserManager implements Serializable {
private AppUser selectedUser;
public AppUser getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(AppUser selectedUser) {
this.selectedUser = selectedUser;
}
}
Selected user is being set by another view.
I'd bet the problem is that somehow your Entity is getting detached prior to accessing the lazy loaded field. Be sure to check your transaction attributes to ensure that your context is still active when you are trying to get lazy loading working.