please help me to create grid by passing parameters to request action - jqgrid

i am applying struts2 jquery grid.the data in the grid will be generated based on the filter selected values and the jsp will be executed where i have written this code.the data type i am using is json and the action is execution here but i want to pass parameters for this action how can i acheive this without including url in same page.even i tried with type="chain",redirect but i am not getting any grid just json data is displaying
*<s:url id="remoteurl" action="gridaction"/>
<s:url id="editurl" action="editaction"/>
<s:url id="selecturl" action="selectaction"/>*
<sjg:grid id="sjgrid" **dataType="json"** href="%{remoteurl}" caption="Grid Model"
gridModel="gridModel" editurl="%{editurl}"
navigator="true"
navigatorSearch="true"
navigatorSearchOptions="{multipleSearch:true}"
navigatorExtraButtons="{
seperator: {
title : 'seperator'
},
hide : {
title : 'Show/Hide',
icon: 'ui-icon-wrench',
topic: 'showcolumns'
},
alert : {
title : 'Alert',
onclick: function(){ alert('Grid Button clicked!') }
}
}"
loadonce="true"
pager="true"
pagerPosition="center"
rowList="5,10,20"
shrinkToFit="true"
altRows="true"
autowidth="true"
filter="true"
>
<sjg:gridColumn name="iduser" title="iduser" key="true" hidden="true"/>
<sjg:gridColumn name="uname" title="Username" editable="true" align="center"
editrules="{required:true}"
/>
<sjg:gridColumn name="passwd" title="Password" editable="true" align="center"
editrules="{required:true}"
/>
<sjg:gridColumn name="country" title="Country" editable="true" align="center"
edittype="select"
editoptions="{dataUrl:'%{selecturl}'}"
/>
<sjg:gridColumn name="contact" title="Contact No" editable="true" align="center"
editrules="{required:true,number:true,integer:true}"
/>
</sjg:grid>

you have to use formIds attribute:
first create a form with the variables you want to send
second reference this form from sjg:grid with the formIds attribute
in the json action you will have all form variables available

Related

Radzen DataGrid Multiple Selection only filtered Items

I have a Razor Component (.net 6) where I make use of the Radzen DataGrid Multiple Selection.
<RadzenDataGrid
#ref="contactsGrid" Data="#contacts" AllowColumnResize="true" EditMode="DataGridEditMode.Single"
RowUpdate="#OnUpdateRow" RowCreate="#OnCreateRow"
AllowSorting="true" AllowFiltering="true" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
TItem="ContactModel" AllowRowSelectOnRowClick="false" SelectionMode="DataGridSelectionMode.Multiple" #bind-Value=#selectedContacts>
<Columns>
<RadzenDataGridColumn TItem="ContactModel" Width="40px" Sortable="false" Filterable="false">
<HeaderTemplate>
<RadzenCheckBox TriState="false" TValue="bool" Value="#(contacts.Any(i => selectedContacts != null && selectedContacts.Contains(i)))" Change="#(args => selectedContacts = args ? contacts.ToList() : null)" />
</HeaderTemplate>
<Template Context="contacts">
<RadzenCheckBox TriState="false" Value="#(selectedContacts != null && selectedContacts.Contains(contacts))" TValue="bool" Change=#(args => { contactsGrid.SelectRow(contacts); }) />
</Template>
</RadzenDataGridColumn>
<!-- FirstName -->
<RadzenDataGridColumn TItem="ContactModel" Property="FirstName" Title="FirstName">
<EditTemplate Context="contact">
<RadzenTextBox #bind-Value="contact.FirstName" Style="width:100%; display: block" Name="FirstName" />
<RadzenRequiredValidator Text="FirstName is required" Component="FirstName" Popup="true" />
</EditTemplate>
</RadzenDataGridColumn>
<!-- LastName -->
<RadzenDataGridColumn TItem="ContactModel" Property="LastName" Title="LastName">
<EditTemplate Context="contact">
<RadzenTextBox #bind-Value="contact.LastName" Style="width:100%; display: block" Name="LastName" />
<RadzenRequiredValidator Text="LastName is required" Component="LastName" Popup="true" />
</EditTemplate>
</RadzenDataGridColumn>
</Columns>
</RadzenDataGrid>
In the HeaderTemplate you can directly select or deselect all items.
Is it possible to change the function so that only all items are selected that match the filter? i.e. which items are currently displayed when I search for certain items using the filter option?
you can use contactsGrid.View to get visible rows. try to use contactsGrid.View instead of selectedContacts.

Looking for a away to validate pre-submit in jsf [duplicate]

This question already has answers here:
How to perform JSF validation in actionListener or action method?
(5 answers)
Validate email format and uniqueness against DB
(1 answer)
Closed 2 years ago.
I've run into a problem validating a certain input (email) before submitting the whole object..
jsf looks like this:
<h:panelGroup id="reportingRecipientTable">
<table cellspacing="0" class="table no-footer" width="100%" style="word-wrap: break-word;">
<thead>
<tr>
<th><h:inputText p:type="email" p:placeholder="Add a valid Email address" value="#{viewModel.reportingRecipient}"
styleClass="form-control #{component.valid ? '' : 'has-errors'}">
<f:ajax execute="#this" />
</h:inputText></th>
<th class="col-sm-3">
<div class="text-center">
<h:commandLink immediate="true" style="width:95px" styleClass="btn btn-default" actionListener="#{viewModel.addReportingRecipient}">
<i class="icon-plus" /> Add
<f:ajax render="reportingRecipientTable" />
</h:commandLink>
</div>
</th>
</tr>
</thead>
<tbody>
<c:forEach items="#{viewModel.getReportingRecipients()}" var="reportingRecipient">
<tr>
<td><h:outputText required="true" value="#{reportingRecipient}" styleClass="form-control" /></td>
<td class="col-sm-3">
<div class="text-center">
<h:commandLink styleClass="btn btn-default" style="width:95px" actionListener="#{viewModel.removeReportingRecipient(reportingRecipient)}">
<i class="icon-trash" /> Remove
<f:ajax render="reportingRecipientTable" />
</h:commandLink>
</div>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</h:panelGroup>
As you see, I'm adding a (supposedly valid) email address to a tablerow before submitting everything:
public void addReportingRecipient() {
if (!Utils.isNullOrBlank(reportingRecipient) && reportingRecipient.matches("(^.*#.*\\..*$)")) {
getReportingRecipients().add(reportingRecipient);
this.reportingRecipient = "";
} else{ //not valid
}
}
Well, this works (email is only added if it matches the pattern), missing one little detail: I want to mark the "inputText" as invalid (styleClass="form-control #{component.valid ? '' : 'has-errors'}") if it isnt a valid email address. adding a validator to the inputText like this:
<h:inputText p:placeholder="Add a valid Email address" validator = "#{emailValidator.isCorrectEmail}" value="#{viewModel.reportingRecipient}"
styleClass="form-control #{component.valid ? '' : 'has-errors'}">
does only work if i hit the final submit button - but i want to mark the field invalid the moment the user tries to add an invalid email.
Anyone got an idea/some hints?
Your code example of using a validator is the right way to go. Don't validate in business methods.
<h:inputText p:type="email" p:placeholder="Add a valid Email address" value="#{viewModel.reportingRecipient}"
styleClass="form-control #{component.valid ? '' : 'has-errors'}">
<f:ajax execute="#this" />
</h:inputText></th>
Does correctly use #{component.valid...} to style the component. But it does not work on the ajax call because you do not (re)render the input on the ajax event. The default is for an f:ajax is render="#none", so nothing is updated. Adding a render="#this" or if you also want to display a message some other id will make it work.
The fact that it works on 'Remove' button is because the ajax call on the input has already updated the state and you do render the complete table. So the input is (re)renderd.
See also
Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
Validator is called but error message is not displayed
Highlight an inputText in JSF when a validation error occurs

Struts2 AJAX validation doesn't stay on page

I've been trying for a few days now to make Struts2 AJAX validation work but I can't solve one last problem. I'm using the struts2jquery plugin to asynchronously submit my form:
<div id="result"></div>
<s:form action="RegisterUser" theme="xhtml" method="post">
<s:textfield key="firstname" label="First name" size="35"
required="true" />
<s:textfield key="lastname" label="Last name" size="35"
required="true" />
<s:textfield key="address" label="Address" size="35"
required="true" />
<s:textfield key="phone" label="Phone number" size="35" />
<s:textfield key="username" label="Username" size="35"
required="true" />
<s:password key="password" label="Password" size="35"
required="true" />
<s:textfield key="email" label="E-mail address" size="35"
required="true" />
<sj:submit key="Inregistrare" targets="result" align="right"
button="true" validate="true" onSuccessTopics="notifyRegistration" />
</s:form>
I've included the required scripts:
<script type="text/javascript" src="./js/registerScript.js"></script>
<!-- This files are needed for AJAX Validation of XHTML Forms -->
<script src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/struts/xhtml/validation.js"
type="text/javascript"></script>
and the tag:
<sj:head jqueryui="true" />
The onSuccess handler:
$(document).ready(function(){
$.subscribe('notifyRegistration', function(event,data) {
var registrationStatus = event.originalEvent.data.registrationStatus;
if(registrationStatus == 'SUCCESS'){
alert('Contul dumneavoastra a fost creat cu success!');
window.location.href = "./index.html";
} else {
alert('Contul dumneavoastra nu a putut fi creat. Va rugam incercati din nou.');
}
});
});
My configuration looks like this:
<action name="RegisterUser" class="actions.Register" method="execute">
<interceptor-ref name="jsonValidationWorkflowStack"/>
<result name="input">/pages/Register.jsp</result>
<result type="json"/>
</action>
And the execute method of my action class:
public String execute() throws Exception {
if (isInvalid(getUsername()) || isInvalid(getPassword())
|| isInvalid(getEmail())) {
registrationStatus = REGISTRATION_ERROR;
}
if (registerUser()) {
registrationStatus = REGISTRATION_SUCCESS;
return SUCCESS;
}else {
registrationStatus = REGISTRATION_ERROR;
}
return SUCCESS;
}
The registerUser() method makes the actual insert into the database. The validation XML is called Register-Validation.xml.
The validation works fine - if some fields are not filled in, it shows the error labels without refreshing the page. My problem is that even is the action returns SUCCESS or ERROR, the browser displays the JSON that it sent back on another page, ../Register.action. I have no idea why it doesn't enter my onSuccess handler. I've successfully used AJAX on other forms, the only difference here is that I use the validation xml and the jsonValidationWorkflowStack interceptor. Why is this happening and how can I avoid being redirected? Why doesn't the request reach the onSuccess handler?
Do you have getters for registrationStatus in your Action ?
I would put an alert(event.originalEvent.data.registrationStatus); in your notifyRegistration callback function, just to see what is its value.
By the way, it seems that you have mixed
Struts2-jQuery Plugin AJAX Form Validation with Struts2 XHTML Theme
with
Struts2-jQuery Plugin: Remote Link that handle an JSON Result with an onSuccessTopic
AFAIK (but I've never used this specific kind of validation), the validation should not be handled in execute(), but in validate() or through XML, or with Annotations.
The example in Struts2-jQuery Plugin showcase uses Annotations, but you can easily transform it in XML and try the showcase.
You would have no need to use the javascript function nor the onSuccessTopic at all, following the example.
You can run it in the showcase too, under Forms -> Forms with Validation (but stick to the documentation for the code, because the code in the showcase seems to miss some pieces... for example the validation against "test" password).

p:pickList not fetching data after pressing p:commandButton

I have a users list page which holds the users in a p:dataTable and in each row I have an update button that shows a p:dialog popup.
The page and the dialog is managed in view scope (implemented in Spring).
When I press the editUserButton in the main page the popup appears with all data and then I type an invalid string into the fields email and username. The validation message appears, but the picklist is not populated with any value.
What could be the problem?
This is the main page (users list) snippet code:
<ui:composition>
<f:view id="bodyView">
<div id="content_body">
<ui:include src="editUserDialog.xhtml"/>
<h:form id="usersListForm">
<table width="85%" align="center">
<tr>
<td>
<p:dataTable id="usersList" var="user"
value="#{usersController.usersList}"
selectionMode="single"
rowKey="#{user.userId}">
<p:columnGroup type="header">
<p:row>
...
<p:column rowspan="2" headerText="Users"/>
...
</p:row>
</p:columnGroup>
...
<p:column id="users" >
<p:commandLink id="editUserButton" oncomplete="addEditUserConfirmation.show()" actionListener="#{addEditUserController.selectionListener}"
update=":addEditCustomerDialogForm:dialogContent">
<f:attribute value="#{user}" name="selectedUser" />
</p:commandLink>
</p:column>
</p:dataTable>
</td>
</tr>
</table>
<br/>
</h:form>
</div>
</f:view>
This is the p:dialog code:
<ui:composition>
<h:form id="addEditUserDialogForm">
<p:dialog id="addEditUserDialog" severity="alert" widgetVar="addEditUserConfirmation" draggable="true" modal="true"
resizable="false" >
<p:outputPanel id="dialogContent">
<div>
<table cellpadding="5">
<tr>
<td>
<p:inputText value="#{addEditUserController.addEditCustomerBean.userName}"
maxlength="250" size="50" label="user name" id="userName">
<f:validator validatorId="UsernameValidator"/>
</p:inputText>
<p:message for="userName"/>
</td>
</tr>
<tr>
<td>
<p:inputText value="#{addEditUserController.addEditCustomerBean.email}"
maxlength="50" size="50" label="E-mail" id="email">
<f:validator validatorId="EmailValidator"/>
</p:inputText>
<p:message for="email"/>
</td>
</tr>
</table>
<table cellpadding="5">
<tr>
<td>
<p:pickList id="customersList" iconOnly="true"
value="#{addEditUserController.customersList}" var="customer"
itemValue="#{customer.value}" itemLabel="#{customer.label}"/>
</td>
</tr>
</table>
</div>
<div align="right">
<p:commandButton value="#{isNewUser ? 'add' : 'update'}" id="updateUserButton"
actionListener="#{addEditUserController.persistUser}"
update="dialogContent"
styleClass="fiftyone-default-button"
oncomplete="handleRequest(xhr, status, args)"/>
</div>
</p:outputPanel>
</p:dialog>
</h:form>
<script type="text/javascript">
function handleRequest(xhr, status, args) {
if(!(args.validationFailed && args.validationFailed == true)) {
addEditUserConfirmation.hide();
}
}
</script>
This is the backing bean code:
import org.primefaces.model.DualListModel;
import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import java.util.List;
public class AddEditUserController {
private AddEditCustomerBean addEditCustomerBean;
private DualListModel<LabelValueBean> customersList;
// ... constructor getters and setters
public void selectionListener(ActionEvent event) throws Exception {
selectedUser = event.getComponent().getAttributes().get("selectedUser");
// some code
AddEditCustomerBean = new AddEditCustomerBean();
// some code
customersList = getSomeCustomersDualListModel()
}
public void persistUser() throws Exception {
// save user to DB
}
}
First thing I'd do would be to make sure that the method selectionListener is being called (either put a break-point on it or print something and check in the console later).
If it is, you must check if the variable customersList is being updated correctly, if it's not, you probably have a problem with bean scoping.
In your sample code it isn't clear how you are setting the scope for the backing bean, so I assume you're doing it on Spring's XML config file.
Make sure you really have the backing bean in the view scope, by inspecting the contents of the view map: FacesContext.getCurrentInstance().getViewRoot().getViewMap().
Hope it helps!
This is an old question, but I also encountered this issue recently, and now being helpless. Let's see the p:pickList:
<td>
<p:pickList id="customersList" iconOnly="true"
value="#{addEditUserController.customersList}" var="customer"
itemValue="#{customer.value}" itemLabel="#{customer.label}"/>
</td>
We know the [var="customer"] is an iterator, but when validation error happens, this var is assigned to String type, it's odd. When you close this popup then re-populate it again, you will get an error, messages like this: no property label(value) on type of String... the customer var now is a String, so it has no value nor label property.
For now, I use a tricky way, it won't work out always, it depends on your code:
Assume that the value and label are unique, set customersList type of List String, customersList binds the label, find the value of the label when submit at the backend; Why this way can avoid re-populate exception, that's because the iterator is always type of String, no matter validation error occurs or not.
Hope this can help the need.

How do I unhide a CFDIV that has dynamic content with AJAX binding itself?

I have the following CFSELECT tags that are used to populate a text input:
<cfselect id="this" name="this" bind="cfc:Data.getThis()" bindonload="true" />
<cfselect id="that" name="that" bind="cfc:Data.getThat({p1})" />
<cfselect id="theOther" name="theOther" bind="cfc:Data.getTheOther({p1}, {p2})" />
The text input is the only value that needs to be submitted in a form:
<cfform name="addItem" method="post" action="somepage.cfm">
<cfinput
type="text"
id="item"
name="item"
bind="cfc:Data.getResult({this}, {that}, {theOther})" /><br />
<cfinput
type="submit"
name="addButton"
value="Add Item" />
</cfform>
I want the form and it's contents to be visible only when all three selections have been made, and there is a value for the text input. What is the best way to do this? I'm assuming some use of CFDIV is the best way, but I'm not sure how to load the dynamic content (the CFINPUTs) this way.
<cfselect id="this" name="this" bind="cfc:Data.getThis()" bindonload="true" onChange="toggleForm();" />
<cfselect id="that" name="that" bind="cfc:Data.getThat({p1})" onChange="toggleForm();" />
<cfselect id="theOther" name="theOther" bind="cfc:Data.getTheOther({p1}, {p2})" onChange="toggleForm();" />
<div id="theForm" style="display:none">
<cfform name="addItem" method="post" action="somepage.cfm">
<cfinput
type="text"
id="item"
name="item"
bind="cfc:Data.getResult({this}, {that}, {theOther})" /><br />
<cfinput
type="submit"
name="addButton"
value="Add Item" />
</cfform>
</div>
<script type="text/javascript">
function toggleForm(){
var a = document.getElementById("this").selectedIndex;
var b = document.getElementById("that").selectedIndex;
var c = document.getElementById("theOther").selectedIndex;
if (a > -1 && b > -1 && c > -1){
document.getElementById("theForm").style.display = "";
}
}
</script>
Personally I would simplify that JS a bit by using jQuery, but I don't know if you're already using jQuery on your site, and I don't want to be another "use jquery" empty answer; so this should work without jQuery, should you want/need to go without it. (But jQuery is awesome!)

Resources