How to show an error or information message in a JQgrid?

2,154 views
Skip to first unread message

Cesar Lopez

unread,
Jun 11, 2012, 11:02:23 AM6/11/12
to struts2-jquery
Hi!

I need to know how to show an error or information message in a JQgrid
after any operation like edit or add rows ?

for example i have a jqgrid to manage competition. this can update
status of competition (this part works OK) but I need to implement an
restriction that only can be 4 competition with status = active at
the same time and show a error or message in JQGrid "You can not add
more competition".

Anybody knows how to implements error or information messages in
jqGrid from side server ?

Regards!

Alexandre bizeau

unread,
Jun 11, 2012, 2:13:56 PM6/11/12
to struts2...@googlegroups.com
Hello cesar,

I'm using ActionMessage. In my java class, i'm startint with : clearErrorsAndMessages(); to clear every message already added to the .jsp page.

and after there 2 kind of message :

addActionError("Hello world.");

and

addActionMessage("World Hello");

Those 2 need to be read into jsp page so use : <p> <s:actionerror /></p>  or/and <s:actionmessage />

And there you go ! Beautiful message into your page.

There a nice example (With css modify) : http://www.mkyong.com/struts2/struts-2-actionerror-actionmessage-example/

and there java documentation : http://www.opensymphony.com/webwork/api/com/opensymphony/xwork/ActionSupport.html

Alex

Cesar Lopez

unread,
Jun 12, 2012, 8:32:56 AM6/12/12
to struts2...@googlegroups.com
Hi Alexandre!

Tank you for you response, but I tried to add an actionerrror but  the message doesn't show. I think that is because the action only reload the grid but not the page.

do you know another way to show a error or information message after edit a row/cell?

Cesar Lopez

unread,
Jun 12, 2012, 8:33:50 AM6/12/12
to struts2...@googlegroups.com
Hi Alexandre!

Tank you for you response, but I tried to add an actionerrror but  the message doesn't show. I think that is because the action only reload the grid but not the page.

do you know another way to show a error or information message after edit a row/cell?

Alexandre Bizeau

unread,
Jun 12, 2012, 8:52:51 AM6/12/12
to struts2...@googlegroups.com
Hello,

When you add or edit a row, are you using the small icon in the grid or a custom action on a button ? In your code, if you have a method to save your data, try to return INPUT and in your action.xml, do the <result name="input>/NameOfCurrentPage.jsp</result> and the actionMessage will show. On my grid, that work well. Because I'm reload the page and not just the grid.

If you press little button that open an edit dialog, you can maybe use this :

http://stackoverflow.com/questions/6791463/jquery-jqgrid-show-message-when-an-edit-row-is-complete

For inline edit you can use this :

 http://stackoverflow.com/questions/1674320/how-can-i-trigger-the-jqgrid-loading-message

and with the options "loadingText" of the grid, you can maybe change it dynamically. So you can prompt it for a certain amount of time or something like that. I really dont know what you really want. But maybe some one have  a better way than mine. For me, i'm always using ActionMessage.

Have a nice day,

Alex



2012/6/12 Cesar Lopez <cesar....@gmail.com>
--
You received this message because you are subscribed to the Google Groups "struts2-jquery" group.
To view this discussion on the web visit https://groups.google.com/d/msg/struts2-jquery/-/P7jDQtBoCyIJ.

To post to this group, send email to struts2...@googlegroups.com.
To unsubscribe from this group, send email to struts2-jquer...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/struts2-jquery?hl=en.

jogep

unread,
Jun 12, 2012, 9:25:18 AM6/12/12
to struts2-jquery
The Grid Showcase[1] has an example for this. Try to delete an Record
when embedded Database is not in write mode.

[1] http://struts.jgeppert.com/struts2-jquery-grid-showcase/index.action

You can use the same way.

Johannes
---
web: http://www.jgeppert.com
twitter: http://twitter.com/jogep

On 12 Jun., 14:33, Cesar Lopez <cesar.lop...@gmail.com> wrote:
> Hi Alexandre!
>
> Tank you for you response, but I tried to add an actionerrror but  the
> message doesn't show. I think that is because the action only reload the
> grid but not the page.
>
> do you know another way to show a error or information message after edit a
> row/cell?
>
>
>
>
>
>
>
> On Monday, June 11, 2012 1:13:56 PM UTC-5, Alexandre bizeau wrote:
>
> > Hello cesar,
>
> > I'm using ActionMessage. In my java class, i'm startint with :
> > clearErrorsAndMessages(); to clear every message already added to the .jsp
> > page.
>
> > and after there 2 kind of message :
>
> > addActionError("Hello world.");
>
> > and
>
> > addActionMessage("World Hello");
>
> > Those 2 need to be read into jsp page so use : <p> <s:actionerror /></p>
> > or/and <s:actionmessage />
>
> > And there you go ! Beautiful message into your page.
>
> > There a nice example (With css modify) :
> >http://www.mkyong.com/struts2/struts-2-actionerror-actionmessage-exam...
>
> > and there java documentation :
> >http://www.opensymphony.com/webwork/api/com/opensymphony/xwork/Action...

Cesar Lopez

unread,
Jun 12, 2012, 9:45:51 AM6/12/12
to struts2-jquery
Hi! Alexandre

I use edition inline, I only edit a cell (status of competition) but
there is a rule that say: only can be 4 competition with
status=active.

I use annotation configurations for struts2 but i dont know wats is
wrong.

********************************************************************************************
jsp
********************************************************************************************
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%@taglib uri="/struts-tags" prefix="s" %>
<%@taglib uri="/struts-jquery-tags" prefix="sj" %>
<%@taglib uri="/struts-jquery-grid-tags" prefix="sjg" %>

<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<link href="../css/xcelerator.css" rel="stylesheet" type="text/css">
<sj:head jquerytheme="ui-lightness" jqueryui="true"/>

<title>XCELERATOR :: ADMINISTRACION DE CONCURSOS</title>

</head>
<body>
<!-- Header -->
<div id="cabecera">
<center><div id="header"></div></center>
</div>
<!-- END Header -->

<!-- Menu (PUESTO DESPUES DEL CONTENIDO PARA QUE ESTE NO LO TAPE EN
IE) -->
<div id="menu">
<div class="menu">
<s:property value="#session.menu" escapeHtml="" />
</div>
</div>
<!-- END Menu -->

<!-- BEGIN Contenido -->
<div id="contenido">
<s:url id="remoteurl" action="loadGridConcurso" namespace="/
concurso" />
<s:url id="editcellurl" action="editCompetitionStatus" />

<s:actionerror />
<s:actionmessage/>

<center>
<sjg:grid
id="gridTable"
caption="Concursos"
dataType="json"
href="%{remoteurl}"
pager="true"
gridModel="gridModel"
rowList="10,15"
rowNum="10"
rownumbers="true"
width="900"
cellEdit="true"
cellurl="%{editcellurl}"
>
<sjg:gridColumn name="id" index="id" title="no. Concurso"
sortable="false" width="105" />
<sjg:gridColumn name="nombre" index="nombre" title="nombre del
concurso" sortable="true" width="335" />
<sjg:gridColumn name="fechaIni" index="fechaIni" title="Fecha
propuesta" sortable="false" width="115"
formatter="date"
formatoptions="{newformat : 'd-m-Y', srcformat : 'Y-m-d H:i:s'}"
/>
<sjg:gridColumn name="fechaFin" index="fechaFin" title="Fecha
limite" sortable="false" width="115"
formatter="date"
formatoptions="{newformat : 'd-m-Y', srcformat : 'Y-m-d H:i:s'}"
/>
<sjg:gridColumn name="diasRest" index="diasRest" title="Días
restantes" sortable="false" width="120" />
<sjg:gridColumn name="responsableArea" index="responsableArea"
title="Responsable de Area" sortable="false" />
<sjg:gridColumn name="status" index="status" title="Estado"
sortable="false" width="100"
editable="true"
edittype="select"
editoptions="{value:'1:Espera;2:Activo;3:Concluido'}"
/>

</sjg:grid>
</center>
</div>
<!-- END Contenido -->

<!-- BEGIN Footer -->
<div id="footer">
<div id="logo_footer"></div>
</div>
<!-- END Footer -->
</body>
</html>
********************************************************************************************

********************************************************************************************
action to load the jqgrid
********************************************************************************************
package com.gemalto.xcelerator.tt.actions.competition;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;

import com.gemalto.xcelerator.beans.CompetitionBean;
import com.gemalto.xcelerator.tt.bos.competition.CompetitionBO;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage(value="json-default")
@Namespace(value="/concurso")
public class LoadGridCompetitionsAction extends ActionSupport
implements SessionAware {

private static final long serialVersionUID = 1L;

private Map<String,Object>sesion;
private Log log;

private String errmsg;

/** lista de resultados */
private List<CompetitionBean> gridModel;

/** lista temporal */
private List<CompetitionBean> myCompetition;

/** Número de filas que queremos tener dentro del grid - atributo
"rowNum" del grid */
private Integer rows = 0;

/** Página actual. Por defecto el grid lo pone en 1 */
private Integer page = 0;

/** Páginas totales */
private Integer total = 0;

/** todos los registros (PUEDE LLAMARSE record) */
private Integer record = 0;

/** Orden - asc o desc */
private String sord;

/** Índice de la fila - i.e. click del usuario para ordenar */
private String sidx;

/** campo de búsqueda */
@SuppressWarnings("unused")
private String searchField;

/** cadena de búsqueda*/
private String searchString;

/** La operación de búsqueda
['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
*/
private String searchOper;


private boolean loadonce = false;

public LoadGridCompetitionsAction() {
log= LogFactory.getLog(LoadGridCompetitionsAction.class);
}

@SuppressWarnings({ "unused" })
@Override
@Action(value="/loadGridConcurso",
results={
@Result(type = "json"),
@Result(name="error", type="redirect", location="/commons/
sessionExpired.jsp")
}
)
public String execute() throws Exception {
log.debug("entra al metodo execute.............");
if(sesion.size()==0)
return ERROR;
else{
/*
****************************************************************************************
* ************************Optimizacion de codigo
*****************************************
*
****************************************************************************************/

CompetitionBO competitionBO=new CompetitionBO();

//llena la lista con todos los concursos de la tabla
log.debug("buid new competition List");
myCompetition=competitionBO.buildList();

// Ordena la lista por nombre
if(getSord()!=null && getSord().equalsIgnoreCase("asc"))
Collections.sort(myCompetition);
if(getSord()!=null && getSord().equalsIgnoreCase("desc")){
Collections.sort(myCompetition);
Collections.reverse(myCompetition);
}

//Obtiene el numero de registros
setRecord(competitionBO.myCompetitionCount(myCompetition));

//Calcula HASTA qué registro será la consulta
int to=(getRows() * getPage());
//Calcula DESDE qué registro se hará la consulta
int from= (to - getRows());

//Si la variable "to" sobrepasa el número de registros
disponible,
//entonces le ponemos ese valor máximo de registros.
if(to > getRecord())
to=getRecord();

//Si se van a mostrar todos los registros en una sola pagina
if(loadonce)
setGridModel(myCompetition);
else
{
// Busquedas (filtrado de registros)
if(searchString != null && searchOper !=null)
{
int id=Integer.parseInt(searchString);

/*
* Implementar metodos para realizar las busquedas
* "eq", "ne", "lt", "gt"
*/
}
else //Muestra todos los registros dividido por paginas

setGridModel(competitionBO.getCompetitionGridList(myCompetition,from,
to));
}

//Establece el total de paginas a mostrar
setTotal((int)Math.ceil((double)getRecord()/(double)
getRows()));

return SUCCESS;
}
}

public void setSession(Map<String, Object> session) {
sesion=session;
}

public String getJSON() throws Exception{
return execute();
}

/*
* Getters and Setters
*/
/**
* @return how many rows we want to have into the grid
*/
public Integer getRows()
{
return rows;
}

/**
* @param rows
* how many rows we want to have into the grid
*/
public void setRows(Integer rows)
{
this.rows = rows;
}

/**
* @return current page of the query
*/
public Integer getPage()
{
return page;
}

/**
* @param page
* current page of the query
*/
public void setPage(Integer page)
{
this.page = page;
}

/**
* @return total pages for the query
*/
public Integer getTotal()
{
return total;
}

/**
* @param total
* total pages for the query
*/
public void setTotal(Integer total)
{
this.total = total;
}

/**
* @return total number of records for the query. e.g. select
count(*) from
* table
*/
public Integer getRecord()
{
return record;
}

/**
* @param record
* total number of records for the query. e.g. select
count(*) from
* table
*/
public void setRecord(Integer record)
{

this.record = record;

if (this.record > 0 && this.rows > 0)
{
this.total = (int) Math.ceil((double) this.record / (double)
this.rows);
}
else
{
this.total = 0;
}
}

/**
* @return an collection that contains the actual data
*/
public List<CompetitionBean> getGridModel()
{
return gridModel;
}

/**
* @param gridModel
* an collection that contains the actual data
*/
public void setGridModel(List<CompetitionBean> gridModel)
{
this.gridModel = gridModel;
}

/**
* @return sorting order
*/
public String getSord()
{
return sord;
}

/**
* @param sord
* sorting order
*/
public void setSord(String sord)
{
this.sord = sord;
}

/**
* @return get index row - i.e. user click to sort.
*/
public String getSidx()
{
return sidx;
}

/**
* @param sidx
* get index row - i.e. user click to sort.
*/
public void setSidx(String sidx)
{
this.sidx = sidx;
}

public void setSearchField(String searchField)
{
this.searchField = searchField;
}

public void setSearchString(String searchString)
{
this.searchString = searchString;
}

public void setSearchOper(String searchOper)
{
this.searchOper = searchOper;
}

public void setLoadonce(boolean loadonce)
{
this.loadonce = loadonce;
}

public String getErrmsg() {
return errmsg;
}

public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}

}
********************************************************************************************

********************************************************************************************
another action to update the cell and save the change in database
********************************************************************************************
package com.gemalto.xcelerator.tt.actions.competition;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;

import com.gemalto.xcelerator.tt.bos.competition.CompetitionBO;
import com.opensymphony.xwork2.ActionSupport;

// TODO: Auto-generated Javadoc
/**
* The Class EditCompetitionStatusAction.
*
* Action to manage the status competition update
*/
@SuppressWarnings("serial")
@Namespace(value="/concurso")
public class EditCompetitionStatusAction extends ActionSupport
implements
SessionAware {

/** The status. */
private int status;

/** The id. */
private int id;

/** The log. */
private Log log;

/** The sesion. */
private Map<String, Object> sesion;

/**
* Instantiates a new edits the competition status action.
*/
public EditCompetitionStatusAction() {
log=LogFactory.getLog(EditCompetitionStatusAction.class);
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.ActionSupport#execute()
*/
@Override
@Action(value="editCompetitionStatus",
results={
@Result(location="/concurso/AdmonConcurso.jsp"),
@Result(name="error", location="/concurso/errorMsg.jsp"),
@Result(name="input", type="redirect", location="/concurso/
AdmonConcurso.jsp")
}
)
public String execute() throws Exception {
if(new CompetitionBO().getTotalCompActive() >= 4 && status==2){
addActionError("mensaje de error");
addActionMessage("hola de nuevo");
return INPUT;
}else{
log.info("actualizando el status del concurso: "+id
+"\nestableciendo status: "+status);
new CompetitionBO().updateStatusById(id,status);
return SUCCESS;
}
}

/* (non-Javadoc)
* @see
org.apache.struts2.interceptor.SessionAware#setSession(java.util.Map)
*/
public void setSession(Map<String, Object> map) {
sesion=map;
}

/*
* Getters and setters
*/
/**
* Gets the status.
*
* @return the status
*/
public int getStatus() {
return status;
}

/**
* Sets the status.
*
* @param status the new status
*/
public void setStatus(int status) {
this.status = status;
}

/**
* Gets the id.
*
* @return the id
*/
public int getId() {
return id;
}

/**
* Sets the id.
*
* @param id the new id
*/
public void setId(int id) {
this.id = id;
}
}
********************************************************************************************

I think that don't respect the result INPUT but I don't know why.

do you see any error in my code?

tanks so much!


On Jun 12, 7:52 am, Alexandre Bizeau <alexandrebiz...@gmail.com>
wrote:
> Hello,
>
> When you add or edit a row, are you using the small icon in the grid or a
> custom action on a button ? In your code, if you have a method to save your
> data, try to return INPUT and in your action.xml, do the <result
> name="input>/NameOfCurrentPage.jsp</result> and the actionMessage will
> show. On my grid, that work well. Because I'm reload the page and not just
> the grid.
>
> If you press little button that open an edit dialog, you can maybe use this
> :
>
> http://stackoverflow.com/questions/6791463/jquery-jqgrid-show-message...
>
> For inline edit you can use this :
>
> http://stackoverflow.com/questions/1674320/how-can-i-trigger-the-jqgr...
>
> and with the options "loadingText" of the grid, you can maybe change it
> dynamically. So you can prompt it for a certain amount of time or something
> like that. I really dont know what you really want. But maybe some one
> have  a better way than mine. For me, i'm always using ActionMessage.
>
> Have a nice day,
>
> Alex
>
> 2012/6/12 Cesar Lopez <cesar.lop...@gmail.com>
>
>
>
>
>
>
>
> > Hi Alexandre!
>
> > Tank you for you response, but I tried to add an actionerrror but  the
> > message doesn't show. I think that is because the action only reload the
> > grid but not the page.
>
> > do you know another way to show a error or information message after edit
> > a row/cell?
>
> > On Monday, June 11, 2012 1:13:56 PM UTC-5, Alexandre bizeau wrote:
>
> >> Hello cesar,
>
> >> I'm using ActionMessage. In my java class, i'm startint with :
> >> clearErrorsAndMessages(); to clear every message already added to the .jsp
> >> page.
>
> >> and after there 2 kind of message :
>
> >> addActionError("Hello world.");
>
> >> and
>
> >> addActionMessage("World Hello");
>
> >> Those 2 need to be read into jsp page so use : <p> <s:actionerror /></p>
> >> or/and <s:actionmessage />
>
> >> And there you go ! Beautiful message into your page.
>
> >> There a nice example (With css modify) :http://www.mkyong.com/struts2/**
> >> struts-2-actionerror-**actionmessage-example/<http://www.mkyong.com/struts2/struts-2-actionerror-actionmessage-exam...>
>
> >> and there java documentation :http://www.opensymphony.com/**
> >> webwork/api/com/opensymphony/**xwork/ActionSupport.html<http://www.opensymphony.com/webwork/api/com/opensymphony/xwork/Action...>

Cesar Lopez

unread,
Jun 12, 2012, 10:57:25 AM6/12/12
to struts2...@googlegroups.com
Hi! jogep its exactly that I want to do.

but where can I see or get the source of jsp and action code to build The Grid Showcase[1]?

Alexandre Bizeau

unread,
Jun 12, 2012, 11:03:43 AM6/12/12
to struts2...@googlegroups.com
Hello cesar,

I'm not using annotation so I'm not really sure what to do but maybe this one of this :


 @Action(value="
editCompetitionStatus",
                       results={
                               @Result(location="/concurso/AdmonConcurso.jsp"),
                               @Result(name="error", location="/concurso/errorMsg.jsp"),
                               @Result(name="input", type="redirectAction", location="
loadGridConcurso")

It loadGridConcurso or editCompetitionStatus, for the redirectAction.

Else try without the type, because you don't want a redirection but only a page reload.

@Result(name="input", location="/concurso/
AdmonConcurso.jsp")

I'm really not sure, but you're code look good for the rest.

Alex



2012/6/12 Cesar Lopez <cesar....@gmail.com>
Hi! Alexandre

Cesar Lopez

unread,
Jun 12, 2012, 3:34:33 PM6/12/12
to struts2...@googlegroups.com
Hi! Alexandre

Thank you so much for help me.

with your and jogep's help I revolved my problem :)

I change the action that load the data, just add the action that edits row in the same class that loads the grid and changes my results:
 
@Action(value="editCompetitionData",
            results={
                @Result(name="success", type="json"),
                @Result(name="error", location="/concurso/errorMsg.jsp")
            }
           )
    public String editData(){

        if(new CompetitionBO().getTotalCompActive() >= 4 && status==2){
            errmsg="ERROR : No puede haber mas de 4 concursos activos";
            return ERROR;
        }
        else{
            new CompetitionBO().updateStatusById(id,status);
            return SUCCESS;
        }       
    }

the jsp error to show is:
<%@taglib prefix="s" uri="/struts-tags" %>
<s:property value="errmsg"/>

and I modify the jsp that contains the grid and I add a script:

<script type="text/javascript">
        function isError(text) {           
            if(text.indexOf('ERROR') >= 0) {
                return [false, text];
            }           
            return [true,''];
        }
</script>

and the grid:

<sjg:grid
                id="gridTable"
                caption="Concursos"
                dataType="json"
                href="%{remoteurl}"
                pager="true"
                gridModel="gridModel"
                rowList="10,15,25"

                rowNum="10"
                rownumbers="true"   
                width="900"   
                editinline="false"
                editurl="%{editcellurl}"
                navigator="true"               
                navigatorEdit="true"
                navigatorEditOptions="{
                    height:280,
                    reloadAfterSubmit:true,
                    afterSubmit:function(response, postdata) {
                                    return isError(response.responseText);

                                 }
                }"                                           
            >           
                <sjg:gridColumn name="id" index="id" title="no. Concurso" sortable="false" width="105" />
                <sjg:gridColumn name="nombre" index="nombre" title="nombre del concurso" sortable="true" width="335" />
                <sjg:gridColumn name="fechaIni" index="fechaIni" title="Fecha propuesta" sortable="false" width="115"
                    formatter="date"
                    formatoptions="{newformat : 'd-m-Y', srcformat : 'Y-m-d H:i:s'}"
                />
                <sjg:gridColumn name="fechaFin" index="fechaFin" title="Fecha limite" sortable="false" width="115"
                     formatter="date"
                    formatoptions="{newformat : 'd-m-Y', srcformat : 'Y-m-d H:i:s'}"
                />
                <sjg:gridColumn name="diasRest" index="diasRest" title="Días restantes" sortable="false" width="120" />
                <sjg:gridColumn name="responsableArea" index="responsableArea" title="Responsable de Area" sortable="false" />
                <sjg:gridColumn name="status" index="status" title="Estado" sortable="false" width="100"
                    editable="true"
                    edittype="select"
                    editoptions="{value:'1:Espera;2:Activo;3:Concluido'}"
                />
               
            </sjg:grid>

now my Grid woks OK.

Thank you for all.

have a great day.
2012/6/12 Cesar Lopez <cesar....@gmail.com>
> > To post to this group, send email to struts2-jquery@googlegroups.com.

> > To unsubscribe from this group, send email to

> > For more options, visit this group at
> >http://groups.google.com/group/struts2-jquery?hl=en.

--
You received this message because you are subscribed to the Google Groups "struts2-jquery" group.
To post to this group, send email to struts2-jquery@googlegroups.com.
To unsubscribe from this group, send email to struts2-jquery+unsubscribe@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages