-
ChatterFeed
-
0Best Answers
-
3Likes Received
-
0Likes Given
-
49Questions
-
40Replies
@Test Class for befor insert
I have wrote the code
trigger updatebody on Property_Obj__c (before update)
{
Property_Obj__c pro= new Property_Obj__c();
List<Property_Obj__c> porpetylsit= new List<Property_Obj__c>();
for (Property_Obj__c newprop: Trigger.new) {
Property_Obj__c oldprop = Trigger.oldMap.get(newprop.Id);
if (oldprop.Counter_No__c != newprop.Counter_No__c) {
Frequency__c frequency = [Select ID, Subject__c, Body__c from Frequency__c where Counter_No__c = : newprop.Counter_No__c];
newprop.Subject__c = frequency.Subject__c;
newprop.Body__c = frequency.Body__c;
}
}
}
But when i run the test class through Ecclipse i get 0 Lines not tested ,100 % covered .But its
giving the error has Multiple markers at this line
- Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is
required
- File only saved locally, not to server
Can you please help out to write the test class for the above trigger
Thanks,
Sailer
- sailer
- February 04, 2014
- Like
- 0
bulkify the code for callout
I worte the code where i am able to connect the endpoint and get the values and update ,and it works awesome.
But i can only 150 DML statement ,so i thought of bulkify
But could not able to get how to add in the list
Code is here
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse(String Acctname,String Ids)
// public static void parseJSONResponse()
{
String AcctNameJson;
system.debug('AccountName______________________________'+AcctName);
String JSONContent = '{"folionum":'+AcctName+'}';
System.debug('JSONContent____________________'+JSONContent);
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'http://abc.xyz.net/api/values';
request.setEndPoint(endpoint);
request.setHeader('content-type', 'application/json; charset=utf-8');
request.setMethod('POST');
// String strbody = '{"folionum":48430721840}';
request.setBody(JSONContent);
HttpResponse response = httpProtocol.send(request);
// String jsonInput = response.getBody(); UCOMMENETED TO READ TEH JSON
JSONParser parser = JSON.createParser(Response.getBody());
system.debug('JSON PARESER___________________'+parser );
system.debug('Respone'+Response.getBody());
double sqft ;
String avgrentpsft ;
String months12pavg ;
String monthsps12ftavg ;
String peakspavg ;
String peakspsftavg ;
while (parser.nextToken() != null)
{
//if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'sqft') &&(parser.getText() == 'avgrentpsft')&&(parser.getText() == '12monthspavg')
//&&(parser.getText() == '12monthspsftavg') &&(parser.getText() == '12monthspsftmax') &&(parser.getText() == 'peakspavg') &&(parser.getText() == 'peakspsftavg'))
//if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'sqft') (parser.getText() == 'sqft'))
if (parser.getCurrentToken() == JSONToken.FIELD_NAME)
{
String text = parser.getText();
parser.nextToken();
if(text == 'sqft')
{
sqft = parser.getDoubleValue();
}else if(text == 'avgrentpsft'){
avgrentpsft=parser.getText();
}
else if(text == '12monthspavg'){
months12pavg =parser.getText();
}
else if(text == '12monthspsftavg'){
monthsps12ftavg =parser.getText();
}
else if(text == '12monthspsftmax'){
monthsps12ftavg=parser.getText();
}
else if(text == 'peakspavg'){
peakspavg=parser.getText();
}
else if(text == 'peakspsftavg'){
peakspsftavg=parser.getText();
}
/* sqft=parser.getDoubleValue();
avgrentpsft=parser.getText();
months12pavg=parser.getText();
monthsps12ftavg=parser.getText();
peakspavg=parser.getText();
peakspsftavg=parser.getText();
parser.nextToken();
*/
}
}
system.debug('TotalAqft' + sqft);
if (response.getStatusCode() == 200) {
//update account
Property_Obj__c acc = new Property_Obj__c(Id=Ids);
acc.Ave_Rent_sf_Per_Area__c =sqft;
acc.Brkr_Remrks_2__c=avgrentpsft;
acc.Garag_Desc__c=months12pavg;
acc.Brkr_Remarks__c=monthsps12ftavg;
acc.city__c=monthsps12ftavg;
acc.DOM__c=peakspavg;
acc.Address__c=peakspsftavg;
update acc;
} else {
System.debug('Callout failed: ' + response);
}
}
}
Please help out .
Regards,
Sailer
- sailer
- January 29, 2014
- Like
- 0
Error while coding the Test Class when calling the method
i am not able to call one method in the test class can you please help me out
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse(String Acctname,String Ids)
// public static void parseJSONResponse()
{
String AcctNameJson;
system.debug('AccountName______________________________'+AcctName);
String JSONContent = '{"folionum":'+AcctName+'}';
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'http://.cloudapp.net/api/values';
request.setEndPoint(endpoint);
request.setHeader('content-type', 'application/json; charset=utf-8');
request.setMethod('POST');
// String strbody = '{"folionum":48430721840}';
request.setBody(JSONContent);
HttpResponse response = httpProtocol.send(request);
// String jsonInput = response.getBody(); UCOMMENETED TO READ TEH JSON
JSONParser parser = JSON.createParser(response.getBody());
system.debug('JSON PARESER___________________'+parser );
system.debug('Respone'+Response.getBody());
String grandTotal ;
while (parser.nextToken() != null)
{
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == '12monthspavg'))
{
parser.nextToken();
grandTotal += parser.getDoubleValue();
}
}
system.debug('Grand total=' + grandTotal);
if (response.getStatusCode() == 200) {
//update account
Account acc = new Account(Id=Ids);
acc.Description =grandTotal ;
update acc;
} else {
System.debug('Callout failed: ' + response);
}
}
}
###################Test Class####################################
@isTest(SeeAlldata=true)
private class E2PPTestClass {
@isTest static void myUnitTest()
{
// TO DO: implement unit test
String Acctname;
String Ids;
List<Account > Acctquery;
Account acct = new Account();
acct.Name='Test';
insert acct;
Acctquery=[Select Id,Name from Account limit 1];
acct.Id =Acct.Id;
acct.Name='Test';
Test.startTest();
Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock());
HttpResponse res = JSONParserUtil.parseJSONResponse(Acctname, Ids);//I am getting the Error here ave error: Illegal assignment from void to System.HttpResponse
Test.stopTest();
}
}
Please help me out
Regards,
Sailer
- sailer
- January 27, 2014
- Like
- 0
How to do the JSON PARSER Dynamically at run time
When i hard code the values in JSON it works ,Now i need to get the JSON structure when the records is inserted ,the values are comming in apex call out call ,not assiging to teh JSON
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse(String Acctname,String ids)
// public static void parseJSONResponse()
{
String AcctNameJson;
system.debug('AccountName______________________________'+AcctName);
system.debug('AccountName______________________________'+ids);
String JSONContent = '{folionum: AcctName, acctids: ids}'; the values are not assiging here
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'http://sherlockhomes.cloudapp.net/api/values';
request.setEndPoint(endpoint);
request.setHeader('content-type', 'application/json; charset=utf-8');
request.setMethod('POST');
//String strbody = '{folionum:AcctNameJson}';
// var obj = {};
// String JSONContent = '{"folionum":Acctname,"acctids":ids}';
system.debug('strbody ____________'+JSONContent);
// String strbody = '{"folionum":48430721840}';
request.setBody(JSONContent );
// request.setBody(strbody);
HttpResponse response = httpProtocol.send(request);
String jsonInput = response.getBody();
system.debug('===>'+jsonInput);
System.debug('Respone_____________________'+response.getBody());
}
}
But when i look at the Debug Log
9:54:30.042 (42485000)|SYSTEM_METHOD_ENTRY|[9]|System.debug(ANY)
09:54:30.042 (42513000)|USER_DEBUG|[9]|DEBUG|AccountName______________________________48430721840
09:54:30.042 (42521000)|SYSTEM_METHOD_EXIT|[9]|System.debug(ANY)
09:54:30.042 (42532000)|SYSTEM_METHOD_ENTRY|[10]|System.debug(ANY)
09:54:30.042 (42541000)|USER_DEBUG|[10]|DEBUG|AccountName______________________________001S000000fVl8DIAS
09:54:30.042 (42546000)|SYSTEM_METHOD_EXIT|[10]|System.debug(ANY)
strbody ____________{folionum: AcctName, acctids: ids}
The values are not populating here
Can anyone please help out
- sailer
- January 26, 2014
- Like
- 0
REST API Intergartion with the other server(By using the Endpoint)
I have given the Endpoint whenever the records are inserted in salesforce.com,i need to get the values from end point in JSON format
and by using External id i need to get that json values and update in salesforce.com
I wrote the trigger to insitate the webservice class
trigger AccountCallout on Account (after insert)
{
for (Account a : Trigger.new) {
// make the asynchronous web service callout
WebServiceCallout.sendNotification(a.Name);
}
}
and this webservice class is
public class WebServiceCallout {
@future (callout=true)
public static void sendNotification(String folionum) {
folionum='484307021840';
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setHeader('content-type', 'application/json; charset=utf-8');
req.setEndpoint('http://abc.cloud.net/api/values');
req.setMethod('POST');
req.setTimeout(60000);
req.setBody('folionum='+EncodingUtil.urlEncode(folionum, 'UTF-8'));
String jsonData = res.getBody();
req.setCompressed(true); // otherwise we hit a limit of 32000
System.debug(res.toString());
System.debug('STATUS:'+res.getStatus());
System.debug('STATUS_CODE:'+res.getStatusCode());
try
{
res = http.send(req);
}catch(System.CalloutException e)
{
System.debug('Callout error: '+ e);
System.debug(res.toString());
}
}
}
when i check teh logs i get the error has
System.HttpRequest[Endpoint=http://abc.cloud.net/api/values, Method=POST]
20:24:21.928 (4928855000)|CALLOUT_RESPONSE|[22]|System.HttpResponse[Status=Internal Server Error, StatusCode=500]
- sailer
- January 26, 2014
- Like
- 0
Outbound Query while reading the endpoint
whenevr the record is created in salesforce.com .I have tho read endpoint http://xxx.yyy.net/api/values, and get some fields and update in salesforce.com.I have downlaoded the wsdl from the outbound and trying to create the client services to update the values.
Is this the right aapporach or any suggestion how to build this?
Thanks,
Sailer
- sailer
- January 20, 2014
- Like
- 0
Email thorugh the Batch Apex and Assigning the subjcet with the Ids of particular record
I need to send the email by appending id in the subject.
I wrote the code ,in my query it pull 2 records and send out the mail for that two records ,but its takes only one id in the subject for the two mails that got triggered
Code is below.
global class TimeRecordReminder implements Schedulable
{
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email{get;set;}
public Map<string,string> Map_usr{get;set;}
public List<Property_Obj__c> Ids{get;set;}
//public Property_Obj__c u;
public String idsvalue;
global void execute(SchedulableContext ctx)
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
usr.clear();
usr_email.clear();
Ids=[Select id from Property_Obj__c where Mail_Response__c=true ];
usr=[select Id, Name,Mail_Response__c,Listing_Sales_Associate_Email__c from Property_Obj__c where Mail_Response__c=true AND Id=:Ids ];
Map_usr=new Map<string,string>();
for(Integer i=0;i<=usr.size();i++)
{
for(Property_Obj__c u:usr)
{
system.debug('_________id______'+u.id+'___________Email______________'+u.Mail_Response__c+'_________DATE________'+u.Name);
Map_usr.put(u.id,u.Listing_Sales_Associate_Email__c);
idsvalue=u.Id;
if(u.Listing_Sales_Associate_Email__c!=null)
usr_email.add(u.Listing_Sales_Associate_Email__c);
}
if (usr_email != null && usr_email.size() > 0)
{
System.debug('Size of the List Mail__________________ '+ usr_email.size());
sendmail(usr_email);
}
}
}
public void sendmail(List<String> str)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string [] toaddress=str;
String[] ccAddresses=new String[]{'abc@gmail.com'};
email.setSubject('Mass Email u.Id'+idsvalue);
//email.setTemplateId('BC');
email.setHtmlBody('Dear Sir /Madam,<br/><br/> Hello <br/><br/>Sincerely,<br><br/><br/>Date :'+string.valueof(system.today()));
email.setToAddresses(toaddress);
email.setCcAddresses(ccAddresses);
Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
}
}
Pl help me out or suggest ant alternative
Thanks for the help.
Regards,
Sailer
- sailer
- January 19, 2014
- Like
- 1
SendEmail failed. First exception on row 0; first error:Maximum stack depth reached: 2:
I have created the Email Template by using the component and trying to send the mail through the scheduled apex
EMAIL Template
<messaging:emailTemplate subject="Remainder FollowUp" recipientType="User" relatedToType="Property_Obj__c" >
<messaging:htmlEmailBody >
<c:RemainderMailC AcctId="{!relatedTo.Id}" />
Regard
{!recipient.Name}
</messaging:htmlEmailBody>
</messaging:emailTemplate>
Component:
<apex:component controller="acctTemplt" access="global">
<apex:attribute name="AcctId" type="Id" description="Id of the account" assignTo="{!conID}"/>>
<apex:repeat value="{!opptys}" var="o">
{!o.Name}
{!o.Id}
</apex:repeat>
</apex:component>
Apex Class
public class acctTemplt
{
public Id conID {get;set;}
public List<Property_Obj__c> usr{get;set;}
//
public List<Property_Obj__c> Ids{get;set;}
public List<String> usr_email{get;set;}
public Map<string,string> Map_usr{get;set;}
public List<Property_Obj__c> getopptys()
{
/*
List<Property_Obj__c> oppty;
oppty = [select Id, Status__c,Name,Mail_Response__c,Listing_Sales_Associate_Email__c from Property_Obj__c where Mail_Response__c=true AND Id =:conID ];
return oppty;
*/
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
usr.clear();
usr_email.clear();
Ids=[Select id from Property_Obj__c];
System.debug('Id of the property___________________________'+Ids);
usr=[select Id, Status__c,Name,Mail_Response__c,Listing_Sales_Associate_Email__c from Property_Obj__c where Mail_Response__c=true AND Id=:Ids LIMIT 1];
System.debug('Query Retrived___________________________________'+usr);
Map_usr=new Map<string,string>();
for(Property_Obj__c u:usr)
{
system.debug('__id______'+u.id+'___________Email______'+u.Listing_Sales_Associate_Email__c+'_________DATE_____'+u.Status__c);
Map_usr.put(u.id,u.Listing_Sales_Associate_Email__c);
if(u.Listing_Sales_Associate_Email__c!=null)
usr_email.add(u.Listing_Sales_Associate_Email__c);
}
if(usr_email != null && usr_email.size() > 0)
{
System.debug('Size of the List Mail__________________ '+ usr_email.size());
sendmail(usr_email);
}
return usr;
}
public void sendmail(List<String> str)
{
EmailTemplate et = [SELECT id,HtmlValue,Body,Subject ,Name FROM EmailTemplate WHERE Name = 'RemainderMailVF'];
Messaging.Singleemailmessage email = new Messaging.Singleemailmessage();
String [] toaddress=str;
String[] ccAddresses=new String[]{'veluri.harani@gmail.com'};
email.setTemplateId('00XS0000000MPu9');
email.setTargetObjectId('005800000059yaE');
email.setSaveAsActivity(false);
email.setToAddresses(toaddress);
email.setCcAddresses(ccAddresses);
Messaging.sendEmail(new Messaging.Singleemailmessage[] { email });
}
}
scheduled Apex Job.
global class RemainderMailFrequency implements Schedulable
{
global void execute(SchedulableContext ctx)
{
acctTemplt acct = new acctTemplt();
acct.getopptys();
acct.sendmail(str);
System.debug('The Size of batch calss');
}
}
Pl help me out i am struck here .
Regards
Sailer
- sailer
- January 17, 2014
- Like
- 0
To get the meta Data Type for profile on Object Settings
I need to migrate the metaData type for one orginsation to another
under Profile overview this there are Object Settings i need to change the Object setting under that profile
How do i need to migrate?
- sailer
- January 16, 2014
- Like
- 0
VF Page template for scheduling
I have req ,when the field in the custom object is checked , i need to send that details to the mail for that records ,where we have custom field.
I wrote the code by VF template and components ,in the VF template i am getting all the records that have checked,but i need one records and send the mail for that record.
and i am scheduling the code that run every day to pick that template and send out the mail
Here is the code.
######Compnent Class#####
<apex:component controller="acctTemplt" access="global">
<apex:attribute name="AcctId" type="Id" description="Id of the account" />
<table border = "2" cellspacing = "5">
<tr>
<td>Name</td>
<td>Status</td>
</tr>
<apex:repeat value="{!opptys}" var="o">
<tr>
<td>{!o.Name}</td>
<td>{!o.Mail_Response__c }</td>
</tr>
</apex:repeat>
</table>
</apex:component>
########Apex Class#######
public class acctTemplt
{
public List<String> usr_email{get;set;}
public List<Property_Obj__c> usr{get;set;} //
public Map<string,string> Map_usr{get;set;}
public List<Property_Obj__c> getopptys()
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
List<Property_Obj__c> oppty;
Map_usr=new Map<string,string>();
oppty = [SELECT Id,Name, Mail_Response__c,Listing_Sales_Associate_Email__c,Status__c FROM Property_Obj__c WHERE Mail_Response__c =true ];
return oppty;
}
}
#####Scheduler Class#######
/*
Created for Followp and to send the mail
*/
global class RemainderMailFrequency implements Schedulable
{
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email{get;set;}
Property_Obj__c updateproperty= new Property_Obj__c();
public Map<string,string> Map_usr{get;set;}
global void execute(SchedulableContext ctx)
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
usr.clear();
usr_email.clear();
usr=[select id, Status__c,Name,Mail_Response__c,Listing_Sales_Associate_Email__c from Property_Obj__c where Mail_Response__c=true ];
Map_usr=new Map<string,string>();
for(Property_Obj__c u:usr)
{
system.debug('__id______'+u.id+'___________Email______'+u.Listing_Sales_Associate_Email__c+'_________DATE_____'+u.Status__c);
Map_usr.put(u.id,u.Listing_Sales_Associate_Email__c);
if(u.Listing_Sales_Associate_Email__c!=null)
usr_email.add(u.Listing_Sales_Associate_Email__c);
}
if(usr_email.size()>0)
{
sendmail(usr_email);
}
}
public void sendmail(List<String> str)
{
EmailTemplate et = [SELECT id,HtmlValue,Body,Subject ,Name FROM EmailTemplate WHERE Name = 'RemainderMailVF'];
system.debug('Template values for sending the mail__________________ '+et.Subject);
Messaging.Singleemailmessage email = new Messaging.Singleemailmessage();
String [] toaddress=str;
String[] ccAddresses=new String[]{'test@gmail.com'};
email.setTemplateId(et.Id);
email.setTargetObjectId('005800000059yaE');
email.setSaveAsActivity(false);
email.setToAddresses(toaddress);
email.setCcAddresses(ccAddresses);
Messaging.sendEmail(new Messaging.Singleemailmessage[] { email });
}
}
and my o/p Look like below ,but there will be one Name for one email id associated i need to this alone
Name Status
13 true
12 true
15 true
14 true
Regards
Sailer
- sailer
- January 07, 2014
- Like
- 0
mass mail for custom object using the template
I wrote the code for sending out the mail for cutom object "I am getting the following error" / SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, Only contacts, leads and users allowed for targetObjectIds.: []
below is the code
/*
Created for Followp and to send the mail
*/
global class Remaindermail implements Schedulable
{
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email;
// List<Property_Obj__c> updateproperty= new List<Property_Obj__c>();
Property_Obj__c updateproperty= new Property_Obj__c();
public Map<string,string> Map_usr{get;set;}
global void execute(SchedulableContext ctx)
{
List<Property_Obj__c> lstcon=[select id, Listing_Sales_Associate_Email__c,Mail_Response__c from Property_Obj__c where Mail_Response__c=true];
List<Id> lstids= new List<Id>();
for(Property_Obj__c c:lstcon){
lstids.add(c.id);
//lstids.add(c.Listing_Sales_Associate_Email__c);
}
EmailTemplate et=[Select id from EmailTemplate where name=:'MailTemplate'];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
//mail.setWhatId(c.ID);
mail.setTargetObjectIds(lstIds);
//mail.setTargetObjectIds(lstIds)
mail.setSenderDisplayName('TestMailFromSFDC');
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}
}
Pl help me out
- sailer
- January 06, 2014
- Like
- 0
Dynamic Email Template in Scheduler Apex
I have Scheduler batch class and i need to trigger email if hard code the subject i can send out the mail,but i i need to call the email tempalet and take the row id of that object and send out mail .
Below is the code
global class Remaindermail implements Schedulable
{
String FrequencyCount;
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email{get;set;}
// List<Property_Obj__c> updateproperty= new List<Property_Obj__c>();
Property_Obj__c updateproperty= new Property_Obj__c();
public Map<string,string> Map_usr{get;set;}
global void execute(SchedulableContext ctx)
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
usr.clear();
usr_email.clear();
usr=[select id, Send_From_Email__c,FrequencyCheck__c,Status__c,Count__c from Property_Obj__c where FrequencyCheck__c=TRUE];
Map_usr=new Map<string,string>();
for(Property_Obj__c u:usr)
{
system.debug('_____________id______'+u.id+'___________Email______________'+u.Send_From_Email__c
+'_________DATE______________________________________'+u.Status__c);
Map_usr.put(u.id,u.Send_From_Email__c);
if(u.Send_From_Email__c!=null)
usr_email.add(u.Send_From_Email__c);
}
if(usr_email.size()>0)
{
sendmail(usr_email);
}
}
public void sendmail(List<String> str)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String [] toaddress=str;
String[] ccAddresses=new String[]{'abc@gmail.com'};
email.setSubject('Mass Email');
email.setHtmlBody('Dear Sir /Madam,<br/><br/> Hello <br/><br/>Sincerely,<br><br/><br/>Date :'+string.valueof
(system.today()));
email.setToAddresses(toaddress);
email.setCcAddresses(ccAddresses);
Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
}
}
- sailer
- January 06, 2014
- Like
- 1
Email Bacth limit in scheduler apex job
what will be limit if the mails that i can send out to external Ids.
Thanks for the Help.
- sailer
- December 31, 2014
- Like
- 0
Not able to build the relation for Account to conact
Hello
I need to query all the contact from the account and its working and when i update the records its get updated and new contact records is created ,but that contact is not associated to that account.
Below is the log and error
Apex Class
public class MultiAdd
{
public List<contact> lstcontact = new List<contact>();
public List<Contact> contacts;
public List<Contact> accts {get; set;}
public ApexPages.StandardController std;
//list of the inner class
public List<innerClass> lstInner
{ get;set; }
//will indicate the row to be deleted
public String selectedRowIndex
{get;set;}
//no. of rows added/records in the inner class list
public Integer count = 1;
//{get;set;}
////save the records by adding the elements in the inner class list to lstAcct,return to the same page
public PageReference Save()
{
PageReference pr = new PageReference('/apex/jqueryDoctorProfile');
for(Integer j = 0;j<lstInner.size();j++)
{
system.debug('123456789@@@@@@@@@@@@@@@@'+lstInner.size());
lstcontact .add(lstInner[j].acct);
}
system.debug('lstcontactupsert------------------------>'+lstcontact);
upsert lstcontact;
pr.setRedirect(True);
return pr;
}
//add one more row
public void Add()
{
count = count+1;
addMore();
}
public void addMoreconst()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
List<Contact> lstCon =new List<Contact>();
// List<Contact> lstCon = [SELECT testvantage__TotalNumber__c , testvantage__DoctorDescription__c, AccountId, LastName, FirstName from Contact limit 1];
lstCon=getContacts();
system.debug('totalconatctlsit'+lstCon.Size());
for(Contact c: lstCon){
objInnerClass = new innerClass(count);
objInnerClass.acct = c;
//objInnerClass.acct = c.AccountId;
lstInner.add(objInnerClass);
}
//add the record to the inner class list
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/*Begin addMore*/
public void addMore()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
//add the record to the inner class list
lstInner.add(objInnerClass);
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/* begin delete */
public void Del()
{
system.debug('selected row index---->'+selectedRowIndex);
lstInner.remove(Integer.valueOf(selectedRowIndex)-1);
count = count - 1;
}/*End del*/
/*Constructor*/
public MultiAdd(ApexPages.StandardController ctlr)
{
std=ctlr;
lstInner = new List<innerClass>();
addMoreconst();
selectedRowIndex = '0';
}/*End Constructor*/
public Account getAccount()
{
return (Account) std.getRecord();
}
/*Inner Class*/
public class innerClass
{
/*recCount acts as a index for a row. This will be helpful to identify the row to be deleted */
public String recCount
{get;set;}
public contact acct
{get;set;}
/*Inner Class Constructor*/
public innerClass(Integer intCount)
{
recCount = String.valueOf(intCount);
/*create a new account*/
acct = new contact();
}/*End Inner class Constructor*/
}/*End inner Class*/
public List<Contact> getContacts()
{ if ( (null!=getAccount().id) && (contacts == null) )
{
contacts=[SELECT Id, Name, testvantage__TotalNumber__c , testvantage__DoctorDescription__c, AccountId, LastName, FirstName FROM Contact WHERE AccountId =:ApexPages.currentPage().getParameters().get('id') ORDER BY CreatedDate];
} return contacts;
}
}/*End Class*/
VFPAGE
<apex:page StandardController="Account" extensions="MultiAdd" id="thePage">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$j = jQuery.noConflict();
$j(document).ready(function()
{
$("input[name^=TotalNumber]").keyup(function() {
var sum = 0;
$("input[name^=TotalNumber]").not("input[name=totalcost]").each(function() {
var number = parseInt(this.value) || 0;
sum += parseInt(number);
});
$("input[name=Description]").val(sum);
});
}
</script>
</head>
<apex:form >
<apex:pageblock id="pb" >
<apex:pageBlockButtons >
<apex:commandbutton value="Add" action="{!Add}" rerender="pb1"/>
<apex:commandbutton value="Save" action="{!Save}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Details" collapsible="true" id="mainRecord" columns="2" >
<apex:inputField value="{!Account.Name}"/>
<apex:inputField value="{!Account.Type}"/>
<apex:inputField value="{!Account.BillingStreet}"/>
<apex:inputField value="{!Account.Industry}"/>
<apex:inputField value="{!Account.Phone}"/>
</apex:pageBlockSection>
<apex:pageblock id="pb1">
<apex:repeat value="{!lstInner}" var="e1" id="therepeat">
<apex:panelGrid columns="6">
<apex:panelGrid headerClass="Name">
<apex:facet name="header">Del</apex:facet>
<apex:commandButton value="X" action="{!Del}" rerender="pb1">
<apex:param name="rowToBeDeleted" value="{!e1.recCount}" assignTo="{!selectedRowIndex}"></apex:param>
</apex:commandButton>
</apex:panelGrid>
<apex:panelGrid title="SPD" >
<apex:facet name="header">LastName</apex:facet>
<apex:inputfield value="{!e1.acct.LastName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">FirstName</apex:facet>
<apex:inputfield value="{!e1.acct.FirstName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">TotalNumber</apex:facet>
<apex:inputfield value="{!e1.acct.TotalNumber__c}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">DoctorDescription</apex:facet>
<apex:inputfield value="{!e1.acct.DoctorDescription__c}"/>
</apex:panelGrid>
</apex:panelgrid>
</apex:repeat>
<apex:panelgrid >
</apex:panelgrid>
</apex:pageBlock>
</apex:pageblock>
</apex:form>
</apex:page>
When is save the record i get the following error.
System.NullPointerException: Attempt to de-reference a null object
Class.testvantage.MultiAdd.addMoreconst: line 56, column 1
Class.testvantage.MultiAdd.<init>: line 98, column 1
The Debug log is below and i am able to see the accountid but is not getting asscoiated to that account
Contact:{Name=Ashley TestVf22, testvantage__DoctorDescription__c=Test123, AccountId=0019000000OmGsCAAV, FirstName=Ashley, Id=0039000000P7oI9AAJ, testvantage__TotalNumber__c=122, LastName=TestVf22}
- sailer
- December 16, 2013
- Like
- 0
System.NullPointerException: Attempt to de-reference a null object
Hi Everyone,
getting the following error
Class.testvantage.MultiAdd.addMoreconst: line 51, column 1
Class.testvantage.MultiAdd.<init>: line 90, column 1
I wrote the Apex class for add and deleting the records in VF page.
When i tried to the save the page i get the following error.
###APEX CLASS############
public class MultiAdd
{
public List<contact> lstcontact = new List<contact>();
public List<Contact> contacts;
public ApexPages.StandardController std;
//list of the inner class
public List<innerClass> lstInner
{ get;set; }
//will indicate the row to be deleted
public String selectedRowIndex
{get;set;}
//no. of rows added/records in the inner class list
public Integer count = 1;
//{get;set;}
////save the records by adding the elements in the inner class list to lstAcct,return to the same page
public PageReference Save()
{
PageReference pr = new PageReference('/apex/jqueryDoctorProfile');
for(Integer j = 0;j<lstInner.size();j++)
{
system.debug('123456789@@@@@@@@@@@@@@@@'+lstInner.size());
lstcontact .add(lstInner[j].acct);
}
system.debug('lstcontactupsert------------------------>'+lstcontact);
upsert lstcontact;
pr.setRedirect(True);
return pr;
}
//add one more row
public void Add()
{
count = count+1;
addMore();
}
public void addMoreconst()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
List<Contact> lstCon = getContacts();
system.debug('totalconatctlsit'+lstCon.Size());
for(Contact c: lstCon){
objInnerClass = new innerClass(count);
objInnerClass.acct = c;
lstInner.add(objInnerClass);
}
//add the record to the inner class list
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/*Begin addMore*/
public void addMore()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
//add the record to the inner class list
lstInner.add(objInnerClass);
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/* begin delete */
public void Del()
{
system.debug('selected row index---->'+selectedRowIndex);
lstInner.remove(Integer.valueOf(selectedRowIndex)-1);
count = count - 1;
}/*End del*/
/*Constructor*/
public MultiAdd(ApexPages.StandardController ctlr)
{
std=ctlr;
lstInner = new List<innerClass>();
addMoreconst();
selectedRowIndex = '0';
}/*End Constructor*/
public Account getAccount()
{
return (Account) std.getRecord();
}
/*Inner Class*/
public class innerClass
{
/*recCount acts as a index for a row. This will be helpful to identify the row to be deleted */
public String recCount
{get;set;}
public contact acct
{get;set;}
/*Inner Class Constructor*/
public innerClass(Integer intCount)
{
recCount = String.valueOf(intCount);
/*create a new account*/
acct = new contact();
}/*End Inner class Constructor*/
}/*End inner Class*/
public List<Contact> getContacts()
{ if ( (null!=getAccount().id) && (contacts == null) )
{
contacts=[SELECT Id, Name, testvantage__TotalNumber__c , testvantage__DoctorDescription__c, LastName, FirstName FROM Contact WHERE AccountId = : getAccount().ID ORDER BY CreatedDate];
} return contacts;
}
}/*End Class*
/########VF PAGE##############
<apex:page StandardController="Account" extensions="MultiAdd" id="thePage">
<apex:form >
<apex:pageblock id="pb" >
<apex:pageBlockButtons >
<apex:commandbutton value="Add" action="{!Add}" rerender="pb1"/>
<apex:commandbutton value="Save" action="{!Save}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Details" collapsible="true" id="mainRecord" columns="2" >
<apex:inputField value="{!Account.Name}"/>
<apex:inputField value="{!Account.Type}"/>
<apex:inputField value="{!Account.BillingStreet}"/>
<apex:inputField value="{!Account.Industry}"/>
<apex:inputField value="{!Account.Phone}"/>
</apex:pageBlockSection>
<apex:pageblock id="pb1">
<apex:repeat value="{!lstInner}" var="e1" id="therepeat">
<apex:panelGrid columns="6">
<apex:panelGrid headerClass="Name">
<apex:facet name="header">Del</apex:facet>
<apex:commandButton value="X" action="{!Del}" rerender="pb1">
<apex:param name="rowToBeDeleted" value="{!e1.recCount}" assignTo="{!selectedRowIndex}"></apex:param>
</apex:commandButton>
</apex:panelGrid>
<apex:panelGrid title="SPD" >
<apex:facet name="header">LastName</apex:facet>
<apex:inputfield value="{!e1.acct.LastName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">FirstName</apex:facet>
<apex:inputfield value="{!e1.acct.FirstName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">TotalNumber</apex:facet>
<apex:inputfield value="{!e1.acct.TotalNumber__c}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">DoctorDescription</apex:facet>
<apex:inputfield value="{!e1.acct.DoctorDescription__c}"/>
</apex:panelGrid>
</apex:panelgrid>
</apex:repeat>
</apex:pageBlock>
</apex:pageblock>
</apex:form>
</apex:page>
Pl help me out
Regards
Sailer
- sailer
- December 16, 2013
- Like
- 0
To Add the rows in VF Page and update the records in the object
Hello Everyone,
I Have created the VF page that shows account and the VF page contains another section where there will be contact list ,and whenevr the user click the Add Button its creates a new row ,when i save from the VF page the records are not created .
Secondly the relatedlist of records are not getting displayed under that account.
VF PAGE
<apex:page StandardController="Account" extensions="MultiAdd" id="thePage">
<apex:form >
<apex:pageblock id="pb" >
<apex:pageBlockButtons >
<apex:commandbutton value="Add" action="{!Add}" rerender="pb1"/>
<apex:commandbutton value="Save" action="{!Save}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Details" collapsible="true" id="mainRecord" columns="2" >
<apex:inputField value="{!Account.Name}"/>
<apex:inputField value="{!Account.Type}"/>
<apex:inputField value="{!Account.BillingStreet}"/>
<apex:inputField value="{!Account.Industry}"/>
<apex:inputField value="{!Account.Phone}"/>
</apex:pageBlockSection>
<apex:pageblock id="pb1">
<apex:repeat value="{!lstInner}" var="e1" id="therepeat">
<apex:panelGrid columns="6">
<apex:panelGrid headerClass="Name">
<apex:facet name="header">Del</apex:facet>
<apex:commandButton value="X" action="{!Del}" rerender="pb1">
<apex:param name="rowToBeDeleted" value="{!e1.recCount}" assignTo="{!selectedRowIndex}"></apex:param>
</apex:commandButton>
</apex:panelGrid>
<apex:panelGrid title="SPD" >
<apex:facet name="header">LastName</apex:facet>
<apex:inputfield value="{!e1.acct.LastName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">FirstName</apex:facet>
<apex:inputfield value="{!e1.acct.FirstName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">TotalNumber</apex:facet>
<apex:inputfield value="{!e1.acct.TotalNumber__c}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">DoctorDescription</apex:facet>
<apex:inputfield value="{!e1.acct.DoctorDescription__c}"/>
</apex:panelGrid>
</apex:panelgrid>
</apex:repeat>
</apex:pageBlock>
</apex:pageblock>
</apex:form>
</apex:page>
Apex Class:
public class MultiAdd
{
public List<contact> lstcontact = new List<contact>();
public List<Contact> contacts;
private ApexPages.StandardController std;
//list of the inner class
public List<innerClass> lstInner
{ get;set; }
//will indicate the row to be deleted
public String selectedRowIndex
{get;set;}
//no. of rows added/records in the inner class list
public Integer count = 1;
//{get;set;}
////save the records by adding the elements in the inner class list to lstAcct,return to the same page
public PageReference Save()
{
PageReference pr = new PageReference('/apex/jqueryDoctorProfile');
for(Integer j = 0;j<lstInner.size();j++)
{
lstcontact .add(lstInner[j].acct);
}
insert lstcontact;
pr.setRedirect(True);
return pr;
}
//add one more row
public void Add()
{
count = count+1;
addMore();
}
/*Begin addMore*/
public void addMore()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
//add the record to the inner class list
lstInner.add(objInnerClass);
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/* begin delete */
public void Del()
{
system.debug('selected row index---->'+selectedRowIndex);
lstInner.remove(Integer.valueOf(selectedRowIndex)-1);
count = count - 1;
}/*End del*/
/*Constructor*/
public MultiAdd(ApexPages.StandardController ctlr)
{
std=ctlr;
lstInner = new List<innerClass>();
addMore();
selectedRowIndex = '0';
}/*End Constructor*/
public Account getAccount()
{
return (Account) std.getRecord();
}
/*Inner Class*/
public class innerClass
{
/*recCount acts as a index for a row. This will be helpful to identify the row to be deleted */
public String recCount
{get;set;}
public contact acct
{get;set;}
/*Inner Class Constructor*/
public innerClass(Integer intCount)
{
recCount = String.valueOf(intCount);
/*create a new account*/
acct = new contact();
}/*End Inner class Constructor*/
}/*End inner Class*/
public List<Contact> getContacts()
{ if ( (null!=getAccount().id) && (contacts == null) )
{
contacts=[SELECT Id, Name, Email, Phone, AccountId, Title, Salutation, OtherStreet, OtherState, OtherPostalCode, OtherPhone, OtherCountry, OtherCity, MobilePhone, MailingStreet, MailingState, MailingPostalCode, MailingCountry, MailingCity, LeadSource, LastName, HomePhone, FirstName, Fax, Description, Department FROM Contact WHERE AccountId = : getAccount().ID ORDER BY CreatedDate];
} return contacts;
}
}/*End Class*/
Thanks for the Help in advance.
Regards
Sailer
- sailer
- December 13, 2013
- Like
- 0
JQuery In visual Force Page for adding the row by clicking the button
Hello Everyone,
I need to develop the Visualforce page.where i need to have button ,whenever i click the button new row should be inserted.
<apex:page standardController="Doctor__c" title="Prototype Account Edit">
<head>
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-1.4.2.min.js')}" />
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-ui-1.8.6.custom.min.js')}" />
<apex:stylesheet value="{!URLFOR($Resource.jQuery, '/css/ui-lightness/jquery-ui-1.8.6.custom.css')}" />
<script>
j$ = jQuery.noConflict();
// $.noConflict();
$j(document).ready(function() {
function () {
$('table').on('click', 'tr a', function (e) {
e.preventDefault();
$(this).parents('tr').remove();
});
$("#addTableRow").click(function() {
$("#mans").each(function () {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
});
}
</script>
</head>
<apex:pageMessages />
<apex:form >
<apex:pageBlock mode="DoctorProfile" title="DoctorProfile">
<apex:pageBlockButtons >
<apex:commandButton action="{!cancel}" value="Cancel" />
<apex:commandButton action="{!save}" value="Save" />
</apex:pageBlockButtons>
<apex:pageBlockSection title="DoctorDetails" collapsible="false" id="mainRecord" columns="2" >
<apex:inputField value="{!Doctor__c.Name}" />
<apex:inputField value="{!Doctor__c.Specialization__c}"/>
<apex:inputField value="{!Doctor__c.Sub_Speciliast__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<!--Licenses Details for the Doctor to Add it-->
<apex:outputPanel id="LicensesDetails">
<form id="form1" name="form1" method="post" action="">
<table width="100%" border="1" cellspacing="0" cellpadding="0" id="mans">
<tr>
<td>LicensesNumber
<label for="11"></label>
<input type="text" name="11" id="11" />
</td>
<td>Comments
<label for="12"></label>
<input type="text" name="12" id="12" />
</td>
<td><a href="#">del</a>
</td>
</tr>
</table>
</form>
<button type="button" id="addTableRow">add row</button>
</apex:outputPanel>
</apex:form>
</apex:page>
when i have developed the code in html the jquery works ,when i added the code to the VF page its not working..
- sailer
- December 11, 2013
- Like
- 0
Save error: Expression must be a list type: SET<Id>
global class RollUpSummaryMapNewTest implements Database.Batchable<sObject>
{
//one map and one loop.
Map<Id,Double> optylineitem=new Map<Id,Double>();
List<Opportunity> updatelist = new List<Opportunity>();
Set<Id> OptyIds = new Set<Id>();
//List<OpportunityLineItem> oppotylineitem =new List<OpportunityLineItem>();
public Double curecy=0;
global Database.QueryLocator start(Database.BatchableContext BC)
{
String lineitem='SELECT id,ListPrice, OpportunityId FROM OpportunityLineItem';
return Database.getQueryLocator(lineitem);
}
global void execute(Database.BatchableContext BC,List<Sobject> batch)
{
List< OpportunityLineItem> Lineitemcast = (List<OpportunityLineItem>) batch;
system.debug('Cast Values'+Lineitemcast);
for(OpportunityLineItem optyrecord : Lineitemcast)
{
if(optylineitem.containsKey(optyrecord.opportunityid))
{
Double listPrice = optyrecord.ListPrice + optylineitem.get(optyrecord.opportunityid);
system.debug('List Price '+listPrice);
optylineitem.remove(optyrecord.opportunityid);
optylineitem.put(optyrecord.opportunityid, listPrice);
}else
{
optylineitem.put(optyrecord.opportunityid,optyrecord.listPrice);
}
}
system.debug('Map Values '+optylineitem.values());
}
global void finish(Database.BatchableContext BC)
{
Set<Id> optylist = new Set<Id>(optylineitem.keySet()); //need to keep in the set as it reuring any values
system.debug('Map List Values'+optylist.size());
for(Integer i=0;i<optylist.size();i++)
{
Opportunity tempstore= new Opportunity(id=optylist[i]); //Save error: Expression must be a list type: SET<Id>
tempstore.testvantage__RollupBatches__c=optylineitem.get(optylist[i]);
updatelist.add(tempstore);
}
try
{
if(updatelist.size()>0)
{
//update updatelist;
system.debug('Final List######### '+updatelist);
}
}catch(DMLException e)
{
system.debug('Batch dosent contain records'+e);
}
}
}
- sailer
- December 10, 2013
- Like
- 0
Save error: Method does not exist or incorrect signature: [MAP<Id,Double>].ketSet() in Batch APEX
Hi Everyone,
I wrote the code where i am able to store the id and another value in the MAP ,By using list i need to access the values and update the price in the Opportunity
Below is the code.
global class RollUpSummaryMapNewTest implements Database.Batchable<sObject>
{
//one map and one loop.
Map<Id,Double> optylineitem=new Map<Id,Double>();
List<Opportunity> updatelist = new List<Opportunity>();
//List<OpportunityLineItem> oppotylineitem =new List<OpportunityLineItem>();
public Double curecy=0;
global Database.QueryLocator start(Database.BatchableContext BC)
{
String lineitem='SELECT id,ListPrice, OpportunityId FROM OpportunityLineItem';
System.debug('The Query@@@@@@@@'+lineitem);
return Database.getQueryLocator(lineitem);
}
global void execute(Database.BatchableContext BC,List<Sobject> batch)
{
List< OpportunityLineItem> Lineitemcast = (List<OpportunityLineItem>) batch;
for(OpportunityLineItem optyrecord : Lineitemcast)
{
if(optylineitem.containsKey(optyrecord.opportunityid))
{
Double listPrice = optyrecord.ListPrice + optylineitem.get(optyrecord.opportunityid);
optylineitem.remove(optyrecord.opportunityid);
optylineitem.put(optyrecord.opportunityid, listPrice);
}else
{
optylineitem.put(optyrecord.opportunityid,optyrecord.listPrice);
}
}
}
global void finish(Database.BatchableContext BC)
{
List<Double> optylist = new List<Double>(optylineitem.values());
system.debug('Map List Values'+optylist);
for(Integer i=0;i<optylist.size();i++)
{
Opportunity tempstore= new Opportunity();
tempstore.id=optylineitem.keySet().get(optylineitem.Id);
tempstore.testvantage__RollupBatches__c=optylineitem.get('Double');
updatelist.add(tempstore);
}
try
{
if(updatelist.size()>0)
{
system.debug('Final List######### '+updatelist);
}
}catch(DMLException e)
{
system.debug('Batch dosent contain records'+e);
}
}
}
Thanks for teh help
- sailer
- December 10, 2013
- Like
- 0
To Add the sum to the Opportunity based on the OpportunityLineItem
HI Everyone,
I want to add the sum to opportunity of all the items and i t should be in the batch process.
Its not going into the for loop that has been coloured.
Pl help me out
Thanks in advance
global class RollUpSummaryMaps implements Database.Batchable<sObject>
{
list<OpportunityLineItem> opporto =new List<OpportunityLineItem>();
list<Opportunity> optylist =new List<Opportunity>();
Opportunity optyupdate= new Opportunity();
public Double curecy=0;
global Database.QueryLocator start(Database.BatchableContext BC)
{
// Access initialState here
String lineitem='SELECT id,ListPrice, OpportunityId, PricebookEntryId FROM OpportunityLineItem';
// Database.ge
System.debug('The Query@@@@@@@@'+lineitem);
return Database.getQueryLocator(lineitem);
}
global void execute(Database.BatchableContext BC,List<Sobject> batch)
{
Map<ID, Opportunity> iMap = new Map<ID, Opportunity>([select Id,testvantage__Updatevalue__c From Opportunity ]);
Map<ID, OpportunityLineItem> mapOppty = new Map<ID, OpportunityLineItem>([SELECT Id,UnitPrice, OpportunityId, PricebookEntryId FROM OpportunityLineItem where OpportunityId IN :iMap.keySet()]);
Integer optylinesize=iMap.size();
System.debug('NEWDEBUGOptyLineItem @@@@@@@@@@@@@@############'+optylinesize);
Integer optysize=mapOppty.size();
System.debug('NEWDEBUGOptyList @@@@@@@@@@@@@@############'+optysize);
try{
if(mapOppty.size() != null && mapOppty.size()>0)
{
for(Id accId:iMap.keySet())
{
for(OpportunityLineItem lineitem:opporto)
{
system.debug('lineitem####################'+lineitem.UnitPrice);
curecy=lineitem.UnitPrice;
curecy++;
system.debug('TOTAL VALUES OF LIST PRICE@@@@@@@@@@@@@@@@@@'+curecy);
}
Id opptyId = iMap.get(accId).Id;
optyupdate = iMap.get(opptyId);
optyupdate.testvantage__Updatevalue__c=+curecy;
OptyList.add(optyupdate);
}
if(OptyList.size()>0)
{
update OptyList;
}
}
}catch(DMLException e)
{
system.debug('The batch jobs were not added to the queue successfully: '+e);
}
}
global void finish(Database.BatchableContext BC)
{
}
}
- sailer
- December 09, 2013
- Like
- 0
Email thorugh the Batch Apex and Assigning the subjcet with the Ids of particular record
I need to send the email by appending id in the subject.
I wrote the code ,in my query it pull 2 records and send out the mail for that two records ,but its takes only one id in the subject for the two mails that got triggered
Code is below.
global class TimeRecordReminder implements Schedulable
{
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email{get;set;}
public Map<string,string> Map_usr{get;set;}
public List<Property_Obj__c> Ids{get;set;}
//public Property_Obj__c u;
public String idsvalue;
global void execute(SchedulableContext ctx)
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
usr.clear();
usr_email.clear();
Ids=[Select id from Property_Obj__c where Mail_Response__c=true ];
usr=[select Id, Name,Mail_Response__c,Listing_Sales_Associate_Email__c from Property_Obj__c where Mail_Response__c=true AND Id=:Ids ];
Map_usr=new Map<string,string>();
for(Integer i=0;i<=usr.size();i++)
{
for(Property_Obj__c u:usr)
{
system.debug('_________id______'+u.id+'___________Email______________'+u.Mail_Response__c+'_________DATE________'+u.Name);
Map_usr.put(u.id,u.Listing_Sales_Associate_Email__c);
idsvalue=u.Id;
if(u.Listing_Sales_Associate_Email__c!=null)
usr_email.add(u.Listing_Sales_Associate_Email__c);
}
if (usr_email != null && usr_email.size() > 0)
{
System.debug('Size of the List Mail__________________ '+ usr_email.size());
sendmail(usr_email);
}
}
}
public void sendmail(List<String> str)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string [] toaddress=str;
String[] ccAddresses=new String[]{'abc@gmail.com'};
email.setSubject('Mass Email u.Id'+idsvalue);
//email.setTemplateId('BC');
email.setHtmlBody('Dear Sir /Madam,<br/><br/> Hello <br/><br/>Sincerely,<br><br/><br/>Date :'+string.valueof(system.today()));
email.setToAddresses(toaddress);
email.setCcAddresses(ccAddresses);
Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
}
}
Pl help me out or suggest ant alternative
Thanks for the help.
Regards,
Sailer
- sailer
- January 19, 2014
- Like
- 1
Dynamic Email Template in Scheduler Apex
I have Scheduler batch class and i need to trigger email if hard code the subject i can send out the mail,but i i need to call the email tempalet and take the row id of that object and send out mail .
Below is the code
global class Remaindermail implements Schedulable
{
String FrequencyCount;
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email{get;set;}
// List<Property_Obj__c> updateproperty= new List<Property_Obj__c>();
Property_Obj__c updateproperty= new Property_Obj__c();
public Map<string,string> Map_usr{get;set;}
global void execute(SchedulableContext ctx)
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
usr.clear();
usr_email.clear();
usr=[select id, Send_From_Email__c,FrequencyCheck__c,Status__c,Count__c from Property_Obj__c where FrequencyCheck__c=TRUE];
Map_usr=new Map<string,string>();
for(Property_Obj__c u:usr)
{
system.debug('_____________id______'+u.id+'___________Email______________'+u.Send_From_Email__c
+'_________DATE______________________________________'+u.Status__c);
Map_usr.put(u.id,u.Send_From_Email__c);
if(u.Send_From_Email__c!=null)
usr_email.add(u.Send_From_Email__c);
}
if(usr_email.size()>0)
{
sendmail(usr_email);
}
}
public void sendmail(List<String> str)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String [] toaddress=str;
String[] ccAddresses=new String[]{'abc@gmail.com'};
email.setSubject('Mass Email');
email.setHtmlBody('Dear Sir /Madam,<br/><br/> Hello <br/><br/>Sincerely,<br><br/><br/>Date :'+string.valueof
(system.today()));
email.setToAddresses(toaddress);
email.setCcAddresses(ccAddresses);
Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
}
}
- sailer
- January 06, 2014
- Like
- 1
Response Code 400 while working on "PATCH"
I am trying to update the values by passing the account id
but i am getting the ERROR has RESPONSE CODE 400.
CAN ANY ONE HELP ME WHAT WENT WRONG IN MY CODE.
package com.JSON.Response;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collection;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.impl.client.DefaultHttpClient;
public class EndPointQuery {
private static final Collection newname = null;
private static JSONObject oauthLogin(String loginUri, String clientId, String clientSecret, String username, String password) {
// HttpRequest req = new HttpRequest(); u
return null;
}
private static JSONArray posturlconnection(String loginUri, String clientId, String clientSecret, String username, String password) {
try {
String strUrl = loginUri + "/services/oauth2/token", strInstanceURL = "", strAccessToken = "";
String strURLParameter = "grant_type=password&client_id=" + clientId + "&client_secret=" + clientSecret + "&username=" +
URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8");
URL wsURL = new URL(strUrl);
HttpURLConnection wsCon = (HttpURLConnection) wsURL.openConnection();
wsCon.setRequestMethod("POST");
wsCon.setDoInput(true);
wsCon.setDoOutput(true);
wsCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//wsCon.setRequestProperty("Content-Type", "application/json");
wsCon.setRequestProperty("Contect-Length", "" + Integer.toString(strURLParameter.getBytes().length));
wsCon.setRequestProperty("charset", "utf-8");
OutputStreamWriter writer = new OutputStreamWriter(wsCon.getOutputStream());
writer.write(strURLParameter);
writer.flush();
writer.close();
String line = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(wsCon.getInputStream()));
while ((line = reader.readLine()) != null)
{
JSONObject jsnObj = new JSONObject(line);
strInstanceURL = jsnObj.getString("instance_url");
strAccessToken = jsnObj.getString("access_token");
}
JSONArray jsnArray = null;
String accountId="0019000000SvJkt";
PostMethod patch = new PostMethod(strInstanceURL + "/services/data/v20.0/sobjiects/Account/" + accountId + "?_HttpMethod=PATCH");
HttpURLConnection wsConQry = (HttpURLConnection) wsURL.openConnection();
System.out.println("Open Connection@@@@@@@@@@@@@@@@@@@"+wsConQry);
wsConQry.setRequestMethod("POST");
wsConQry.setRequestProperty("Authorization", "OAuth " + strAccessToken);
System.out.println("ResponseCode"+wsConQry.getResponseCode());
if(wsConQry.getResponseCode() == HttpURLConnection.HTTP_OK)
{
jsnArray = new JSONArray(line);
JSONObject update1=new JSONObject();
update1.put("Name", newname);
System.out.println("Updatename");
HttpClient httpclient = new HttpClient();
httpclient.executeMethod(patch);
/*BufferedReader readerRes = new BufferedReader(new InputStreamReader(wsConQry.getInputStream()));
while ((line = readerRes.readLine()) != null) {
jsnArray = new JSONArray(line);
JSONObject update1=new JSONObject();
update1.put("Name", newname);
System.out.println("Updatename");
HttpClient httpclient = new HttpClient();
httpclient.executeMethod(patch);
}*/
System.out.println(jsnArray.toString());
return jsnArray;
}
/*System.out.println(jsnArray.toString());
return jsnArray;*/
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
return null;
}
public static String restTest(String name) {
posturlconnection("https://login.salesforce.com", "3MVG9Y6d_Btp4xp4O7MWPf5592ThVeMSzmSMxLE.c8Efg.._MSWi1TIkCuwgg0n6INTp8C",
"4455896129340", "username","Password");
return null;
}
}
REGARDS
sailer
- sailer
- November 05, 2013
- Like
- 1
bulkify the code for callout
I worte the code where i am able to connect the endpoint and get the values and update ,and it works awesome.
But i can only 150 DML statement ,so i thought of bulkify
But could not able to get how to add in the list
Code is here
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse(String Acctname,String Ids)
// public static void parseJSONResponse()
{
String AcctNameJson;
system.debug('AccountName______________________________'+AcctName);
String JSONContent = '{"folionum":'+AcctName+'}';
System.debug('JSONContent____________________'+JSONContent);
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'http://abc.xyz.net/api/values';
request.setEndPoint(endpoint);
request.setHeader('content-type', 'application/json; charset=utf-8');
request.setMethod('POST');
// String strbody = '{"folionum":48430721840}';
request.setBody(JSONContent);
HttpResponse response = httpProtocol.send(request);
// String jsonInput = response.getBody(); UCOMMENETED TO READ TEH JSON
JSONParser parser = JSON.createParser(Response.getBody());
system.debug('JSON PARESER___________________'+parser );
system.debug('Respone'+Response.getBody());
double sqft ;
String avgrentpsft ;
String months12pavg ;
String monthsps12ftavg ;
String peakspavg ;
String peakspsftavg ;
while (parser.nextToken() != null)
{
//if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'sqft') &&(parser.getText() == 'avgrentpsft')&&(parser.getText() == '12monthspavg')
//&&(parser.getText() == '12monthspsftavg') &&(parser.getText() == '12monthspsftmax') &&(parser.getText() == 'peakspavg') &&(parser.getText() == 'peakspsftavg'))
//if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'sqft') (parser.getText() == 'sqft'))
if (parser.getCurrentToken() == JSONToken.FIELD_NAME)
{
String text = parser.getText();
parser.nextToken();
if(text == 'sqft')
{
sqft = parser.getDoubleValue();
}else if(text == 'avgrentpsft'){
avgrentpsft=parser.getText();
}
else if(text == '12monthspavg'){
months12pavg =parser.getText();
}
else if(text == '12monthspsftavg'){
monthsps12ftavg =parser.getText();
}
else if(text == '12monthspsftmax'){
monthsps12ftavg=parser.getText();
}
else if(text == 'peakspavg'){
peakspavg=parser.getText();
}
else if(text == 'peakspsftavg'){
peakspsftavg=parser.getText();
}
/* sqft=parser.getDoubleValue();
avgrentpsft=parser.getText();
months12pavg=parser.getText();
monthsps12ftavg=parser.getText();
peakspavg=parser.getText();
peakspsftavg=parser.getText();
parser.nextToken();
*/
}
}
system.debug('TotalAqft' + sqft);
if (response.getStatusCode() == 200) {
//update account
Property_Obj__c acc = new Property_Obj__c(Id=Ids);
acc.Ave_Rent_sf_Per_Area__c =sqft;
acc.Brkr_Remrks_2__c=avgrentpsft;
acc.Garag_Desc__c=months12pavg;
acc.Brkr_Remarks__c=monthsps12ftavg;
acc.city__c=monthsps12ftavg;
acc.DOM__c=peakspavg;
acc.Address__c=peakspsftavg;
update acc;
} else {
System.debug('Callout failed: ' + response);
}
}
}
Please help out .
Regards,
Sailer
- sailer
- January 29, 2014
- Like
- 0
Error while coding the Test Class when calling the method
i am not able to call one method in the test class can you please help me out
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse(String Acctname,String Ids)
// public static void parseJSONResponse()
{
String AcctNameJson;
system.debug('AccountName______________________________'+AcctName);
String JSONContent = '{"folionum":'+AcctName+'}';
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'http://.cloudapp.net/api/values';
request.setEndPoint(endpoint);
request.setHeader('content-type', 'application/json; charset=utf-8');
request.setMethod('POST');
// String strbody = '{"folionum":48430721840}';
request.setBody(JSONContent);
HttpResponse response = httpProtocol.send(request);
// String jsonInput = response.getBody(); UCOMMENETED TO READ TEH JSON
JSONParser parser = JSON.createParser(response.getBody());
system.debug('JSON PARESER___________________'+parser );
system.debug('Respone'+Response.getBody());
String grandTotal ;
while (parser.nextToken() != null)
{
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == '12monthspavg'))
{
parser.nextToken();
grandTotal += parser.getDoubleValue();
}
}
system.debug('Grand total=' + grandTotal);
if (response.getStatusCode() == 200) {
//update account
Account acc = new Account(Id=Ids);
acc.Description =grandTotal ;
update acc;
} else {
System.debug('Callout failed: ' + response);
}
}
}
###################Test Class####################################
@isTest(SeeAlldata=true)
private class E2PPTestClass {
@isTest static void myUnitTest()
{
// TO DO: implement unit test
String Acctname;
String Ids;
List<Account > Acctquery;
Account acct = new Account();
acct.Name='Test';
insert acct;
Acctquery=[Select Id,Name from Account limit 1];
acct.Id =Acct.Id;
acct.Name='Test';
Test.startTest();
Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock());
HttpResponse res = JSONParserUtil.parseJSONResponse(Acctname, Ids);//I am getting the Error here ave error: Illegal assignment from void to System.HttpResponse
Test.stopTest();
}
}
Please help me out
Regards,
Sailer
- sailer
- January 27, 2014
- Like
- 0
How to do the JSON PARSER Dynamically at run time
When i hard code the values in JSON it works ,Now i need to get the JSON structure when the records is inserted ,the values are comming in apex call out call ,not assiging to teh JSON
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse(String Acctname,String ids)
// public static void parseJSONResponse()
{
String AcctNameJson;
system.debug('AccountName______________________________'+AcctName);
system.debug('AccountName______________________________'+ids);
String JSONContent = '{folionum: AcctName, acctids: ids}'; the values are not assiging here
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'http://sherlockhomes.cloudapp.net/api/values';
request.setEndPoint(endpoint);
request.setHeader('content-type', 'application/json; charset=utf-8');
request.setMethod('POST');
//String strbody = '{folionum:AcctNameJson}';
// var obj = {};
// String JSONContent = '{"folionum":Acctname,"acctids":ids}';
system.debug('strbody ____________'+JSONContent);
// String strbody = '{"folionum":48430721840}';
request.setBody(JSONContent );
// request.setBody(strbody);
HttpResponse response = httpProtocol.send(request);
String jsonInput = response.getBody();
system.debug('===>'+jsonInput);
System.debug('Respone_____________________'+response.getBody());
}
}
But when i look at the Debug Log
9:54:30.042 (42485000)|SYSTEM_METHOD_ENTRY|[9]|System.debug(ANY)
09:54:30.042 (42513000)|USER_DEBUG|[9]|DEBUG|AccountName______________________________48430721840
09:54:30.042 (42521000)|SYSTEM_METHOD_EXIT|[9]|System.debug(ANY)
09:54:30.042 (42532000)|SYSTEM_METHOD_ENTRY|[10]|System.debug(ANY)
09:54:30.042 (42541000)|USER_DEBUG|[10]|DEBUG|AccountName______________________________001S000000fVl8DIAS
09:54:30.042 (42546000)|SYSTEM_METHOD_EXIT|[10]|System.debug(ANY)
strbody ____________{folionum: AcctName, acctids: ids}
The values are not populating here
Can anyone please help out
- sailer
- January 26, 2014
- Like
- 0
To get the meta Data Type for profile on Object Settings
I need to migrate the metaData type for one orginsation to another
under Profile overview this there are Object Settings i need to change the Object setting under that profile
How do i need to migrate?
- sailer
- January 16, 2014
- Like
- 0
VF Page template for scheduling
I have req ,when the field in the custom object is checked , i need to send that details to the mail for that records ,where we have custom field.
I wrote the code by VF template and components ,in the VF template i am getting all the records that have checked,but i need one records and send the mail for that record.
and i am scheduling the code that run every day to pick that template and send out the mail
Here is the code.
######Compnent Class#####
<apex:component controller="acctTemplt" access="global">
<apex:attribute name="AcctId" type="Id" description="Id of the account" />
<table border = "2" cellspacing = "5">
<tr>
<td>Name</td>
<td>Status</td>
</tr>
<apex:repeat value="{!opptys}" var="o">
<tr>
<td>{!o.Name}</td>
<td>{!o.Mail_Response__c }</td>
</tr>
</apex:repeat>
</table>
</apex:component>
########Apex Class#######
public class acctTemplt
{
public List<String> usr_email{get;set;}
public List<Property_Obj__c> usr{get;set;} //
public Map<string,string> Map_usr{get;set;}
public List<Property_Obj__c> getopptys()
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
List<Property_Obj__c> oppty;
Map_usr=new Map<string,string>();
oppty = [SELECT Id,Name, Mail_Response__c,Listing_Sales_Associate_Email__c,Status__c FROM Property_Obj__c WHERE Mail_Response__c =true ];
return oppty;
}
}
#####Scheduler Class#######
/*
Created for Followp and to send the mail
*/
global class RemainderMailFrequency implements Schedulable
{
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email{get;set;}
Property_Obj__c updateproperty= new Property_Obj__c();
public Map<string,string> Map_usr{get;set;}
global void execute(SchedulableContext ctx)
{
usr=new List<Property_Obj__c>();
usr_email=new List<String>();
usr.clear();
usr_email.clear();
usr=[select id, Status__c,Name,Mail_Response__c,Listing_Sales_Associate_Email__c from Property_Obj__c where Mail_Response__c=true ];
Map_usr=new Map<string,string>();
for(Property_Obj__c u:usr)
{
system.debug('__id______'+u.id+'___________Email______'+u.Listing_Sales_Associate_Email__c+'_________DATE_____'+u.Status__c);
Map_usr.put(u.id,u.Listing_Sales_Associate_Email__c);
if(u.Listing_Sales_Associate_Email__c!=null)
usr_email.add(u.Listing_Sales_Associate_Email__c);
}
if(usr_email.size()>0)
{
sendmail(usr_email);
}
}
public void sendmail(List<String> str)
{
EmailTemplate et = [SELECT id,HtmlValue,Body,Subject ,Name FROM EmailTemplate WHERE Name = 'RemainderMailVF'];
system.debug('Template values for sending the mail__________________ '+et.Subject);
Messaging.Singleemailmessage email = new Messaging.Singleemailmessage();
String [] toaddress=str;
String[] ccAddresses=new String[]{'test@gmail.com'};
email.setTemplateId(et.Id);
email.setTargetObjectId('005800000059yaE');
email.setSaveAsActivity(false);
email.setToAddresses(toaddress);
email.setCcAddresses(ccAddresses);
Messaging.sendEmail(new Messaging.Singleemailmessage[] { email });
}
}
and my o/p Look like below ,but there will be one Name for one email id associated i need to this alone
Name Status
13 true
12 true
15 true
14 true
Regards
Sailer
- sailer
- January 07, 2014
- Like
- 0
mass mail for custom object using the template
I wrote the code for sending out the mail for cutom object "I am getting the following error" / SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, Only contacts, leads and users allowed for targetObjectIds.: []
below is the code
/*
Created for Followp and to send the mail
*/
global class Remaindermail implements Schedulable
{
public List<Property_Obj__c> usr{get;set;} //
public List<String> usr_email;
// List<Property_Obj__c> updateproperty= new List<Property_Obj__c>();
Property_Obj__c updateproperty= new Property_Obj__c();
public Map<string,string> Map_usr{get;set;}
global void execute(SchedulableContext ctx)
{
List<Property_Obj__c> lstcon=[select id, Listing_Sales_Associate_Email__c,Mail_Response__c from Property_Obj__c where Mail_Response__c=true];
List<Id> lstids= new List<Id>();
for(Property_Obj__c c:lstcon){
lstids.add(c.id);
//lstids.add(c.Listing_Sales_Associate_Email__c);
}
EmailTemplate et=[Select id from EmailTemplate where name=:'MailTemplate'];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
//mail.setWhatId(c.ID);
mail.setTargetObjectIds(lstIds);
//mail.setTargetObjectIds(lstIds)
mail.setSenderDisplayName('TestMailFromSFDC');
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}
}
Pl help me out
- sailer
- January 06, 2014
- Like
- 0
System.NullPointerException: Attempt to de-reference a null object
Hi Everyone,
getting the following error
Class.testvantage.MultiAdd.addMoreconst: line 51, column 1
Class.testvantage.MultiAdd.<init>: line 90, column 1
I wrote the Apex class for add and deleting the records in VF page.
When i tried to the save the page i get the following error.
###APEX CLASS############
public class MultiAdd
{
public List<contact> lstcontact = new List<contact>();
public List<Contact> contacts;
public ApexPages.StandardController std;
//list of the inner class
public List<innerClass> lstInner
{ get;set; }
//will indicate the row to be deleted
public String selectedRowIndex
{get;set;}
//no. of rows added/records in the inner class list
public Integer count = 1;
//{get;set;}
////save the records by adding the elements in the inner class list to lstAcct,return to the same page
public PageReference Save()
{
PageReference pr = new PageReference('/apex/jqueryDoctorProfile');
for(Integer j = 0;j<lstInner.size();j++)
{
system.debug('123456789@@@@@@@@@@@@@@@@'+lstInner.size());
lstcontact .add(lstInner[j].acct);
}
system.debug('lstcontactupsert------------------------>'+lstcontact);
upsert lstcontact;
pr.setRedirect(True);
return pr;
}
//add one more row
public void Add()
{
count = count+1;
addMore();
}
public void addMoreconst()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
List<Contact> lstCon = getContacts();
system.debug('totalconatctlsit'+lstCon.Size());
for(Contact c: lstCon){
objInnerClass = new innerClass(count);
objInnerClass.acct = c;
lstInner.add(objInnerClass);
}
//add the record to the inner class list
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/*Begin addMore*/
public void addMore()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
//add the record to the inner class list
lstInner.add(objInnerClass);
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/* begin delete */
public void Del()
{
system.debug('selected row index---->'+selectedRowIndex);
lstInner.remove(Integer.valueOf(selectedRowIndex)-1);
count = count - 1;
}/*End del*/
/*Constructor*/
public MultiAdd(ApexPages.StandardController ctlr)
{
std=ctlr;
lstInner = new List<innerClass>();
addMoreconst();
selectedRowIndex = '0';
}/*End Constructor*/
public Account getAccount()
{
return (Account) std.getRecord();
}
/*Inner Class*/
public class innerClass
{
/*recCount acts as a index for a row. This will be helpful to identify the row to be deleted */
public String recCount
{get;set;}
public contact acct
{get;set;}
/*Inner Class Constructor*/
public innerClass(Integer intCount)
{
recCount = String.valueOf(intCount);
/*create a new account*/
acct = new contact();
}/*End Inner class Constructor*/
}/*End inner Class*/
public List<Contact> getContacts()
{ if ( (null!=getAccount().id) && (contacts == null) )
{
contacts=[SELECT Id, Name, testvantage__TotalNumber__c , testvantage__DoctorDescription__c, LastName, FirstName FROM Contact WHERE AccountId = : getAccount().ID ORDER BY CreatedDate];
} return contacts;
}
}/*End Class*
/########VF PAGE##############
<apex:page StandardController="Account" extensions="MultiAdd" id="thePage">
<apex:form >
<apex:pageblock id="pb" >
<apex:pageBlockButtons >
<apex:commandbutton value="Add" action="{!Add}" rerender="pb1"/>
<apex:commandbutton value="Save" action="{!Save}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Details" collapsible="true" id="mainRecord" columns="2" >
<apex:inputField value="{!Account.Name}"/>
<apex:inputField value="{!Account.Type}"/>
<apex:inputField value="{!Account.BillingStreet}"/>
<apex:inputField value="{!Account.Industry}"/>
<apex:inputField value="{!Account.Phone}"/>
</apex:pageBlockSection>
<apex:pageblock id="pb1">
<apex:repeat value="{!lstInner}" var="e1" id="therepeat">
<apex:panelGrid columns="6">
<apex:panelGrid headerClass="Name">
<apex:facet name="header">Del</apex:facet>
<apex:commandButton value="X" action="{!Del}" rerender="pb1">
<apex:param name="rowToBeDeleted" value="{!e1.recCount}" assignTo="{!selectedRowIndex}"></apex:param>
</apex:commandButton>
</apex:panelGrid>
<apex:panelGrid title="SPD" >
<apex:facet name="header">LastName</apex:facet>
<apex:inputfield value="{!e1.acct.LastName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">FirstName</apex:facet>
<apex:inputfield value="{!e1.acct.FirstName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">TotalNumber</apex:facet>
<apex:inputfield value="{!e1.acct.TotalNumber__c}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">DoctorDescription</apex:facet>
<apex:inputfield value="{!e1.acct.DoctorDescription__c}"/>
</apex:panelGrid>
</apex:panelgrid>
</apex:repeat>
</apex:pageBlock>
</apex:pageblock>
</apex:form>
</apex:page>
Pl help me out
Regards
Sailer
- sailer
- December 16, 2013
- Like
- 0
To Add the rows in VF Page and update the records in the object
Hello Everyone,
I Have created the VF page that shows account and the VF page contains another section where there will be contact list ,and whenevr the user click the Add Button its creates a new row ,when i save from the VF page the records are not created .
Secondly the relatedlist of records are not getting displayed under that account.
VF PAGE
<apex:page StandardController="Account" extensions="MultiAdd" id="thePage">
<apex:form >
<apex:pageblock id="pb" >
<apex:pageBlockButtons >
<apex:commandbutton value="Add" action="{!Add}" rerender="pb1"/>
<apex:commandbutton value="Save" action="{!Save}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Details" collapsible="true" id="mainRecord" columns="2" >
<apex:inputField value="{!Account.Name}"/>
<apex:inputField value="{!Account.Type}"/>
<apex:inputField value="{!Account.BillingStreet}"/>
<apex:inputField value="{!Account.Industry}"/>
<apex:inputField value="{!Account.Phone}"/>
</apex:pageBlockSection>
<apex:pageblock id="pb1">
<apex:repeat value="{!lstInner}" var="e1" id="therepeat">
<apex:panelGrid columns="6">
<apex:panelGrid headerClass="Name">
<apex:facet name="header">Del</apex:facet>
<apex:commandButton value="X" action="{!Del}" rerender="pb1">
<apex:param name="rowToBeDeleted" value="{!e1.recCount}" assignTo="{!selectedRowIndex}"></apex:param>
</apex:commandButton>
</apex:panelGrid>
<apex:panelGrid title="SPD" >
<apex:facet name="header">LastName</apex:facet>
<apex:inputfield value="{!e1.acct.LastName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">FirstName</apex:facet>
<apex:inputfield value="{!e1.acct.FirstName}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">TotalNumber</apex:facet>
<apex:inputfield value="{!e1.acct.TotalNumber__c}"/>
</apex:panelGrid>
<apex:panelGrid >
<apex:facet name="header">DoctorDescription</apex:facet>
<apex:inputfield value="{!e1.acct.DoctorDescription__c}"/>
</apex:panelGrid>
</apex:panelgrid>
</apex:repeat>
</apex:pageBlock>
</apex:pageblock>
</apex:form>
</apex:page>
Apex Class:
public class MultiAdd
{
public List<contact> lstcontact = new List<contact>();
public List<Contact> contacts;
private ApexPages.StandardController std;
//list of the inner class
public List<innerClass> lstInner
{ get;set; }
//will indicate the row to be deleted
public String selectedRowIndex
{get;set;}
//no. of rows added/records in the inner class list
public Integer count = 1;
//{get;set;}
////save the records by adding the elements in the inner class list to lstAcct,return to the same page
public PageReference Save()
{
PageReference pr = new PageReference('/apex/jqueryDoctorProfile');
for(Integer j = 0;j<lstInner.size();j++)
{
lstcontact .add(lstInner[j].acct);
}
insert lstcontact;
pr.setRedirect(True);
return pr;
}
//add one more row
public void Add()
{
count = count+1;
addMore();
}
/*Begin addMore*/
public void addMore()
{
//call to the iner class constructor
innerClass objInnerClass = new innerClass(count);
//add the record to the inner class list
lstInner.add(objInnerClass);
system.debug('lstInner---->'+lstInner);
}/* end addMore*/
/* begin delete */
public void Del()
{
system.debug('selected row index---->'+selectedRowIndex);
lstInner.remove(Integer.valueOf(selectedRowIndex)-1);
count = count - 1;
}/*End del*/
/*Constructor*/
public MultiAdd(ApexPages.StandardController ctlr)
{
std=ctlr;
lstInner = new List<innerClass>();
addMore();
selectedRowIndex = '0';
}/*End Constructor*/
public Account getAccount()
{
return (Account) std.getRecord();
}
/*Inner Class*/
public class innerClass
{
/*recCount acts as a index for a row. This will be helpful to identify the row to be deleted */
public String recCount
{get;set;}
public contact acct
{get;set;}
/*Inner Class Constructor*/
public innerClass(Integer intCount)
{
recCount = String.valueOf(intCount);
/*create a new account*/
acct = new contact();
}/*End Inner class Constructor*/
}/*End inner Class*/
public List<Contact> getContacts()
{ if ( (null!=getAccount().id) && (contacts == null) )
{
contacts=[SELECT Id, Name, Email, Phone, AccountId, Title, Salutation, OtherStreet, OtherState, OtherPostalCode, OtherPhone, OtherCountry, OtherCity, MobilePhone, MailingStreet, MailingState, MailingPostalCode, MailingCountry, MailingCity, LeadSource, LastName, HomePhone, FirstName, Fax, Description, Department FROM Contact WHERE AccountId = : getAccount().ID ORDER BY CreatedDate];
} return contacts;
}
}/*End Class*/
Thanks for the Help in advance.
Regards
Sailer
- sailer
- December 13, 2013
- Like
- 0
JQuery In visual Force Page for adding the row by clicking the button
Hello Everyone,
I need to develop the Visualforce page.where i need to have button ,whenever i click the button new row should be inserted.
<apex:page standardController="Doctor__c" title="Prototype Account Edit">
<head>
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-1.4.2.min.js')}" />
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-ui-1.8.6.custom.min.js')}" />
<apex:stylesheet value="{!URLFOR($Resource.jQuery, '/css/ui-lightness/jquery-ui-1.8.6.custom.css')}" />
<script>
j$ = jQuery.noConflict();
// $.noConflict();
$j(document).ready(function() {
function () {
$('table').on('click', 'tr a', function (e) {
e.preventDefault();
$(this).parents('tr').remove();
});
$("#addTableRow").click(function() {
$("#mans").each(function () {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
});
}
</script>
</head>
<apex:pageMessages />
<apex:form >
<apex:pageBlock mode="DoctorProfile" title="DoctorProfile">
<apex:pageBlockButtons >
<apex:commandButton action="{!cancel}" value="Cancel" />
<apex:commandButton action="{!save}" value="Save" />
</apex:pageBlockButtons>
<apex:pageBlockSection title="DoctorDetails" collapsible="false" id="mainRecord" columns="2" >
<apex:inputField value="{!Doctor__c.Name}" />
<apex:inputField value="{!Doctor__c.Specialization__c}"/>
<apex:inputField value="{!Doctor__c.Sub_Speciliast__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<!--Licenses Details for the Doctor to Add it-->
<apex:outputPanel id="LicensesDetails">
<form id="form1" name="form1" method="post" action="">
<table width="100%" border="1" cellspacing="0" cellpadding="0" id="mans">
<tr>
<td>LicensesNumber
<label for="11"></label>
<input type="text" name="11" id="11" />
</td>
<td>Comments
<label for="12"></label>
<input type="text" name="12" id="12" />
</td>
<td><a href="#">del</a>
</td>
</tr>
</table>
</form>
<button type="button" id="addTableRow">add row</button>
</apex:outputPanel>
</apex:form>
</apex:page>
when i have developed the code in html the jquery works ,when i added the code to the VF page its not working..
- sailer
- December 11, 2013
- Like
- 0
Save error: Expression must be a list type: SET<Id>
global class RollUpSummaryMapNewTest implements Database.Batchable<sObject>
{
//one map and one loop.
Map<Id,Double> optylineitem=new Map<Id,Double>();
List<Opportunity> updatelist = new List<Opportunity>();
Set<Id> OptyIds = new Set<Id>();
//List<OpportunityLineItem> oppotylineitem =new List<OpportunityLineItem>();
public Double curecy=0;
global Database.QueryLocator start(Database.BatchableContext BC)
{
String lineitem='SELECT id,ListPrice, OpportunityId FROM OpportunityLineItem';
return Database.getQueryLocator(lineitem);
}
global void execute(Database.BatchableContext BC,List<Sobject> batch)
{
List< OpportunityLineItem> Lineitemcast = (List<OpportunityLineItem>) batch;
system.debug('Cast Values'+Lineitemcast);
for(OpportunityLineItem optyrecord : Lineitemcast)
{
if(optylineitem.containsKey(optyrecord.opportunityid))
{
Double listPrice = optyrecord.ListPrice + optylineitem.get(optyrecord.opportunityid);
system.debug('List Price '+listPrice);
optylineitem.remove(optyrecord.opportunityid);
optylineitem.put(optyrecord.opportunityid, listPrice);
}else
{
optylineitem.put(optyrecord.opportunityid,optyrecord.listPrice);
}
}
system.debug('Map Values '+optylineitem.values());
}
global void finish(Database.BatchableContext BC)
{
Set<Id> optylist = new Set<Id>(optylineitem.keySet()); //need to keep in the set as it reuring any values
system.debug('Map List Values'+optylist.size());
for(Integer i=0;i<optylist.size();i++)
{
Opportunity tempstore= new Opportunity(id=optylist[i]); //Save error: Expression must be a list type: SET<Id>
tempstore.testvantage__RollupBatches__c=optylineitem.get(optylist[i]);
updatelist.add(tempstore);
}
try
{
if(updatelist.size()>0)
{
//update updatelist;
system.debug('Final List######### '+updatelist);
}
}catch(DMLException e)
{
system.debug('Batch dosent contain records'+e);
}
}
}
- sailer
- December 10, 2013
- Like
- 0
Save error: Method does not exist or incorrect signature: [MAP<Id,Double>].ketSet() in Batch APEX
Hi Everyone,
I wrote the code where i am able to store the id and another value in the MAP ,By using list i need to access the values and update the price in the Opportunity
Below is the code.
global class RollUpSummaryMapNewTest implements Database.Batchable<sObject>
{
//one map and one loop.
Map<Id,Double> optylineitem=new Map<Id,Double>();
List<Opportunity> updatelist = new List<Opportunity>();
//List<OpportunityLineItem> oppotylineitem =new List<OpportunityLineItem>();
public Double curecy=0;
global Database.QueryLocator start(Database.BatchableContext BC)
{
String lineitem='SELECT id,ListPrice, OpportunityId FROM OpportunityLineItem';
System.debug('The Query@@@@@@@@'+lineitem);
return Database.getQueryLocator(lineitem);
}
global void execute(Database.BatchableContext BC,List<Sobject> batch)
{
List< OpportunityLineItem> Lineitemcast = (List<OpportunityLineItem>) batch;
for(OpportunityLineItem optyrecord : Lineitemcast)
{
if(optylineitem.containsKey(optyrecord.opportunityid))
{
Double listPrice = optyrecord.ListPrice + optylineitem.get(optyrecord.opportunityid);
optylineitem.remove(optyrecord.opportunityid);
optylineitem.put(optyrecord.opportunityid, listPrice);
}else
{
optylineitem.put(optyrecord.opportunityid,optyrecord.listPrice);
}
}
}
global void finish(Database.BatchableContext BC)
{
List<Double> optylist = new List<Double>(optylineitem.values());
system.debug('Map List Values'+optylist);
for(Integer i=0;i<optylist.size();i++)
{
Opportunity tempstore= new Opportunity();
tempstore.id=optylineitem.keySet().get(optylineitem.Id);
tempstore.testvantage__RollupBatches__c=optylineitem.get('Double');
updatelist.add(tempstore);
}
try
{
if(updatelist.size()>0)
{
system.debug('Final List######### '+updatelist);
}
}catch(DMLException e)
{
system.debug('Batch dosent contain records'+e);
}
}
}
Thanks for teh help
- sailer
- December 10, 2013
- Like
- 0