Conversion of Visualforce page into LWC - visualforce

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;
}
}

Related

How To Properly Update Components in a Form

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;
}

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();
}
}

Reset mx:hslider value

I am new to flex and my question is how to reset mx hslider value with "reset" button.
here is a sample script:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.SliderEvent;
private var txtvalue:int = 0;
protected function Focal_changeHandler(event:SliderEvent):void
{
txtvalue = Focal.value;
if(txtvalue == 0)
Slider_txt.text = "Low";
if(txtvalue == 1)
Slider_txt.text = "Middle";
if(txtvalue == 2)
Slider_txt.text = "High";
}
]]>
</fx:Script>
<mx:HSlider id="Focal" x="476" y="345" maximum="2" minimum="0" value="0" buttonMode="true" enabled="true" snapInterval="1" tickInterval="1" allowTrackClick="true" liveDragging="true" change="Focal_changeHandler(event)"/>
<s:Label id="Slider_txt" x="472" y="319" text= "Low"/>
<s:Button x="476" y="459" label="Reset" id="Res_btn"/>
</s:Application>
Normally you could do
<s:Button x="476" y="459" label="Reset" id="Res_btn" click="{Focal.value = 0}"/>
But since you'd need to update the text as well, it's better to do an own method for that:
<s:Button x="476" y="459" label="Reset" id="Res_btn" click="onResetClick()"/>
and in your code part:
protected function Focal_changeHandler(event:SliderEvent):void
{
updateSliderText();
}
private function onResetClick():void
{
Focal.value = 0;
updateSliderText();
}
private function updateSliderText():void
{
txtvalue = Focal.value;
if (txtvalue == 0)
Slider_txt.text = "Low";
if (txtvalue == 1)
Slider_txt.text = "Middle";
if (txtvalue == 2)
Slider_txt.text = "High";
}

How to find XElement specific Children (in c# with LINQ)?

I've got an XML file like this :
<root>
<environment env="PROD">
<key name="Big Key" propagate="true" value="21" />
</environment>
<environment env="PRE-PROD">
<key name="First Key" propagate="true" value="4" />
<key name="Second Key" propagate="true" value="3" />
</environment>
</root>
I want to check if a key exist in that file, and if the propagate item is true.
I manage to get those 2 System.Xml.Linq.XElement : key name="First Key" AND key name="Second Key".
but I would like to get only the one by pKeyname (like "Second Key" for eg.) I can't find how...
public static bool IsPropagate(string pXmlFileName, string pEnvironment, string pKeyname)
{
var doc = XElement.Load(pXmlFileName);
IEnumerable<XElement> childList = doc.Elements("environment")
.Where(elt => elt.Attribute("env").Value == pEnvironment)
.Elements();
if (childList.Any())
return true;
return false;
}
Any help would be highly appreciated!
This would help to get the exact key:
public static bool IsPropagate(string pXmlFileName, string pEnvironment,
string pKeyname)
{
var doc = XElement.Load(pXmlFileName);
IEnumerable<XElement> childList = doc.Elements("environment")
.Where(elt => elt.Attribute("env").Value == pEnvironment)
.Elements()
.Where(a => a.Attribute("name").Value == pKeyname);
if (childList.Any())
return true;
return false;
}
It's working by adding the "FirstOrDefault"! Thanks.
public static bool IsPropagate(string pXmlFileName, string pEnvironment, string pKeyname)
{
var doc = XElement.Load(pXmlFileName);
XElement child = doc.Elements("environment")
.Where(elt => elt.Attribute("env").Value == pEnvironment)
.Elements()
.FirstOrDefault(a => a.Attribute("name").Value == pKeyname);
if (child != null)
return true;
return false;
}

struts 2 checkboxlist validation question

I have struts 2 checkboxlist as followed:
<s:checkboxlist list="listOfOptions" name="someName" />
I would like to add validation to make sure that at least ONE of the checkboxes has been checked. Any thoughts?
Thanks
I use JS to do that.
<sx:submit
id="button_submit"
name="button_submit"
onclick="return validateNotEmptyCheckbox();" />
And JS:
function validateNotEmptyCheckbox() {
var checkboxes = document.getElementsByTagName('input');
for (i = 0; i < arguments.length; i++) {
var fieldName = arguments[i];
var atLeastOne = false;
for (j = 0; j < checkboxes.length; j++) {
if ((checkboxes[j].type == "checkbox" || checkboxes[j].type == "radio")
&& checkboxes[j].name == fieldName
&& checkboxes[j].checked == true)
atLeastOne = true;
}
if (atLeastOne == false) {
alert("Choose one!!!");
return false;
}
}
}
Also for radio buttons, as you can see.
I made an validation method on the action to whom the form is submitted.
deliveryTimesInputList is here the list of integer with the values from the checkboxlist.
#Override
public void validate() {
if(deliveryTimesInputList == null || deliveryTimesInputList.isEmpty()){
addFieldError("deliveryTimesInputList", "Du må velge minst et leveringstidspunkt for dette postnummeret");
}
}
Use the following code for struts2 xml validation .The value of checkbox List is stored as a string.Hence,you can use requiredstring.
<field name="someName">
<field-validator type="requiredstring">
<message>You need to select at least one option</message>
</field-validator>
</field>

Resources