I am trying to populate a DataTable from google chart to generate a chart. So far, I was able to get the information to travel from the database (MySQL) to the controller, and from there to the view using an ArrayList but when reading the dates, something happens and controls are subtracted:
In summary: I am sending an Array with data in the 2019-05-21 format and JavaScript interprets it as a mathematical operation, leaving 1,993.
I understand that it may be seen as a basic error, but it is my first time working with JavaScript and I have already spent several hours reading documentation and have not found any solution.
Controller:
#Controller
#RequestMapping
public class indexController {
#Autowired
private IAccionService service;
#GetMapping("chart_index")
public String profileSettings(Model model) {
String msg="holasoyundatodeprueba";
String msg2="Fecha1";
model.addAttribute("msg", msg);
model.addAttribute("msg2", msg2);
List<Acciones>accioneslst=service.listar_acciones();
Acciones[] arrayAcciones = new Acciones[accioneslst.size()];
arrayAcciones=accioneslst.toArray(arrayAcciones);
ArrayList<String> arrayFechas = new ArrayList<String>();
ArrayList<Integer> arrayOpen = new ArrayList<Integer>();
ArrayList<Integer> arrayClose = new ArrayList<Integer>();
for (Acciones acciones : arrayAcciones) {
arrayFechas.add(acciones.getFecha().toString());
arrayOpen.add(acciones.getOpen_value());
arrayClose.add(acciones.getClose_value());
System.out.println(arrayFechas.toString());
}
model.addAttribute("fechaGrafico",arrayFechas);
model.addAttribute("openGrafico",arrayOpen);
model.addAttribute("closeGrafico",arrayClose);
return "chart_index";
}
JavaScript code (Google Chart: Line Chart) added to the view:
<!DOCTYPE html>
<html>
<head xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gráfico de acciones</title>
<link rel="stylesheet" type="text/css" href="CSS/styles_chart.css" />
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var Fecha=[[${fechaGrafico}]];
var Open=[[${openGrafico}]];
var Close=[[${closeGrafico}]];
var data = new google.visualization.DataTable(); //Cambiado a DataTable
data.addColumn('string','Fecha');
data.addColumn('number','Open');
data.addColumn('number','Close');
for(i=0;i<Fecha.length;i++)
data.addRow(["'"+Fecha[i]+"'",Open[i],Close[i]]);
console.log(Fecha);
var options = {
title : "[[${msg}]]",
curveType : 'function',
backgroundColor : '#EDEEF0',
width : '1323',
height : '855',
legend : 'none',
chartArea : {
width : '1200',
height : '800'
},
colors : [ '#A6CEE3', '#1F78B4' ]
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
Class:
Package com.amsterdam.springboot.v1.app.models;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="accion") //Nombre de la tabla
public class Acciones {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Date fecha;
private int open_value;
private int high_value;
private int low_value;
private int close_value;
private int adj_close;
private int volume;
private String enterprise;
public Acciones() {
// TODO Auto-generated constructor stub
}
public Acciones(Date fecha, int open_value, int high_value, int low_value, int close_value, int adj_close,
int volume, String enterprise) {
super();
this.fecha = fecha;
this.open_value = open_value;
this.high_value = high_value;
this.low_value = low_value;
this.close_value = close_value;
this.adj_close = adj_close;
this.volume = volume;
this.enterprise = enterprise;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public int getOpen_value() {
return open_value;
}
public void setOpen_value(int open_value) {
this.open_value = open_value;
}
public int getHigh_value() {
return high_value;
}
public void setHigh_value(int high_value) {
this.high_value = high_value;
}
public int getLow_value() {
return low_value;
}
public void setLow_value(int low_value) {
this.low_value = low_value;
}
public int getClose_value() {
return close_value;
}
public void setClose_value(int close_value) {
this.close_value = close_value;
}
public int getAdj_close() {
return adj_close;
}
public void setAdj_close(int adj_close) {
this.adj_close = adj_close;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public String getEnterprise() {
return enterprise;
}
public void setEnterprise(String enterprise) {
this.enterprise = enterprise;
}
}
Related
OK... so I have a Custom HTMLWebview which I want to add Javascript to. A lot of examples I find online have the HTML on Android (and iOS) level but I would prefer keeping the HTML in the Custom Renderer (that way I can fill it with custom content on seperate pages).
Right now I have a button which should fire an event but it is not happening and I'm not sure why.
This is my Custom Renderer:
public class HybridWebView : WebView
{
public HybridWebView()
{
const string html = #"
<html>
<body>
<h3>Test page</h3>
<button type=""button"" onClick=""CSharp.ShowToast('Hello from JS')"">Native Interaction</button>
</body>
</html>";
var htmlSource = new HtmlWebViewSource();
htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
htmlSource.Html = html;
Source = htmlSource;
}
}
This is my Android Renderer:
[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace Test.Droid.Renderers
{
public class HybridWebViewRenderer : WebViewRenderer
{
Context _context;
public HybridWebViewRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (Control != null)
{
Control.Settings.JavaScriptEnabled = true;
Control.AddJavascriptInterface(new HybridJSBridge(Android.App.Application.Context), "CSharp");
}
base.OnElementPropertyChanged(sender, e);
}
}
}
This is my bridge:
public class HybridJSBridge : Java.Lang.Object
{
Context context;
public HybridJSBridge(Context context)
{
this.context = context;
}
[JavascriptInterface]
[Export]
public void ShowToast(string msg)
{
Toast.MakeText(context, msg, ToastLength.Short).Show();
}
}
Right now nothing happens when the button is pressed. I hope someone can point me in the right direction?
Thanks in advance!
Do you want to achieve the result like following GIF?
I do not know what value of BaseUrl
in htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get(); , If I set the value of return "file:///android_asset";
[assembly: Dependency(typeof(BaseUrl_Android))]
namespace WebviewInvokeJS.Droid
{
class BaseUrl_Android : IBaseUrl
{
public string Get()
{
//throw new NotImplementedException();
return "file:///android_asset";
}
}
}
and add Control.SetWebViewClient(new WebViewClient()); in HybridWebViewRenderer it worked.
[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace WebviewInvokeJS.Droid
{
public class HybridWebViewRenderer : WebViewRenderer
{
Context _context;
public HybridWebViewRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (Control != null)
{
Control.Settings.JavaScriptEnabled = true;
Control.AddJavascriptInterface(new HybridJSBridge(Android.App.Application.Context), "CSharp");
Control.SetWebViewClient(new WebViewClient());
}
base.OnElementPropertyChanged(sender, e);
}
}
}
You also could download my demo to make a test.
https://github.com/851265601/XFormsWebviewInvokeJS
I have written the code below in java to retrieve the value from database and stored in Json file. File name is DatabaseGraphValue.java.
package com;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.GraphValue;
import com.google.gson.Gson;
#WebServlet("/GraphJsonValueServlet")
public class DataBaseGraphValue extends HttpServlet
{
static Connection conn = null;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project="Project1";
public static Connection getDataBaseVale()
{
if(conn != null)
{
return conn;
}
else
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue","root","root");
}
catch (Exception e)
{
e.printStackTrace();
}
return conn;
}
}
public DataBaseGraphValue()
{
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
List<GraphValue> listOfGraphValue = getGraphValue();
Gson gson = new Gson();
String jsonString = gson.toJson(listOfGraphValue);
response.setContentType("application/json");
response.getWriter().write(jsonString);
}
private List<GraphValue> getGraphValue()
{
conn = getDataBaseVale();
List<GraphValue> listOfGraphValue = new ArrayList<GraphValue>();
try
{
stmt=conn.prepareStatement("select * from TestCase where ProjectName= ?");
stmt.setString(1,project);
rs=stmt.executeQuery();
while(rs.next())
{
GraphValue gv1 = new GraphValue();
gv1.setProjectName(rs.getString(1));
gv1.setTotalTestCase(rs.getInt(2));
gv1.setTestCaseExecuted(rs.getInt(3));
gv1.setFailedTestCase(rs.getInt(4));
gv1.setTestCaseNotExecuted(rs.getInt(2));
listOfGraphValue.add(gv1);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return listOfGraphValue;
}
}
And the other file name is GraphValue.java.
package com;
public class GraphValue {
private String projectName;
private int totalTestCase;
private int testCaseExecuted;
private int failedTestCase;
private int testCaseNotExecuted;
public String getProjectName()
{
return projectName;
}
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
public int getTotalTestCase()
{
return totalTestCase;
}
public void setTotalTestCase(int totalTestCase)
{
this.totalTestCase = totalTestCase;
}
public int getTestCaseExecuted()
{
return testCaseExecuted;
}
public void setTestCaseExecuted(int testCaseExecuted)
{
this.testCaseExecuted = testCaseExecuted;
}
public int getFailedTestCase()
{
return failedTestCase;
}
public void setFailedTestCase(int failedTestCase)
{
this.failedTestCase = failedTestCase;
}
public int getTestCaseNotExecuted()
{
return testCaseNotExecuted;
}
public void setTestCaseNotExecuted(int testCaseNotExecuted)
{
this.testCaseNotExecuted = testCaseNotExecuted;
}
}
Now I need help in writing a JavaScript so that I can access the value which I am retrieving from the database and can draw a graph. Below is my code where I want the Json data.
<html>
<head>
</head>
<body>
<select id="ChartType" name="ChartType" onchange="drawChart()">
<option value = "PieChart">Select Chart Type
<option value="PieChart">PieChart
<option value="Histogram">Histogram
<option value="LineChart">LineChart
<option value="BarChart">BarChart
</select>
<div id="chart_div" style="border: solid 2px #000000;"></div>
<p id="demo"></p>
<p id="demo1"></p>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var row = [];
var temp;
var stri;
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(getValues);
function getValues() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
stri = xmlhttp.responseText;
drawChart();
}
};
xmlhttp.open("GET", "sample.java", true);
xmlhttp.send();
}
function drawChart()
{
var data = new google.visualization.DataTable();
----How to get the jason data here for the graph
}
data.addRows(row);
var a = document.getElementById("ChartType").value;
document.getElementById("demo1").innerHTML = "You selected: " + a;
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300
};
var chart = new google.visualization[document.getElementById("ChartType").value](document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</body>
</html>
Value which I am retrieving from the database is:
ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted
Project1 50 30 8 20
Please let me know how to proceed further. Thank you
Pass xmlhttp.responseText to drawChart() at onreadystatechange handler
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
stri = xmlhttp.responseText;
drawChart(stri);
}
at drawChart()
function drawChart(response) {
var data = new google.visualization.DataTable();
// How to get the jason data here for the graph
// do stuff with `response`:`stri`
console.log(response);
}
I am working with spring batch , I have configured my job to be executed by clicking on a button (spring MVC).
all information about my job are in BATCH_JOB_EXECUTION in the database.
I want to have this scenario:
-when I load the page , the table contains all the records existing in the database
-when I click on the button to execute my job, the last record added in the database is added in the front end of my table.
This is what I have done But still not working!
Here is the content of BATCH_JOB_EXECUTION.java file :
public class BATCH_JOB_EXECUTION {
private int JOB_EXECUTION_ID ;
private int VERSION;
private int JOB_INSTANCE_ID;
private Time CREATE_TIME ;
private Time START_TIME;
private Time END_TIME;
private String STATUS;
private String EXIT_CODE;
private String EXIT_MESSAGE;
private Time LAST_UPDATED;
public BATCH_JOB_EXECUTION(){
}
public int getJOB_EXECUTION_ID() {
return JOB_EXECUTION_ID;
}
public void setJOB_EXECUTION_ID(int jOB_EXECUTION_ID) {
JOB_EXECUTION_ID = jOB_EXECUTION_ID;
}
public int getVERSION() {
return VERSION;
}
public void setVERSION(int vERSION) {
VERSION = vERSION;
}
public int getJOB_INSTANCE_ID() {
return JOB_INSTANCE_ID;
}
public void setJOB_INSTANCE_ID(int jOB_INSTANCE_ID) {
JOB_INSTANCE_ID = jOB_INSTANCE_ID;
}
public Time getCREATE_TIME() {
return CREATE_TIME;
}
public void setCREATE_TIME(Time cREATE_TIME) {
CREATE_TIME = cREATE_TIME;
}
public Time getSTART_TIME() {
return START_TIME;
}
public void setSTART_TIME(Time sTART_TIME) {
START_TIME = sTART_TIME;
}
public Time getEND_TIME() {
return END_TIME;
}
public void setEND_TIME(Time eND_TIME) {
END_TIME = eND_TIME;
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String sTATUS) {
STATUS = sTATUS;
}
public String getEXIT_CODE() {
return EXIT_CODE;
}
public void setEXIT_CODE(String eXIT_CODE) {
EXIT_CODE = eXIT_CODE;
}
public String getEXIT_MESSAGE() {
return EXIT_MESSAGE;
}
public void setEXIT_MESSAGE(String eXIT_MESSAGE) {
EXIT_MESSAGE = eXIT_MESSAGE;
}
public Time getLAST_UPDATED() {
return LAST_UPDATED;
}
public void setLAST_UPDATED(Time lAST_UPDATED) {
LAST_UPDATED = lAST_UPDATED;
}
}
and here is my view :
<div>
<table id="contactTableResponse" class="table tr">
<thead>
<tr>
<th>JOB_INSTANCE_ID</th>
<th>START_TIME</th>
<th>END_TIME</th>
<th>EXIT_CODE</th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="row">Spring-Ajax</th>
<td colspan="4">JQuery Ajax</td>
</tr>
</tfoot>
<tbody>
<c:forEach items="${jobs}" var="BATCH_JOB_EXECUTION">
<tr>
<td>${BATCH_JOB_EXECUTION.JOB_INSTANCE_ID}</td>
<td>${BATCH_JOB_EXECUTION.START_TIME}</td>
<td>${BATCH_JOB_EXECUTION.END_TIME}</td>
<td>${BATCH_JOB_EXECUTION.EXIT_CODE}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
The ajax call:
$('#JobBtn').click( function() {
$('#JobBtn').click( function() {
alert('in submit function');
$.ajax({
type: 'GET',
url: 'load',
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
Updated
this is my controller:
public class AjacController {
#Inject
#Named(value = "dataSource")
private DataSource dataSource1;
#RequestMapping(value="/load" )
public ModelAndView connect(){
ModelAndView model = new ModelAndView("");
BATCH_JOB_EXECUTION batch=null;
List<BATCH_JOB_EXECUTION> list =null;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
String select= "select JOB_INSTANCE_ID, START_TIME,END_TIME,EXIT_CODE from BATCH_JOB_EXECUTION";
try {
connection = dataSource1.getConnection();
preparedStatement = connection.prepareStatement(select);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
batch.setJOB_EXECUTION_ID(resultSet.getInt("JOB_INSTANCE_ID")) ;
batch.setSTART_TIME(resultSet.getTime("START_TIME")) ;
batch.setEND_TIME(resultSet.getTime("END_TIME")) ;
batch.setEXIT_CODE(resultSet.getString("EXIT_CODE")) ;
list.add(batch);
model.addObject("listJobs", list);
}
return model ;
}
but data is not displayed in my table!
Any help will be appreciated.
I am working on a web application developed using Asp.Net MVC which on which I have a page on which data gets updated at realtime whenever data is modified on the database. I have some source on line and tried to implement this feature but it resulted in huge invalid data on the webpage.
I am using SQL dependency and SignalR to achieve this as follows
In Global.asax, I have the following
protected void Application_Start()
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
protected void Application_End()
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
and in Models section I have the following classes
public class JobInfo
{
public int JobID { get; set; }
public string Name { get; set; }
public DateTime LastExecutionDate { get; set; }
public string Status { get; set; }
}
public class JobInfoRepository
{
public IEnumerable<JobInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [JobID],[Name],[LastExecutionDate],[Status]
FROM [dbo].[JobInfo]", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo(){
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3) }).ToList();
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
JobHub.Show();
}
}
I have created a SignalR Hub class as follows which has the Show() function used in the above class
using Microsoft.AspNet.SignalR.Hubs;
public class JobHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
context.Clients.All.displayStatus();
}
}
And I have the controller in which I am calling GetData() method defined in the JobInfoRepository class
public class JobInfoController : Controller
{
// GET: /JobInfo/
JobInfoRepository objRepo = new JobInfoRepository();
public IEnumerable<JobInfo> Get()
{
return objRepo.GetData();
}
}
I have created an Action named JobInfo in HomeController and returned the following view
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JobStatus</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div>
<table id="tblJobInfo" class="clientTable" style="text-align:center;margin-left:10px"></table>
</div>
</body>
</html>
#section scripts {
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="~/App/JobInfo.js"></script>
}
to retrieve the data and supply it to tblJobInfo id in the above html, a java script function is used
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../JobInfo/',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Status</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Status + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
As in the demo I found it to be working fine but when I go to http://localhost:57044/Home/JobInfo/ I get invalid data on the page besides not getting the realtime notifications as in the following image
reference to the source I found online is http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency
I have a little (i hope) problem trying to use Doubleselect element from Struts2 jQuery plugin. I have followed the sample without problems, and the behaviour is as expected when I add a new record (add new record to database), but when i try to edit an existing one the second select does not load the stored value for the record being edited.
Any help?
Code and configuration follows:
JSP code
<s:form id="ingresoForm" action="saveIngreso" method="post" validate="true" cssClass="well form-horizontal">
<s:hidden key="ingreso.id"/>
<s:hidden key="cliente" id="cliente"/>
<div class="type-text">
<label for="cliente">Cliente: </label>
<s:url var="remoteurl" action="ajax/clienteProyectoSelectSource"/>
<sj:select
href="%{remoteurl}"
id="clienteSelect"
onChangeTopics="reloadsecondlist"
name="ingreso.cliente.id"
list="clientes"
listKey="id"
listValue="nombre"
emptyOption="false"
headerKey="-10"
headerValue="Por favor seleccione un cliente"/>
</div>
<div class="type-text">
<label for="Proyecto">Proyecto: </label>
<sj:select
href="%{remoteurl}"
id="proyectoSelect"
formIds="ingresoForm"
reloadTopics="reloadsecondlist"
name="ingreso.proyecto.id"
list="proyectos"
listKey="id"
listValue="nombre"
emptyOption="false"
/>
</div>
Action Code
public class ClienteProyectoSelectSourceAjaxAction extends BaseAction {
private List<Cliente> clientes;
private List<Proyecto> proyectos;
private String cliente;
private GenericManager<Cliente, Long> clienteManager;
#Override
public String execute() {
clientes = clienteManager.getAll();
if (cliente != null && cliente.length() > 0 && !cliente.equals("-10")) {
proyectos = clienteManager.get(new Long(cliente)).getProyectos();
}
return Action.SUCCESS;
}
Action Declaration
<package name="example" extends="json-default" namespace="/ajax">
<action name="clienteProyectoSelectSource" class="com.queres.smtm.webapp.action.ajax.ClienteProyectoSelectSourceAjaxAction">
<result type="json"/>
</action>
</package>
Ingreso entity (model)
#Entity
#Table(name = "ingreso")
public class Ingreso extends BaseObject {
// Campos comunes
private Long id;
private TipoIngreso tipo;
private String observaciones;
private BigDecimal importe;
private BigDecimal tipoIVA;
private Date fechaPrevistaCobro;
private Date fechaEfectivaCobro;
// Campos para facturas
private String numeroFactura;
private Cliente cliente;
private Proyecto proyecto;
private TipoServicio servicio;
private Date fechaEmision;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Enumerated(EnumType.STRING)
public TipoIngreso getTipo() {
return tipo;
}
public void setTipo(TipoIngreso tipo) {
this.tipo = tipo;
}
public String getObservaciones() {
return observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
public BigDecimal getImporte() {
return importe;
}
public void setImporte(BigDecimal importe) {
this.importe = importe;
}
public BigDecimal getTipoIVA() {
return tipoIVA;
}
public void setTipoIVA(BigDecimal tipoIVA) {
this.tipoIVA = tipoIVA;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaPrevistaCobro() {
return fechaPrevistaCobro;
}
public void setFechaPrevistaCobro(Date fechaPrevistaCobro) {
this.fechaPrevistaCobro = fechaPrevistaCobro;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaEfectivaCobro() {
return fechaEfectivaCobro;
}
public void setFechaEfectivaCobro(Date fechaEfectivaCobro) {
this.fechaEfectivaCobro = fechaEfectivaCobro;
}
public String getNumeroFactura() {
return numeroFactura;
}
public void setNumeroFactura(String numeroFactura) {
this.numeroFactura = numeroFactura;
}
#ManyToOne
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
#ManyToOne
public Proyecto getProyecto() {
return proyecto;
}
public void setProyecto(Proyecto proyecto) {
this.proyecto = proyecto;
}
#Enumerated(EnumType.STRING)
public TipoServicio getServicio() {
return servicio;
}
public void setServicio(TipoServicio servicio) {
this.servicio = servicio;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaEmision() {
return fechaEmision;
}
public void setFechaEmision(Date fechaEmision) {
this.fechaEmision = fechaEmision;
}
#Override
public int hashCode() {
int hash = 3;
hash = 43 * hash + (this.numeroFactura != null ? this.numeroFactura.hashCode() : 0);
hash = 43 * hash + (this.fechaEmision != null ? this.fechaEmision.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Ingreso other = (Ingreso) obj;
if ((this.numeroFactura == null) ? (other.numeroFactura != null) : !this.numeroFactura.equals(other.numeroFactura)) {
return false;
}
if (this.fechaEmision != other.fechaEmision && (this.fechaEmision == null || !this.fechaEmision.equals(other.fechaEmision))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Ingreso{" + "id=" + id + ", tipo=" + tipo + ", observaciones=" + observaciones + ", importe=" + importe + ", tipoIVA=" + tipoIVA + ", fechaPrevistaCobro=" + fechaPrevistaCobro + ", fechaEfectivaCobro=" + fechaEfectivaCobro + ", numeroFactura=" + numeroFactura + ", cliente=" + cliente + ", proyecto=" + proyecto + ", servicio=" + servicio + ", fechaEmision=" + fechaEmision + '}';
}
}
Thx in advance
Problem solved. It seems that jquery-plugin work perfectly, as usual the error was between the keyboard and the chair...
I forgot to load the data list for the second select, so jquery was unable to select the aproppiate value.
So, the solution was to ensure that the second list (proyectos) was loaded when the user edits an element.
I add a flag (cliente) as a hidden element on JSP and preloaded it from the main action, so I can check from the Ajax Action if it is necessary to populate the second list.
Ingreso Action (main action for the view)
public class IngresoAction extends BaseAction implements Preparable {
private String cliente;
public String edit() {
if (id != null) {
ingreso = ingresoManager.get(id);
cliente = Long.toString(ingreso.getCliente().getId());
} else {
ingreso = new Ingreso();
}
return SUCCESS;
}
public String getCliente() {
return cliente;
}
public void setCliente(String cliente) {
this.cliente = cliente;
}
<...>