How To Properly Update Components in a Form - ajax

I have a bunch of panels in my form which display images but i have a problem with getting the images to update(load next set of images) with a click of a button. I have tried using the ajax="false" method but this erases the all the variables in the form e.g(the urls used to load the images ) This is my button:
<div style="position : absolute; right:400px; top:1500px" >
<p:commandButton value="Confirm" id="Confirm" actionListener="#{con.confirmButton}" oncomplete="PF('panelP').hide()" ajax="false" />
</div>
The panels and Confirm button are stored in the form like:
<h:form id="form">
<p:galleria id= "ISSimage" style="position : absolute; left:50px; top:550px" value="#{con.gallery}" var="image" panelWidth="500" panelHeight="313" showCaption="true">
<p:graphicImage value="#{image}" alt="Image Description for #{image}" title="#{image}"/>
</p:galleria>
<f:view contentType="text/html">
<p:panel id="satImage" style="position : absolute; right:50px; top:550px" panelWidth="500" panelHeight="400">
<p:gmap id="satview" center="#{con.lati}, #{con.longi}" zoom="6" type="SATELLITE" style="width:600px;height:400px" model="#{con.simpleModel}" />
</p:panel>
</f:view>
I try to store a list of all the image
Is there a way to properly load the next set of images with the click of the confirm button without erasing the image variables?
MY BEAN is 300 lines so i only limited to showing the relevant parts . here it is:
public void confirmButton(ActionEvent actionEvent){
//setting Next Image
//add the point depending on which panels are open then reset the panel booelan values
gallery = new ArrayList<String>();
candidates = new ArrayList<String>();
Connection conn = null;
PreparedStatement stmt = null;
//Statement stmt1 = null;
ResultSet rs = null;
//gallery.clear();
try{
gallery = new ArrayList<String>();
conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
stmt = conn.prepareStatement(op);
//stmt.setString(1, oldconsole);
//stmt.setString(2, oldconsole);
stmt.setDouble(1, oldlati);
stmt.executeUpdate();
stmt = conn.prepareStatement("SELECT * FROM `ISS` WHERE taskinfo__citylat = (SELECT taskinfo__citylat FROM `ISS` LIMIT ?,1)");
int rdmnum = randomise();
stmt.setInt(1, rdmnum);
rs = stmt.executeQuery();
while(rs.next()){
String issimg=rs.getString("taskinfo__link_small");
gallery.add(issimg);
//ADDS IMAGES TO GALLERIA
excl_num = rs.getInt("rownum");
excluded.add(excl_num);
//ADDS ROWNUMBERS TO EXCLUDED ARRAY SO THEY DONT GET CALLED AGAIN.
lati = rs.getFloat("taskinfo__citylat");
longi = rs.getFloat("taskinfo__citylon");
oldlati=lati;
}
catch(SQLException e){
System.err.println(e);
}
public float getLati(){
return lati;
}
public float getLongi(){
return longi;
}
public double getOldlati(){
return oldlati;
}
public double getOldlongi(){
return oldlongi;
}

Related

Conversion of Visualforce page into LWC

Need help to convert my following VF page into LWC
VF code:
<apex:page showHeader="true" sidebar="true" controller="OrgWideOppBidContrl">
<apex:form >
<apex:pageBlock >
<apex:pageMessages id="pagMsg"/>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputText value="From" style="padding-top:5px;"/>
<apex:inputField value="{!opp.StartDate__c}" required="true"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText value="To" style="padding-top:5px;"/>
<apex:inputField value="{!opp.EstimatedHarvestDate__c}" required="true"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:commandButton value="start Batch " action="{!startBatchJob}" style="margin-left:500px;" reRender="pagMsg"/>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex code:
public with sharing class OrgWideOppBidContrl {
public Opportunity opp{get;set;}
public OrgWideOppBidContrl(){
opp = new Opportunity();
opp.StartDate__c = Date.today();
opp.EstimatedHarvestDate__c = Date.today();
}
public PageReference startBatchJob(){
OrgWideOpportunityBidSetting__c orgwideOppBidSett = OrgWideOpportunityBidSetting__c.getInstance('OrgWideOppBid');
if(orgwideOppBidSett == null){
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,'OrgWideOppBid not found'));
return null;
}
if(orgwideOppBidSett.InProgress__c == true){
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.WARNING,'Please wait Batch job for Org Wide Opportunity Bid is already in progress'));
return null;
}
String queryString = 'Select id From OrgWideMatch__c';
Database.executeBatch(new BatchExecutor(new DeleteOrgWideMatchData(), queryString, null), 1000);
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,'Batch job for Org Wide Opportunity Bid is started successfully'));
orgwideOppBidSett.InProgress__c = true;
orgwideOppBidSett.startDate__c = opp.StartDate__c;
orgwideOppBidSett.EndDate__c = opp.EstimatedHarvestDate__c;
update orgwideOppBidSett;
return null;
}
}

cant able to test file extension on test class?

visuaforce page:
<apex:page sidebar="false" controller="UploadOpportunityScheduleLineItem123">
<apex:form >
<apex:sectionHeader title="Upload data from CSV file"/>
<apex:pagemessages />
<center>
<apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
<apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
<br/> <br/>
</center>
</apex:form>
</apex:page>
apex:
public with sharing class UploadOpportunityScheduleLineItem123{
// Global variables
public string nameFile{get;set;}
Public Id parentId{get;set;}
public Blob contentFile{get;set;}
List<account> lstScheduleToUpdate = new List<account>();
public account objSchedule{get;set;}
//String array for taking csv data by line.
String[] filelines = new String[]{};
//set for storing all id's from csv.
set<String> opptoupload{get;set;}
//Main constructor
public UploadOpportunityScheduleLineItem123()
{
//Initalizing required objects.
objSchedule = new account();
opptoupload = new set<String>();
}
//Method to read file content and check extension and file format.
public Pagereference ReadFile()
{
parentId=Apexpages.currentPage().getParameters().get('ParentId');
//If without selecting csv file you clicked on upload it will give error message.
if(nameFile == null)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'You should select csv file to upload');
ApexPages.addMessage(errormsg);
return null;
}
//Taking file extension.
String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
//Checking if file extension is .csv.
if(extension == 'csv' ||extension == 'CSV')
{
nameFile =blobToString( contentFile,'ISO-8859-1');
//Spliting by new line
filelines = nameFile.split('\n');
//Spliting values by (,) for checking coloumn size
for (Integer i=1;i<filelines.size();i++){
String[] inputconvalues = new String[]{};
inputconvalues = filelines[i].split(',');
account b = new account();
b.name= inputconvalues[0];
b.billingcountry = inputconvalues[1];
b.billingcity = inputconvalues[2];
lstScheduleToUpdate.add(b);
}
//Checking if list is not empty then updating.
if(lstScheduleToUpdate.Size()>0)
{
insert lstScheduleToUpdate;
}
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.info,'Batches File uploaded successfully');
ApexPages.addMessage(errormsg);
return null;
}
//If file is not csv type then it will give error message.
else
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'File type should be csv type');
ApexPages.addMessage(errormsg);
return null;
}
}
public static String blobToString(Blob input, String inCharset){
String hex = EncodingUtil.convertToHex(input);
System.assertEquals(0, hex.length() & 1);
final Integer bytesCount = hex.length() >> 1;
String[] bytes = new String[bytesCount];
for(Integer i = 0; i < bytesCount; ++i)
bytes[i] = hex.mid(i << 1, 2);
return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
}
}
test class :
#IsTest(SeeAllData=true)
private class testexceltoaccount
{
static testmethod void testLoadData() {
StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload1'];
UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
testUpload.contentFile= testdoc.Body;
testUpload.ReadFile();
}
}
Cant able to cross this section of code in code coverage :
String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
//Checking if file extension is .csv.
if(extension == 'csv' ||extension == 'CSV')
{
I tried many possible to cross code coverage but still it is at that point .Please help me in this regard.
Thanks in advance
When we use apex:inputFile on VF page and upload any file, then name of file is automatically update field into the field specified in filename attribute, but when you are writing test class you only specifying content of file
testUpload.contentFile= testdoc.Body;
You should add name in nameFile global variable manually
testUpload.nameFile= 'test.csv';
#IsTest(SeeAllData=true)
private class testexceltoaccount
{
static testmethod void testLoadData() {
StaticResource testdoc = [Select Id,Body,Name from StaticResource where name ='testMethodCSVUpload1'];
UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
testUpload.contentFile= testdoc.Body;
testUpload.nameFile= 'test.csv';
testUpload.ReadFile();
}
}

Is there any way to replace Response.Write?

My problem is, I have the following function:
function change_tarif(param) {
var arrTarif = <% Response.Write(Session["Tarif"]); %>
.....
}
Session["Tarif"] - contains multidimensional array List and when I'm loading my page it's giving this Error that
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
When I delete <% Response.Write(Session["Tarif"]); %> it doesn't give this error. So, how can I replace this code to get array List from Session["Tarif"] without using the code blocks <% %>?
This is my Array List code in C#:
public void getTarifList()
{
int intRows = 0;
string strTarif = "null";
Session["Tarif"] = "null";
SqlCommand cmdTarif = new SqlCommand("sp_SIMPay_GetTarifList");
cmdTarif.CommandType = CommandType.StoredProcedure;
DataTable dtTarif = SQL.GetData(cmdTarif);
if (dtTarif.Rows.Count > 0)
{
intRows = dtTarif.Rows.Count;
strTarif = "new Array(" + intRows + ");";
int intIndex = 0;
foreach (DataRow dRows in dtTarif.Rows)
{
strTarif += "arrTarif[" + intIndex + "] = new Array('" + dRows["TarifName"] + "', '" + dRows["ProviderID"] + "', '" + dRows["CodeID"] + "');";
intIndex++;
}
}
else
{
strTarif = "null";
}
Session["Tarif"] = strTarif;
}
My full script:
function change_tarif(param) {
var arrTarif = <% Response.Write(Session["Tarif"]); %>
var select = document.getElementById('TarifList');
var i = 0;
if (arrTarif != null) {
for (i = 0; i < arrTarif.length; i++) {
if (arrTarif[i][1] == '98' && param == '98') {
clear_tarif();
select.options[select.options.length] = new Option('' + arrTarif[i][0] + '', '' + arrTarif[i][2] + '');
break;
}
else {
clear_tarif();
select.options[select.options.length] = new Option('Default Tarif', '');
}
}
}
}
This happens because somewhere in your page code you do something like (just an example - it doesn't matter that it's a Label here, any dynamically added/removed control would trigger the error):
Label lbl = new Label ();
lbl.Xxxx = ...;
Controls.Add ( lbl ); // this is what triggers your issue
When you have <%= ... %> in the same container where you also try to dynamically add controls through the use of the Controls collection of that container (Page, Panel, etc.), you'll get that error that you saw.
If you can, try to remove the code that dynamically adds/removes the control to the container (the same container where you have the <%= ... %> and then your <%= ... %> block will start working.
To remove the dynamic logic that adds/removes control(s), simply put those controls into the container like any other control, like
<asp:Label runat="server" id="lbl" ... />
and then simply show/hide the control when you need it. This way the control is always present in the page, you won't have to add/remove it during run-time and then you can have code blocks in the same container.
Here's a quick example that would create this error:
...
<div runat="server" id="div1">
<asp:Label runat="server" id="lbl1" /><br />
<span>Name: <%= Session["name"] %></span>
</div>
...
// in code-behind
protected override void OnLoad ( EventArgs e )
{
Label lbl2 = new Label ();
lbl2.Text = "Time: " + DateTime.Now.ToString ();
// Error: you cannot modify the Controls collection if
// the same control contains code blocks
div1.Controls.Add ( lbl2 );
}
You can use Expression (Equivalent to Response.Write()).
function change_tarif(param) {
var arrTarif = <%= Session["Tarif"] %>;
}
EDIT : I've customized your code,
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
getTarifList();
}
public void getTarifList()
{
Session["Tarif"] = "null";
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Array(" + 3 + ");");
for(int i=0;i<3;i++)
{
sb.AppendLine("arrTarif[" + i + "] = new Array('A" + i + "', 'B" + i + "', 'C" + i + "');");
}
Session["Tarif"] = sb.ToString();
}
And markup,
<script type="text/javascript">
function change_tarif(param){
var arrTarif = <% Response.Write(Session["Tarif"]); %>
return arrTarif;
}
console.log(change_tarif('test'));
</script>

edit datatable with code in managedBean jsf2 primefaces

I have a datatable which I want to edit the value of their component by programing when the user check or uncheck one of their chceckbox
here is the datatable :
<p:dataTable var="car" style="width: 270px;margin-top: 15px;margin-left: 60px" binding="#{editCommandController.hd}" value="#{editCommandController.lp}" id="carList" editable="true">
<f:facet name="header">
Stock Papiers
</f:facet>
<p:column headerText="Libéllé" style="width:70px">
<h:outputText value="#{car.libelle}" style="width: 70px;" label="Year"/>
</p:column>
<p:column headerText="Stock" style="width:40px">
<h:outputText value="#{car.stock}" label="Year"/>
</p:column>
<p:column headerText="Choisir" style="width:40px;margin: auto;">
<p:selectBooleanCheckbox id="karim" binding="#{editCommandController.tmp}" value="#{car.checked}" disabled="#{editCommandController.result gt car.stock}" >
<p:ajax listener="#{editCommandController.checkListener}"/>
</p:selectBooleanCheckbox>
</p:column>
</p:dataTable>
and here is the managedBean :
public void checkListener(AjaxBehaviorEvent e) {
System.out.println("je suis "+e.getComponent().getClientId()+" utilisé : et tmp :" );
List<Papier> lp1;
lp1 = new ArrayList();
lp1 = (List<Papier>) getHd().getValue();
// getHd().se
System.out.println("lp1.size() : "+lp1.size());
Boolean a = true;
System.out.println("ce bool a = "+a);
for(int i = 0 ; i< lp1.size();i++){
System.out.println("alors le cheched est : "+lp1.get(i).getChecked());
if(lp1.get(i).getChecked()){
if(lastChecked != null){
for(int j = 0;j<lp1.size();j++){
if(lp1.get(j).getId().equals(lastChecked)){
lp1.get(j).setChecked(false);
break;
}
}
lastChecked = lp1.get(i).getId();
}else{
lastChecked = lp1.get(i).getId();
}
}
}
System.out.println("avant d'affecter voila ce quilya : ");
for(int i = 0 ; i< lp1.size();i++){
System.out.println("alors le cheched n "+i+" est : "+lp1.get(i).getChecked());
}
org.primefaces.component.datatable.DataTable editdt = new DataTable();
editdt.setValue(lp1);
setHd(editdt);
//getHd().setValue(lp1);
}
also in the managedBean I have :
private org.primefaces.component.datatable.DataTable hd;
public org.primefaces.component.datatable.DataTable getHd() {
return hd;
}
public void setHd(org.primefaces.component.datatable.DataTable hd) {
this.hd = hd;
}
like you see above, I use the binding attribute to link the datatable with the managedBean but when I use
org.primefaces.component.datatable.DataTable editdt = new DataTable();
editdt.setValue(lp1);
setHd(editdt);
//getHd().setValue(lp1);
I don't see my changes on the datatable
do you have any idea
thanks
You're not updating your datatable on the client side to reflect the changes you made on the server side. Refresh the datatable via ajax using update= "carList" to the ajax event.

ajax to populate an input type text

I have an <input> of type text that I want to populate with a value from a database using AJAX.
First, I define my text zone like the following:
<td><input type=text id='st' value=" " name='stname' onclick="donnom();" /></td>
In javascript, I do the following:
xhr5.onreadystatechange = function(){
if(xhr5.readyState == 4 && xhr5.status == 200) {
selects5 = xhr5.responseText;
// On se sert de innerHTML pour rajouter les options a la liste
document.getElementById('st').innerHTML = selects5;
}
};
xhr5.open("POST", "ajaxIDentifier5.jsp", true);
xhr5.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
id = document.getElementById(idIdden).value;
xhr5.send("id=" + id);
In IDentifier5.jsp, I put the next code:
<%
String id = request.getParameter("id");
System.out.println("idDailyTimeSheet ajaxIDentifier5 as is:" + id);
Session s = null;
Transaction tx;
try {
s = HibernateUtil.currentSession();
tx = s.beginTransaction();
Query query = s.createQuery(
"select from Dailytimesheet dailytimesheet " +
"where dailytimesheet.IdDailyTimeSheet=" + id + " ");
for(Iterator it=query.iterate();it.hasNext();) {
if(it.hasNext()) {
Dailytimesheet object=(Dailytimesheet)it.next();
out.print( "<input type=\"text\" id=\"st1\" value=\"" +
object.getTimeFrom() +
"\" name=\"starting\" onclick=\"donnom()\" ></input>");
}
}
} catch (HibernateException e) {
e.printStackTrace();
}
%>
I want to get only the value in the input type text populated from database, because after that I will be able to change it.
Obviously, your query returns only one result (WHERE ID = ...) that you want to put in your textfield.
Strange things:
The page you are calling via AJAX is priting HTML code, but your are trying to use it as the innerHTML of a element.
It seems you want to add an input more than populating an existing one. Why has it different id/name ?
Maybe instead of :
document.getElementById('st').innerHTML = selects5;
You want to do :
document.getElementById('st').value = selects5;
But then you will need to return only the result of the query in your JSP, not HTML code :
out.print(object.getTimeFrom());

Resources