- Keshab Acharya
- NEWBIE
- 70 Points
- Member since 2014
- Force.com Developer
-
ChatterFeed
-
2Best Answers
-
0Likes Received
-
1Likes Given
-
0Questions
-
20Replies
- udayarangareddy mekala
- October 19, 2015
- Like
- 0
Oncomplete issues with apex commandButton
Folks.
I am using <apex:commandButton value="Next" action="{!method1}" rerender="test" oncomplete="complete1();"/>
Once the method1 executes, it updates a boolean variable to 'true' and in the constructor this variable value is set as false
public void method1(){
fieldstatus='true';
//system.debug('fieldstatus:'+fieldstatus);
}
Now on VF page , i want to access this variable value so used oncomplete, but in the oncomplete function i always got the value as false.
function complete1() {
var check1= '{!fieldstatus}';
alert(check1);
}
Any idea why this wierd behaviour?
I am using <apex:commandButton value="Next" action="{!method1}" rerender="test" oncomplete="complete1();"/>
Once the method1 executes, it updates a boolean variable to 'true' and in the constructor this variable value is set as false
public void method1(){
fieldstatus='true';
//system.debug('fieldstatus:'+fieldstatus);
}
Now on VF page , i want to access this variable value so used oncomplete, but in the oncomplete function i always got the value as false.
function complete1() {
var check1= '{!fieldstatus}';
alert(check1);
}
Any idea why this wierd behaviour?
- Abhik Dey
- April 22, 2015
- Like
- 0
plz clarifie this............
what is the different b/w trigger_events and trigger context varaiables..................? with 1 example...
what is best pratices of trigger?
what is best pratices of trigger?
- bhanu challenge
- July 27, 2016
- Like
- 0
Test Apex Class fails due to code coverage
Hi All,
I am very new to Force.com and Sales Force Apex classes. I found this article online which adds a next button to leads and cases. I was able to get it to work on Sandbox but failed to migrate it to production. Deployment fails due to code coverage. It only covers 66 percent. i can not find any solution for this. Any help would be appreciated.
Here is the article:
https://developer.salesforce.com/page/The_Get_Next_Button
Here is code:
I am very new to Force.com and Sales Force Apex classes. I found this article online which adds a next button to leads and cases. I was able to get it to work on Sandbox but failed to migrate it to production. Deployment fails due to code coverage. It only covers 66 percent. i can not find any solution for this. Any help would be appreciated.
Here is the article:
https://developer.salesforce.com/page/The_Get_Next_Button
Here is code:
@isTest(SeeAllData=true) private class TestNextButton { static Id retrieveNextCase(String userId) { //Really we're only specifying the user ID for the sake of the test methods if (userId=='') { //Use the currently running user userId = UserInfo.getUserId(); } //First find out which queues this user is a member of List<Id> listGroupIds = getQueuesForUser(userId); if(listGroupIds.size()>0) { //Find an open case that is assigned to one of those queues Case caseObj = [select c.Id,c.OwnerId from Case c where c.IsClosed=false and c.OwnerId in :listGroupIds limit 1 for update]; if (caseObj!=null) { //If we found one, assign it to the current user caseObj.OwnerId = userId; update caseObj; return caseObj.Id; } } return null; } static Id retrieveNextLead(String userId) { //Really we're only specifying the user ID for the sake of the test methods if (userId=='') { //Use the currently running user userId = UserInfo.getUserId(); } //First find out which queues this user is a member of List<Id> listGroupIds = getQueuesForUser(userId); if(listGroupIds.size()>0) { //Find an open lead that is assigned to one of those queues List<Lead> leads = [select l.Id,l.OwnerId from Lead l where l.IsConverted=false and l.OwnerId in :listGroupIds limit 1 for update]; if (leads.size()>0) { //If we found one, assign it to the current user leads[0].OwnerId = userId; update leads; return leads[0].Id; } } return null; } //Returns a list of ids of queues that this user is a member of public static List<Id> getQueuesForUser(String userId) { List<Id> listGroupIds = new List<Id>(); List<GroupMember> listGroupMembers = [Select g.GroupId From GroupMember g where g.Group.Type='Queue' and g.UserOrGroupId=:userId]; if (listGroupMembers!=null && listGroupMembers.size()>0) { for (GroupMember gm:listGroupMembers) { listGroupIds.add(gm.GroupId); } } return listGroupIds; } public static Group createTestGroup() { Group g = new Group(Type='Queue',Name='testRetrieveNextCase'); insert g; //Make this queue assignable to leads and cases List<QueueSobject> qs = new List<QueueSobject>(); qs.add(new QueueSobject(QueueId=g.Id,SObjectType='Case')); qs.add(new QueueSobject(QueueId=g.Id,SObjectType='Lead')); insert qs; return g; } static User createTestUser() { User user = new User(); user.Username = 'test'+System.currentTimeMillis()+'@RetrieveNextUtils.com'; user.LastName = 'LastTestName'; user.Email = 'test@RetrieveNextUtils.com'; user.alias = 'testAl'; user.TimeZoneSidKey = 'America/New_York'; user.LocaleSidKey = 'en_US'; user.EmailEncodingKey = 'ISO-8859-1'; user.ProfileId = [select id from Profile where Name='System Administrator'].Id; user.LanguageLocaleKey = 'en_US'; insert user; //setUser(user); return user; } public static testMethod void testRetrieveNextLead() { User u = createTestUser(); Group g = createTestGroup(); GroupMember gm = new GroupMember(UserOrGroupId=u.Id,GroupId=g.Id); insert gm; Test.startTest(); //We have to runAs so that we don't get a MIXED_DML_EXCEPTION System.runAs(u) { Lead l = new Lead(LastName='Test',OwnerId=g.Id,Company='Test'); insert l; Id leadId = retrieveNextLead(u.Id); System.assertEquals(leadId,l.Id); Lead ownedLead = [select OwnerId from Lead where Id=:l.Id]; System.assertEquals(ownedLead.OwnerId,u.Id); } } public static testMethod void testNegativeRetrieveNextLead() { User u = createTestUser(); Group g = createTestGroup(); Test.startTest(); //We have to runAs so that we don't get a MIXED_DML_EXCEPTION System.runAs(u) { //Do not insert this user in the queue -- he should not get the case Lead l = new Lead(LastName='Test',OwnerId=g.Id,Company='Test'); insert l; Id leadId = retrieveNextLead(u.Id); System.assertEquals(leadId,null); Lead ownedLead = [select OwnerId from Lead where Id=:l.Id]; System.assertNotEquals(ownedLead.OwnerId,u.Id); } } public static testMethod void testRetrieveNextCase() { User u = createTestUser(); Group g = createTestGroup(); GroupMember gm = new GroupMember(UserOrGroupId=u.Id,GroupId=g.Id); insert gm; Test.startTest(); //We have to runAs so that we don't get a MIXED_DML_EXCEPTION System.runAs(u) { Case c = new Case(Subject='Test',OwnerId=g.Id); insert c; Id caseId = retrieveNextCase(u.Id); System.assertEquals(caseId,c.Id); Case ownedCase = [select OwnerId from Case where Id=:c.Id]; System.assertEquals(ownedCase.OwnerId,u.Id); } } public static testMethod void testNegativeRetrieveNextCase() { User u = createTestUser(); Group g = createTestGroup(); Test.startTest(); //We have to runAs so that we don't get a MIXED_DML_EXCEPTION System.runAs(u) { //Do not insert this user in the queue -- he should not get the case Case c = new Case(Subject='Test',OwnerId=g.Id); insert c; Id caseId = retrieveNextCase(u.Id); System.assertEquals(caseId,null); Case ownedCase = [select OwnerId from Case where Id=:c.Id]; System.assertNotEquals(ownedCase.OwnerId,u.Id); } } }
- Burak Yurttas 7
- July 27, 2016
- Like
- 0
Update Field(Apex Class Schedule Daily)
Hi,
I have a requirement we i need to update the field daily.
Every day when date changes the value from Field 1 should be updated in Field 2 and Field 2 value should be moved to Field 3.
This process should trigger every day.
Object Name: Daily_Check_List__c
Field 1: Todays_Status__c
Field 2: YesterdayStatus__c
Field 3: X2DaysPastStatus__c
Thanks,
Zeeshan.
I have a requirement we i need to update the field daily.
Every day when date changes the value from Field 1 should be updated in Field 2 and Field 2 value should be moved to Field 3.
This process should trigger every day.
Object Name: Daily_Check_List__c
Field 1: Todays_Status__c
Field 2: YesterdayStatus__c
Field 3: X2DaysPastStatus__c
Thanks,
Zeeshan.
- Zeeshan Moulvi 2
- May 03, 2016
- Like
- 0
How to open new tab in visualforce page
hii..
I have a button on the click of button output show in same tab , I want on the click of button output display a new tab without using java script?
plz help me...
=============It's my visualforce page code :- =============
<apex:page standardController="Opportunity" extensions="quickaction">
<apex:form >
<style>
.test{
float:right;
}
</style>
<div class='test'>
<apex:commandButton action="{!call}" image="/resource/trac_QuickActions/Phone.png"/>
<apex:commandButton action="{!email}" image="/resource/trac_QuickActions/Mail.png"/>
<apex:commandButton action="{!meeting}" image="/resource/trac_QuickActions/Calendar.png"/>
<apex:commandButton action="{!task}" image="/resource/trac_QuickActions/Notes.png"/>
</div>
</apex:form>
</apex:page>
=========It's my apex code:-==========
public class quickaction {
public String p;
public String Name1;
public quickaction(ApexPages.StandardController controller) {
p = ApexPages.currentPage().getParameters().get('id');
integer n=[SELECT Count() FROM OpportunityContactRole WHERE OpportunityId =:ApexPages.currentPage().getParameters().get('id') AND IsPrimary = true];
system.debug(Name1+'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn');
if(n > 0){
OpportunityContactRole op=[SELECT ContactId FROM OpportunityContactRole WHERE OpportunityId =:ApexPages.currentPage().getParameters().get('id') AND IsPrimary = true];
Contact c=[select Name,id From Contact where Id=:op.ContactId ];
Name1=c.Name;
system.debug(Name1+'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn');
}
}
public PageReference task(){
PageReference acctPage = new PageReference('/00T/e?who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&tsk4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage;
}
public PageReference email(){
if(Name1 != null){
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Email&00N7A000000NoRm=Email&tsk4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&tsk12=Completed&tsk2='+Name1+'&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage;
}
else{
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Email&00N7A000000NoRm=Email&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage;
}
}
public PageReference call(){
if(Name1 != ''){
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Call&00N7A000000NoRm=Call&tsk4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&tsk12=Completed&tsk2='+Name1+'&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage ;
}
else{
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Call&00N7A000000NoRm=Call&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage ;
}
}
public PageReference meeting(){
if(Name1 != null){
PageReference acctPage = new PageReference('/00U/e?who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&ent=Event&retURL= '+ApexPages.currentPage().getParameters().get('id')+'&evt5=Meeting Booked with '+Name1+'&evt4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&evt2='+Name1);
acctPage.setRedirect(true);
return acctPage;
}
else{
PageReference acctPage = new PageReference('/00U/e?who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&ent=Event&retURL= '+ApexPages.currentPage().getParameters().get('id')+'&evt5=Meeting&evt4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year());
acctPage.setRedirect(true);
return acctPage;
}
}
}
I have a button on the click of button output show in same tab , I want on the click of button output display a new tab without using java script?
plz help me...
=============It's my visualforce page code :- =============
<apex:page standardController="Opportunity" extensions="quickaction">
<apex:form >
<style>
.test{
float:right;
}
</style>
<div class='test'>
<apex:commandButton action="{!call}" image="/resource/trac_QuickActions/Phone.png"/>
<apex:commandButton action="{!email}" image="/resource/trac_QuickActions/Mail.png"/>
<apex:commandButton action="{!meeting}" image="/resource/trac_QuickActions/Calendar.png"/>
<apex:commandButton action="{!task}" image="/resource/trac_QuickActions/Notes.png"/>
</div>
</apex:form>
</apex:page>
=========It's my apex code:-==========
public class quickaction {
public String p;
public String Name1;
public quickaction(ApexPages.StandardController controller) {
p = ApexPages.currentPage().getParameters().get('id');
integer n=[SELECT Count() FROM OpportunityContactRole WHERE OpportunityId =:ApexPages.currentPage().getParameters().get('id') AND IsPrimary = true];
system.debug(Name1+'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn');
if(n > 0){
OpportunityContactRole op=[SELECT ContactId FROM OpportunityContactRole WHERE OpportunityId =:ApexPages.currentPage().getParameters().get('id') AND IsPrimary = true];
Contact c=[select Name,id From Contact where Id=:op.ContactId ];
Name1=c.Name;
system.debug(Name1+'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn');
}
}
public PageReference task(){
PageReference acctPage = new PageReference('/00T/e?who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&tsk4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage;
}
public PageReference email(){
if(Name1 != null){
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Email&00N7A000000NoRm=Email&tsk4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&tsk12=Completed&tsk2='+Name1+'&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage;
}
else{
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Email&00N7A000000NoRm=Email&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage;
}
}
public PageReference call(){
if(Name1 != ''){
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Call&00N7A000000NoRm=Call&tsk4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&tsk12=Completed&tsk2='+Name1+'&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage ;
}
else{
PageReference acctPage = new PageReference('/00T/e?title=Call&who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&00N7A000000NoRh=Communication&tsk5=Call&00N7A000000NoRm=Call&retURL='+ApexPages.currentPage().getParameters().get('id'));
acctPage.setRedirect(true);
return acctPage ;
}
}
public PageReference meeting(){
if(Name1 != null){
PageReference acctPage = new PageReference('/00U/e?who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&ent=Event&retURL= '+ApexPages.currentPage().getParameters().get('id')+'&evt5=Meeting Booked with '+Name1+'&evt4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year()+'&evt2='+Name1);
acctPage.setRedirect(true);
return acctPage;
}
else{
PageReference acctPage = new PageReference('/00U/e?who_id='+userinfo.getuserid()+'&what_id='+ApexPages.currentPage().getParameters().get('id')+'&ent=Event&retURL= '+ApexPages.currentPage().getParameters().get('id')+'&evt5=Meeting&evt4='+system.today().month()+'/'+system.today().day()+'/'+system.today().year());
acctPage.setRedirect(true);
return acctPage;
}
}
}
- Navjeet Singh 6
- May 03, 2016
- Like
- 0
Error while implementing a REST Service
Below is my code
@RestResource(urlMapping='/v1/accounts/*')
global with sharing class REST_AccountService_V1 {
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website, BillingState FROM Account WHERE External_Id__c = :accountId];
return result;
}
}
When I try to test the above Rest service in SOAPUI Tool
I am getting an error as below:
[ERROR:]Service not found at: /services/apexrest/AccountRaw ResponseHTTP/1.1 404 Not Found Date: Fri, 30 Oct 2015 06:35:33 GMT Set-Cookie: BrowserId=-MDkUrODQ_K2MkY-SmGwqw;Path=/;Domain=.salesforce.com;Expires=Tue, 29-Dec-2015 06:35:33 GMT Expires: Thu, 01 Jan 1970 00:00:00 GMT Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked
[ { "errorCode" : "NOT_FOUND", "message" : "Could not find a match for URL /Account" } ]
Do I need to create a Remote site URL also ?How does it help?
@RestResource(urlMapping='/v1/accounts/*')
global with sharing class REST_AccountService_V1 {
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website, BillingState FROM Account WHERE External_Id__c = :accountId];
return result;
}
}
When I try to test the above Rest service in SOAPUI Tool
I am getting an error as below:
[ERROR:]Service not found at: /services/apexrest/AccountRaw ResponseHTTP/1.1 404 Not Found Date: Fri, 30 Oct 2015 06:35:33 GMT Set-Cookie: BrowserId=-MDkUrODQ_K2MkY-SmGwqw;Path=/;Domain=.salesforce.com;Expires=Tue, 29-Dec-2015 06:35:33 GMT Expires: Thu, 01 Jan 1970 00:00:00 GMT Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked
[ { "errorCode" : "NOT_FOUND", "message" : "Could not find a match for URL /Account" } ]
Do I need to create a Remote site URL also ?How does it help?
- Abhilash M
- October 30, 2015
- Like
- 1
Can't get the SOQL correct Limit 100
I am not sure what I am doing incorrectlly, I am pretty new.
Here is my query, I need to add a limit in there no matter what I try it is not working.
public PageReference submitCase() {
List<Account> accts = [SELECT Id FROM Account WHERE AccountNumber = :acctNum];
I tried which I thought would work.
List<Account> accts = [SELECT Id FROM Account [Limit 100] WHERE AccountNumber = :acctNum limit 10];
But it is not. Thanks in advance!
Here is my query, I need to add a limit in there no matter what I try it is not working.
public PageReference submitCase() {
List<Account> accts = [SELECT Id FROM Account WHERE AccountNumber = :acctNum];
I tried which I thought would work.
List<Account> accts = [SELECT Id FROM Account [Limit 100] WHERE AccountNumber = :acctNum limit 10];
But it is not. Thanks in advance!
- Michael Webb 15
- October 19, 2015
- Like
- 0
Date Format function
Hello everyone,
I have been using a the following date format function to for format my date in the following format 'October 19, 2015'
The function has been working well but today we jsut found out that if the date selected is 2015-31-12, It is being formated as 'December 30, 2016' instead of 'December 30, 2015'
Does anyone knows what is causing this?
This is how I am calling the function dateTimeScheduled.format('MMMM d, YYYY');
I have been using a the following date format function to for format my date in the following format 'October 19, 2015'
The function has been working well but today we jsut found out that if the date selected is 2015-31-12, It is being formated as 'December 30, 2016' instead of 'December 30, 2015'
Does anyone knows what is causing this?
This is how I am calling the function dateTimeScheduled.format('MMMM d, YYYY');
- aottaru
- October 19, 2015
- Like
- 0
- udayarangareddy mekala
- October 19, 2015
- Like
- 0
Display the name of Workflow on visualforce page
Hello guyz,
I want to display all the workflow rules name on a single visualforce page with count (dont know on which object workflow rules get stored )
Thanks
I want to display all the workflow rules name on a single visualforce page with count (dont know on which object workflow rules get stored )
Thanks
- mohit Srivastava
- October 19, 2015
- Like
- 0
UserInfo.getUserId() returns Null for Community User
We have this query now SELECT Id, Contact.AccountId, Contact.Account.Name FROM User WHERE Id = : UserInfo.getUserId()
that it suppose to bring back the id and the account name of the Community User which is the Contact of an account in salesforce. but its returning Null back and the page crashes when I use it It seems to me that UserInfor.getUserId() is not returning a value and that is why I am getting that error . So i am trying to query the current partner community user ...Force.com and access the parent account, which it will always be the same account
that it suppose to bring back the id and the account name of the Community User which is the Contact of an account in salesforce. but its returning Null back and the page crashes when I use it It seems to me that UserInfor.getUserId() is not returning a value and that is why I am getting that error . So i am trying to query the current partner community user ...Force.com and access the parent account, which it will always be the same account
- Behzad Bahadori 18
- October 14, 2015
- Like
- 0
Could you Please help me how to write the test class for this code
Hi All,
I don't have much experience in writing the test class as i have written the below code. Can you please write the test class for the below code.
I don't have much experience in writing the test class as i have written the below code. Can you please write the test class for the below code.
public without sharing class CaseFrecuencyIncidenceCLS { public static Id RTMX_REDLTH_CONSUMER_CALL = null; public static Id RTREJC_SERVICE = null; private String vDueDay; private String vDueTime; private double vDueTimeDoub; private String vDueTimeDoubl; private String Classification; private map<String,list<Account>> mpCoverDC; //index by Colony //-----------------------------$$ future method for final case record update : ------- @future public static void updateCaseStatusToAssigned(id caseRecId) { system.debug('@@caseRecId@@'+caseRecId); Case caseRec = [SELECT id, status, Service_Center__c,Declined_Reason__c, Confirmed_Declined_by__c FROM case WHERE id=: caseRecId]; if(caseRec.Service_Center__c != null){ caseRec.status= 'Assigned'; caseRec.Declined_Reason__c=''; caseRec.Confirmed_Declined_by__c=''; update caseRec; } } //---------------------------------------------------------------------- public void rt(){ RTMX_REDLTH_CONSUMER_CALL = getRecordTypeId('Case','MX RedLTH Consumer Call'); RTREJC_SERVICE = getRecordTypeId('Case','Rejected Service'); }//rt() //---------------------------------------------------------------------- //Used to get record Type Id public Id getRecordTypeId(String objType, String name) { Id RecordTypeId = null; Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objType); if (targetType != null) { SObject obj = targetType.newSObject(); Schema.DescribeSObjectResult d = obj.getSObjectType().getDescribe(); if (d != null) { Map<String,Schema.RecordTypeInfo> rtMap = d.getRecordTypeInfosByName(); if (rtMap != null) { Schema.RecordTypeInfo rtInfo = rtMap.get(name); if (rtInfo != null) { RecordTypeId = rtInfo.getRecordTypeId(); }//if }//if }//if }//if return RecordTypeId; }//getRecordTypeId //---------------------------------------------------------------------- public void updateRelatedContact(list<Case> cases){ list<Id> lsIDCITY = new list<Id>(); list<Id> lsIDCOLO = new list<Id>(); list<Id> lsIDCONT = new list<Id>(); for(Case c: cases){ lsIDCITY.add(c.City__c); lsIDCOLO.add(c.Colony__c); lsIDCONT.add(c.ContactId); }//for map<Id,City__c> mpCITY = new map<Id,City__c>([SELECT Id,Name From City__c where id=:lsIDCITY]); map<Id,Colony__c> mpCOLONY = new map<Id,Colony__c>([SELECT Id,Name From Colony__c where id=:lsIDCOLO]); map<Id,Contact> mpCONTACT = new map<Id,Contact>([SELECT Id,Name From Contact where id=:lsIDCONT AND MailingCity=null AND MailingState=null]); for(Case Issue: cases){ if(mpCONTACT.containsKey(Issue.ContactId)){ Contact cont = mpCONTACT.get(Issue.ContactId); cont.MailingCountry= (Issue.Country__c == null)?'':Issue.Country__c; cont.MailingStreet= ((Issue.Street__c == null)?'':Issue.Street__c) + ' ' + ((Issue.Street_number__c == null)?'':Issue.Street_number__c); cont.MailingCity= (Issue.City__c == null || !mpCITY.containsKey(Issue.City__c))?'':mpCITY.get(Issue.City__c).Name; cont.MailingState= (Issue.State__c == null)?'':Issue.State__c; cont.MailingPostalCode= (Issue.Zip_Code__c == null)?'':Issue.Zip_Code__c; cont.Colony__c= (Issue.Colony__c == null || !mpCOLONY.containsKey(Issue.Colony__c))?'':mpCOLONY.get(Issue.Colony__c).Name; cont.Between_Streets__c= (Issue.Between_Streets__c == null)?'':Issue.Between_Streets__c; cont.Reference__c= (Issue.References__c == null)?'':Issue.References__c; cont.Place__c= (Issue.Place__c == null)?'':Issue.Place__c; }//if }//for if(!mpCONTACT.isEmpty()) update mpCONTACT.values(); }//updateRelatedContact //---------------------------------------------------------------------- public void updateFrecuencyIncidence(list<Case> cases){ searchServiceCenter(cases); for(Case c: cases){ Account center = assignServiceCenter(c.Colony__c); if(center.Id != null) { c.Service_Center__c=center.Id; c.Service_center_email__c=center.E_mail__c; c.Status = 'Assigned'; // Changed value from 'center.AccountID' to 'c.Contact.AccountId' #(Task: , Story:S-266263) c.AccountID = c.Contact.AccountId; System.debug(' Case Center Id :' + center.Id); System.debug(' Case Service Center :' + c.Service_Center__c); System.debug('Case Service Center email :' + c.Service_center_email__c); System.debug('Case Status :' + c.Status); //------Added by Vinoth----------- //-------------------------------- } else { c.addError('No existe un Centro de Servicio registrado con cobertura para esta colonia. There is no Service Center Coverage for this Neighborhood'); }//if }//for } //---------------------------------------------------------------------- public void searchServiceCenter(list<Case> cases){ list<Id> lsColony = new list<Id>(); for(Case c: cases){ lsColony.add(c.Colony__c); //lsCity.add(c.City__c); vDueDay = c.Due_Day__c; vDueTimeDoub = c.Due_Time__c; Classification = c.Classification__c; System.debug('vDueTimeDoub :' + vDueTimeDoub); }//for // Get all the 'Service Centers Ids' for this colony that provides 'Home Delivery' list<Service_Center_Coverage__c >lsCover = new list<Service_Center_Coverage__c >([Select id,Colony__c,Service_Center__c FROM Service_Center_Coverage__c Where Colony__c=: lsColony AND Service_Center__r.RecordType.Name = 'LTH Service Center' and Service_Center__r.Service_Center_Type__c = 'Red LTH SC' and Service_Center__r.Home_delivery_service__c = true]); list<Id> lsACC = new list<Id>(); for(Service_Center_Coverage__c csc :lsCover){ lsACC.add(csc.Service_Center__c); System.debug('* 2. SC Coverage : '+ csc.id); }//for mpCoverDC = new map<String,list<Account>>(); //map<Id,Account> mpAccount ; map<Id,Account> mpAccount = new map<Id,Account>(); // Query for all the Account that provides 'Home Delivery' in this colony if (vDueDay == 'Saturday' && Classification== 'Home Service - Scheduled') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Saturday__c <> 'Closed' AND Closing_Hours_Saturday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Saturday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); }//vDueDay == 'Saturday' else if (vDueDay == 'Sunday' && Classification== 'Home Service - Scheduled') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Sunday__c <> 'Closed' AND Closing_Hours_Sunday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Sunday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); }//vDueDay == 'Sunday' else if ((vDueDay == 'Monday' || vDueDay == 'Tuesday' || vDueDay == 'Wednesday' || vDueDay == 'Thursday' || vDueDay == 'Friday') && Classification == 'Home Service - Scheduled' ) { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Monday_to_Friday__c <> 'Closed' AND Closing_Hours_Monday_to_Friday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Monday_to_Friday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); }//vDueDay == Weekdays else if (vDueDay == 'Saturday' && Classification == 'Home Service') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Sunday__c <> 'Closed' AND Closing_Hours_Sunday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Sunday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); } else if (vDueDay == 'Sunday' && Classification == 'Home Service') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Sunday__c <> 'Closed' AND Closing_Hours_Sunday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Sunday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); } else if ((vDueDay == 'Monday' || vDueDay == 'Tuesday' || vDueDay == 'Wednesday' || vDueDay == 'Thursday' || vDueDay == 'Friday') && Classification == 'Home Service' ) { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Monday_to_Friday__c <> 'Closed' AND Closing_Hours_Monday_to_Friday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Monday_to_Friday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); } system.debug('* Service Centers found : ' + mpAccount.keySet()); calculateFrequencyNIncidents(mpAccount.values()); for(Case c: cases){ String COLONY = c.Colony__c; list<Account> lsTMP = new list<Account>(); for(Service_Center_Coverage__c csc:lsCover){ if(csc.Colony__c==COLONY && mpAccount.containsKey(csc.Service_Center__c)) lsTMP.add(mpAccount.get(csc.Service_Center__c)); }//for system.debug('lsTMP '+lsTMP); mpCoverDC.put(COLONY,lsTMP); } }//searchServiceCenter //---------------------------------------------------------------------- public map<String,list<Account>> searchServiceCentersforrejected(list<Case> cases){ //$$ method return type changed system.debug('##entry into searchServiceCenter ##'); list<Id> lsColony = new list<Id>(); list<Id> lsACC = new list<Id>(); //$$ list<Id> lsAlredyAssignedACC = new list<Id>(); //$$ to hold the already assigned srvc centre ids Set<Id> allCaseId = new Set<Id>(); list<Service_Center_Case_Status__c> allRelatedSrvcCntrCaseStatus = new list<Service_Center_Case_Status__c>(); //$$----- Set<Id> allRelatedServiceCenterIds = new Set<Id>(); //$$--------------- for(Case c: cases){ lsColony.add(c.Colony__c); allCaseId.add(c.id); //$$------------ //lsCity.add(c.City__c); vDueDay = c.Due_Day__c; vDueTimeDoub = c.Due_Time__c; //vDueTimeDouble = c.DueTime__c; Classification = c.Classification__c; System.debug('vDueTimeDoub :' + vDueTimeDoub); }//for //$$--------------------------------- system.debug('##allCaseId##'+allCaseId); allRelatedSrvcCntrCaseStatus = [SELECT Service_Center__c,Case_Number__c FROM Service_Center_Case_Status__c WHERE Case_Number__c in: allCaseId]; system.debug('##allRelatedSrvcCntrCaseStatus ##'+allRelatedSrvcCntrCaseStatus ); if(allRelatedSrvcCntrCaseStatus.size()>0) { for(Service_Center_Case_Status__c sCCSVar: allRelatedSrvcCntrCaseStatus) { allRelatedServiceCenterIds.add(sCCSVar.Service_Center__c); } } system.debug('##allRelatedServiceCenterIds##'+allRelatedServiceCenterIds); //$$---------------------- // Get all the 'Service Centers Ids' for this colony that provides 'Home Delivery' //$$------------- list<Service_Center_Coverage__c >lsCover = new list<Service_Center_Coverage__c >([Select id,Colony__c,Service_Center__c FROM Service_Center_Coverage__c Where Colony__c=: lsColony AND Service_Center__r.RecordType.Name = 'LTH Service Center' and Service_Center__r.Service_Center_Type__c = 'Red LTH SC' and Service_Center__r.Home_delivery_service__c = true AND Service_Center__r.Id NOT in: allRelatedServiceCenterIds]); system.debug('##lsCover ##'+lsCover ); if(lsCover.size() > 0) { lsACC = new list<Id>(); for(Service_Center_Coverage__c csc :lsCover){ lsACC.add(csc.Service_Center__c); System.debug('## SC Coverage option ##: '+ csc.id); }//for }// end of if else{ system.debug('## NO SERVICE CENTER AVAILABLE'); } system.debug('##lsACC ##'+lsACC); mpCoverDC = new map<String,list<Account>>(); //map<Id,Account> mpAccount ; map<Id,Account> mpAccount = new map<Id,Account>(); // Query for all the Account that provides 'Home Delivery' in this colony if (vDueDay == 'Saturday' && Classification== 'Home Service - Scheduled') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Saturday__c <> 'Closed' AND Closing_Hours_Saturday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Saturday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); }//vDueDay == 'Saturday' else if (vDueDay == 'Sunday' && Classification== 'Home Service - Scheduled') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Sunday__c <> 'Closed' AND Closing_Hours_Sunday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Sunday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); }//vDueDay == 'Sunday' else if ((vDueDay == 'Monday' || vDueDay == 'Tuesday' || vDueDay == 'Wednesday' || vDueDay == 'Thursday' || vDueDay == 'Friday') && Classification == 'Home Service - Scheduled' ) { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Monday_to_Friday__c <> 'Closed' AND Closing_Hours_Monday_to_Friday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Monday_to_Friday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); }//vDueDay == Weekdays else if (vDueDay == 'Saturday' && Classification == 'Home Service') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Sunday__c <> 'Closed' AND Closing_Hours_Sunday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Sunday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); } else if (vDueDay == 'Sunday' && Classification == 'Home Service') { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Sunday__c <> 'Closed' AND Closing_Hours_Sunday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Sunday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); } else if ((vDueDay == 'Monday' || vDueDay == 'Tuesday' || vDueDay == 'Wednesday' || vDueDay == 'Thursday' || vDueDay == 'Friday') && Classification == 'Home Service' ) { mpAccount = new map<id,Account> ([Select id, Name, E_mail__c,Frecuency__c, Incidence__c, Closing_Hours_Monday_to_Friday__c,Closing_Hours_Saturday__c,Closing_Hours_Sunday__c, Opening_Hours_Saturday_Int__c,Opening_Hours_Sunday_Int__c,Opening_Hours_Monday_to_Friday_Int__c FROM Account Where Id =: lsACC AND Closing_Hours_Monday_to_Friday__c <> 'Closed' AND Closing_Hours_Monday_to_Friday_Int__c >= :(vDueTimeDoub + 1) AND Opening_Hours_Monday_to_Friday_Int__c <= :vDueTimeDoub order by Frecuency__c, Incidence__c]); } system.debug('* Service Centers found : ' + mpAccount.keySet()); calculateFrequencyNIncidents(mpAccount.values()); for(Case c: cases){ String COLONY = c.Colony__c; list<Account> lsTMP = new list<Account>(); for(Service_Center_Coverage__c csc:lsCover){ if(csc.Colony__c==COLONY && mpAccount.containsKey(csc.Service_Center__c)) lsTMP.add(mpAccount.get(csc.Service_Center__c)); }//for system.debug('##lsTMP ##'+lsTMP); //$$------------ system.debug('##lsTMP@@'+lsTMP); //$$------------- mpCoverDC.put(COLONY,lsTMP); } return mpCoverDC; }//searchServiceCentersforrejected //---------------------------------------------------------------------------------------------------------- private void calculateFrequencyNIncidents(list<Account> Accs){ Service_Center_Selector__c scs = Service_Center_Selector__c.getInstance(UserInfo.getProfileId()); //Custom Hierarchy settings double Incid = (scs==null || scs.Incidents_Range_Days__c ==null )?1:scs.Incidents_Range_Days__c; Date d= system.today().addDays(Incid.intValue()*-1); System.debug('****Incidence Date****:' +d); // Changed the RecordType from "Rejected Service" to 'MX RedLTH Consumer Call' and added the Status "Declined" by Vinoth AggregateResult[] grpINC = [Select Count(id) TOT,Service_Center__c FROM Case Where Service_Center__c in : Accs and RecordType.Name = 'MX RedLTH Consumer Call' and Status='Declined' and CreatedDate >=: d GROUP BY Service_Center__c]; map<Id,Integer> mpINCIDENCES = new map<Id,Integer>(); for(AggregateResult AR: grpINC) mpINCIDENCES.put(Id.valueOf(String.valueOf(AR.get('Service_Center__c'))),Integer.valueOf(AR.get('TOT'))); //FREQUENCY double Frec = (scs==null || scs.Frequency_Range_Days__c ==null )?1:scs.Frequency_Range_Days__c; d= system.today().addDays(Frec.intValue()*-1); System.debug('***Frequency Date****:' +d); // Changed the record type from 'Home service' to 'MX RedLTH Consumer Call' #(T-325212) AggregateResult[] grpFRC = [Select Count(id) TOT,Service_Center__c FROM Case Where Service_Center__c in : Accs and RecordType.Name = 'MX RedLTH Consumer Call' and Status='Assigned' and CreatedDate >=: d GROUP BY Service_Center__c]; map<Id,Integer> mpFREQUENCY = new map<Id,Integer>(); for(AggregateResult AR: grpFRC) mpFREQUENCY.put(Id.valueOf(String.valueOf(AR.get('Service_Center__c'))),Integer.valueOf(AR.get('TOT'))); for(Account A:Accs){ A.Frecuency__c = (mpFREQUENCY.containsKey(A.Id))?mpFREQUENCY.get(A.Id):0; System.debug('****Frequency****:' +A.Frecuency__c ); A.Incidence__c = (mpINCIDENCES.containsKey(A.Id))?mpINCIDENCES.get(A.Id):0; System.debug('****Incidence****:' + A.Incidence__c ); }//for }//calculateFrequencyNIncidents //---------------------------------------------------------------------- public Account assignServiceCenter(String Colony){ Account center = new Account(); Boolean assignment = false; if(mpCoverDC.containsKey(Colony)){ list<Account> lsAccount = mpCoverDC.get(Colony); for(Account acc : lsAccount){ if(assignment==false || (acc.Frecuency__c==center.Frecuency__c && acc.Incidence__c<center.Incidence__c) || (acc.Frecuency__c<center.Frecuency__c)){ center.Id=acc.Id; center.E_mail__c=acc.E_mail__c; center.Frecuency__c=acc.Frecuency__c; center.Incidence__c=acc.Incidence__c; assignment=true; System.debug('****CenterId****:' + center.Id ); System.debug('****CenterEmail****:' + center.E_mail__c ); System.debug('****CenterFrequency****:' + center.Frecuency__c ); System.debug('****CenterIncidence****:' + center.Incidence__c ); }//if }//for } //This method is added to update the account record (Task: T-325212) if(center != null) { updateAccountRecord(center); }//if return center; }//assignServiceCenter private void updateAccountRecord(Account cen) { List<Account> acc = [SELECT Id, Frecuency__c, Incidence__c, Opening_Hours_Monday_to_Friday__c, Closing_Hours_Monday_to_Friday__c, Opening_Hours_Saturday__c, Closing_Hours_Saturday__c, Opening_Hours_Sunday__c, Closing_Hours_Sunday__c FROM Account WHERE Id =:cen.Id LIMIT 1]; If (acc.size()>0) { if(acc[0].Frecuency__c != null) { acc[0].Frecuency__c++; }//if else { acc[0].Frecuency__c = 1; } update acc; }//If (acc.size()>0) }//updateAccountRecord }
- vinothk balasubramanian
- October 14, 2015
- Like
- 0
why does the Account ID equal Null
I am passing a person ID to a function that creates opportunities.
I am completely stumped because the Account ID equals null.
If it makes any difference, the account is a person account
below is the code:
static void CreateServices(Account a)
{
system.debug(a.FirstName+'firstname'+a.Id); //when I do this the names print but not the ID. What is going on?
List<RecordType> opRecordType = [SELECT id, Name FROM RecordType WHERE SobjectType = 'Opportunity'];
For (RecordType rt: opRecordType)
{
Opportunity newOpp= new opportunity();
newOpp.Name='test' +i;
newOpp.RecordTypeId=rt.ID;
i++;
newOpp.AccountId= a.Id;
system.debug('account ID'+a.Id);
... //code adds more details to the opportunity.
createdServices.add(newOpp);
}
}
I am completely stumped because the Account ID equals null.
If it makes any difference, the account is a person account
below is the code:
static void CreateServices(Account a)
{
system.debug(a.FirstName+'firstname'+a.Id); //when I do this the names print but not the ID. What is going on?
List<RecordType> opRecordType = [SELECT id, Name FROM RecordType WHERE SobjectType = 'Opportunity'];
For (RecordType rt: opRecordType)
{
Opportunity newOpp= new opportunity();
newOpp.Name='test' +i;
newOpp.RecordTypeId=rt.ID;
i++;
newOpp.AccountId= a.Id;
system.debug('account ID'+a.Id);
... //code adds more details to the opportunity.
createdServices.add(newOpp);
}
}
- Aidel Bruck
- October 08, 2015
- Like
- 0
The Add row functionality is not working in my code. can someone help me to resolve my issue.
Hi,
I pasted my code below and darked area is an issue one.
public class AllUserList
{
public list<SelectOption> selectedobject { get; set; }
public String objectName { get; set; }
public list<SelectOption> fieldsName {get;set;}
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<string,EmailTemplate> alltemplate;
Map<string,string> FieldType = new Map<string,string>();
Map<string,string> fieldTypes=new Map<string,string>();
public list<SelectOption> open{get;set;}
public list<selectoption> templates{get;set;}
public list<wrapperclass> value{get;set;}
public list<Sobject> rowlist{get;set;}
// Public list<Wrapper> wrap{get;set;}
Public List<sobject> val4{get;set;}
Public List<Contact> conList = new List<Contact>();
public string templatename{get;set;}
public Integer totalRecords;
public Integer sno=0;
public string templateid{get;set;}
Public string FieldName{get;set;}
public string query{get;set;}
public string Fname1{get;set;}
public string Operator1{get;set;}
public string Value1{get;set;}
public void search()
{
string whereQuery='select id,Name,Email from ObjectName';
string whereclause ='where';
if(Fname1!='' && Fname1!=null && Operator1!='' && Operator1!=null && Value1!='' && Value1!=null)
{
whereQuery=whereQuery+retwhereQuery(Fname1,Operator1,Value1)+' and ';
}
if(objectName=='Contact')
{
whereQuery = ' select id,Email,Name' + ' from ' + objectName + ' where ' + retwhereQuery(Fname1,Operator1,Value1);
}
else
if(objectName=='Lead')
{
whereQuery = ' select id,Email,Name' + ' from ' + objectName + ' where ' + retwhereQuery(Fname1,Operator1,Value1);
}
else
if(objectName=='User')
{
whereQuery = ' select id,Email,Name' + ' from ' + objectName + ' where ' + retwhereQuery(Fname1,Operator1,Value1);
}
if(whereQuery.contains('and'))
whereQuery = whereQuery.subString(0,whereQuery.lastIndexOf('and'));
system.debug('################################################'+Query);
val4 = Database.query(whereQuery);
value=new list<wrapperclass>();
// wrap = new list<Wrapper>();
for(Sobject s:val4)
{
wrapperclass wr = new wrapperclass('s.Email','s.Name',false,s.id,sno);
wr.email=string.valueof(s.get('Email'));
wr.name= string.valueof(s.get('Name'));
value.add(wr);
system.debug('^^^^^^^^^^^^^'+value);
}
system.debug('$$$$$$$$$$$$$'+value);
}
public class wrapperclass
{
public string id{get;set;}
public string name{get;set;}
public string email{get;set;}
public Boolean checked{get;set;}
public string snumber{get;set;}
public wrapperclass(string email,string name,Boolean checked,string id,Integer sno)
{
this.id=id;
this.Name=name;
this.Email=email;
this.checked=checked;
snumber=String.valueOf(sno);
}
}
/* public class wrapper
{
public Integer sno{get;set;}
public wrapper(Integer sno)
{
this.sno=sno;
}
} */
public AllUserList()
{
value = new List<wrapperclass>();
// addrow();
// wrap = new List<Wrapper>();
templates = new list<selectoption>();
templates.add(new selectoption('','--None--'));
val4 = new List<sobject> ();
rowlist = new List<Sobject>();
totalRecords=0;
String folderId = [Select Id,Name From Folder where Name = 'Email'].Id;
system.debug('????????????'+folderId );
alltemplate = new map<string,EmailTemplate>();
for(EmailTemplate fd: [Select Body, HtmlValue, Id, Name, Subject from EmailTemplate where FolderId=:folderId])
{
templates.add(new selectoption(fd.Name,fd.Name));
alltemplate.put(fd.Name,fd);
}
system.debug('++++++++++++'+alltemplate);
}
public list<selectoption> getobject()
{
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('','--None--'));
for(Schema.SObjectType f : gd)
{
if(!f.getDescribe().isCustomSetting() && f.getDescribe().isAccessible() && f.getDescribe().isCreateable() && f.getDescribe().isSearchable() && f.getDescribe().isQueryable())
{
if(string.valueof(f.getDescribe().getName()) == 'Lead' || string.valueof(f.getDescribe().getName()) == 'Contact' || string.valueof(f.getDescribe().getName()) == 'User')
options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getLabel()));
}
options.sort();
}
return options;
}
public List<SelectOption> getfd()
{
List<SelectOption> fieldsName =new List<SelectOption>();
if(objectName != null)
{
system.debug('!!!!!!!'+objectName );
Map <String, Schema.SObjectField> fieldMap= Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.values())
{
schema.describefieldresult dfield = sfield.getDescribe();
fieldTypes.put(string.valueof(dfield.getName()),string.valueof(dfield.getType()));
fieldsName.add(new SelectOption(dfield.getName(),dfield.getLabel()));
}
}
return fieldsName;
}
public List<SelectOption> getSelect()
{
List<SelectOption> option = new List<SelectOption>();
option=getSearchOperator(Fname1);
return option;
return open;
}
/* public void add()
{
sno=sno+1;
addrow();
} */
public void addrow()
{
rowlist = new List<Sobject>();
totalRecords=0;
sno = value.size();
system.debug('@@@@@@@@@@@@@'+sno);
for(Sobject s:val4)
{
wrapperclass wr = new wrapperclass('s.Email','s.Name',false,s.id,sno);
value.add(wr);
}
system.debug('$$$$$$$$$$$$$$$'+value);
}
public void removerow()
{
if(value.size() > 1)
{
value.remove(value.size()-1);
}
}
}
Thanks.
I pasted my code below and darked area is an issue one.
public class AllUserList
{
public list<SelectOption> selectedobject { get; set; }
public String objectName { get; set; }
public list<SelectOption> fieldsName {get;set;}
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<string,EmailTemplate> alltemplate;
Map<string,string> FieldType = new Map<string,string>();
Map<string,string> fieldTypes=new Map<string,string>();
public list<SelectOption> open{get;set;}
public list<selectoption> templates{get;set;}
public list<wrapperclass> value{get;set;}
public list<Sobject> rowlist{get;set;}
// Public list<Wrapper> wrap{get;set;}
Public List<sobject> val4{get;set;}
Public List<Contact> conList = new List<Contact>();
public string templatename{get;set;}
public Integer totalRecords;
public Integer sno=0;
public string templateid{get;set;}
Public string FieldName{get;set;}
public string query{get;set;}
public string Fname1{get;set;}
public string Operator1{get;set;}
public string Value1{get;set;}
public void search()
{
string whereQuery='select id,Name,Email from ObjectName';
string whereclause ='where';
if(Fname1!='' && Fname1!=null && Operator1!='' && Operator1!=null && Value1!='' && Value1!=null)
{
whereQuery=whereQuery+retwhereQuery(Fname1,Operator1,Value1)+' and ';
}
if(objectName=='Contact')
{
whereQuery = ' select id,Email,Name' + ' from ' + objectName + ' where ' + retwhereQuery(Fname1,Operator1,Value1);
}
else
if(objectName=='Lead')
{
whereQuery = ' select id,Email,Name' + ' from ' + objectName + ' where ' + retwhereQuery(Fname1,Operator1,Value1);
}
else
if(objectName=='User')
{
whereQuery = ' select id,Email,Name' + ' from ' + objectName + ' where ' + retwhereQuery(Fname1,Operator1,Value1);
}
if(whereQuery.contains('and'))
whereQuery = whereQuery.subString(0,whereQuery.lastIndexOf('and'));
system.debug('################################################'+Query);
val4 = Database.query(whereQuery);
value=new list<wrapperclass>();
// wrap = new list<Wrapper>();
for(Sobject s:val4)
{
wrapperclass wr = new wrapperclass('s.Email','s.Name',false,s.id,sno);
wr.email=string.valueof(s.get('Email'));
wr.name= string.valueof(s.get('Name'));
value.add(wr);
system.debug('^^^^^^^^^^^^^'+value);
}
system.debug('$$$$$$$$$$$$$'+value);
}
public class wrapperclass
{
public string id{get;set;}
public string name{get;set;}
public string email{get;set;}
public Boolean checked{get;set;}
public string snumber{get;set;}
public wrapperclass(string email,string name,Boolean checked,string id,Integer sno)
{
this.id=id;
this.Name=name;
this.Email=email;
this.checked=checked;
snumber=String.valueOf(sno);
}
}
/* public class wrapper
{
public Integer sno{get;set;}
public wrapper(Integer sno)
{
this.sno=sno;
}
} */
public AllUserList()
{
value = new List<wrapperclass>();
// addrow();
// wrap = new List<Wrapper>();
templates = new list<selectoption>();
templates.add(new selectoption('','--None--'));
val4 = new List<sobject> ();
rowlist = new List<Sobject>();
totalRecords=0;
String folderId = [Select Id,Name From Folder where Name = 'Email'].Id;
system.debug('????????????'+folderId );
alltemplate = new map<string,EmailTemplate>();
for(EmailTemplate fd: [Select Body, HtmlValue, Id, Name, Subject from EmailTemplate where FolderId=:folderId])
{
templates.add(new selectoption(fd.Name,fd.Name));
alltemplate.put(fd.Name,fd);
}
system.debug('++++++++++++'+alltemplate);
}
public list<selectoption> getobject()
{
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('','--None--'));
for(Schema.SObjectType f : gd)
{
if(!f.getDescribe().isCustomSetting() && f.getDescribe().isAccessible() && f.getDescribe().isCreateable() && f.getDescribe().isSearchable() && f.getDescribe().isQueryable())
{
if(string.valueof(f.getDescribe().getName()) == 'Lead' || string.valueof(f.getDescribe().getName()) == 'Contact' || string.valueof(f.getDescribe().getName()) == 'User')
options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getLabel()));
}
options.sort();
}
return options;
}
public List<SelectOption> getfd()
{
List<SelectOption> fieldsName =new List<SelectOption>();
if(objectName != null)
{
system.debug('!!!!!!!'+objectName );
Map <String, Schema.SObjectField> fieldMap= Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.values())
{
schema.describefieldresult dfield = sfield.getDescribe();
fieldTypes.put(string.valueof(dfield.getName()),string.valueof(dfield.getType()));
fieldsName.add(new SelectOption(dfield.getName(),dfield.getLabel()));
}
}
return fieldsName;
}
public List<SelectOption> getSelect()
{
List<SelectOption> option = new List<SelectOption>();
option=getSearchOperator(Fname1);
return option;
return open;
}
/* public void add()
{
sno=sno+1;
addrow();
} */
public void addrow()
{
rowlist = new List<Sobject>();
totalRecords=0;
sno = value.size();
system.debug('@@@@@@@@@@@@@'+sno);
for(Sobject s:val4)
{
wrapperclass wr = new wrapperclass('s.Email','s.Name',false,s.id,sno);
value.add(wr);
}
system.debug('$$$$$$$$$$$$$$$'+value);
}
public void removerow()
{
if(value.size() > 1)
{
value.remove(value.size()-1);
}
}
}
Thanks.
- salesforce@14
- April 22, 2015
- Like
- 0
Oncomplete issues with apex commandButton
Folks.
I am using <apex:commandButton value="Next" action="{!method1}" rerender="test" oncomplete="complete1();"/>
Once the method1 executes, it updates a boolean variable to 'true' and in the constructor this variable value is set as false
public void method1(){
fieldstatus='true';
//system.debug('fieldstatus:'+fieldstatus);
}
Now on VF page , i want to access this variable value so used oncomplete, but in the oncomplete function i always got the value as false.
function complete1() {
var check1= '{!fieldstatus}';
alert(check1);
}
Any idea why this wierd behaviour?
I am using <apex:commandButton value="Next" action="{!method1}" rerender="test" oncomplete="complete1();"/>
Once the method1 executes, it updates a boolean variable to 'true' and in the constructor this variable value is set as false
public void method1(){
fieldstatus='true';
//system.debug('fieldstatus:'+fieldstatus);
}
Now on VF page , i want to access this variable value so used oncomplete, but in the oncomplete function i always got the value as false.
function complete1() {
var check1= '{!fieldstatus}';
alert(check1);
}
Any idea why this wierd behaviour?
- Abhik Dey
- April 22, 2015
- Like
- 0
issues with test class on account owner change
Can anyone help please, I think I'm just getting lost and going in circles with this test class. No matter how I compare the new value with the old I still can't get the test to cover the comparison part in my trigger. Please help me fix this.
***************************************************************************************************** @isTest private class testAccOwner { public static testMethod void testAccOwnerChange() { test.startTest(); List<User> usrList = new List<User>(); User testUser2 = [Select Id, ManagerId from User where IsActive = true limit 1]; User testUser3 = [Select Id, ManagerId from User where IsActive = true limit 1]; User testUser1 = new User(alias = 'TstUsr1',Firstname='tst1', email='newuserDP@testorg.com', emailencodingkey='UTF-8', lastname='Tst11', languagelocalekey='en_US', localesidkey='en_US', profileid = 'idNumer04', timezonesidkey='America/Los_Angeles', username='newuser11@testorg.com', UserRoleId = 'idNumer03',Country_picklist__c = 'UNITED STATES', Global_Region__c = 'US', DIRECTOR_NM__c=testUser2.id, ManagerId = testUser3.Id); User testUser4 = new User(alias = 'TstUsr2',Firstname='tst2', email='newuserDP2@testorg.com', emailencodingkey='UTF-8', lastname='Tst112', languagelocalekey='en_US', localesidkey='en_US', profileid = 'idNumer04', timezonesidkey='America/Los_Angeles', username='newuser112@testorg.com', UserRoleId = 'idNumer03',Country_picklist__c = 'UNITED STATES', Global_Region__c = 'US', DIRECTOR_NM__c=testUser2.id, ManagerId = 'idNumer02'); //insert testUser1; usrList.add(testUser1); usrList.add(testUser4); insert usrList; System.runAs(testUser1){ Account acc = new Account(Name = 'Febe01', OwnerId = 'idNumer01', Previous_Account_Owner__c = 'idNumer01'); insert acc; system.assert(acc.Previous_Account_Owner__c == acc.OwnerId); acc.OwnerId = testUser1.Id; acc.Previous_Account_Owner__c = 'idNumer01'; update acc; //system.assertEquals('idNumer01', acc.Previous_Account_Owner__c); system.assert(acc.Previous_Account_Owner__c != acc.OwnerId); system.debug('New account owner : ' + acc.OwnerId + 'Old Account owner: ' + acc.Previous_Account_Owner__c); } List<Account> lstNewAcc = [select id, name, ownerId from Account where ownerId =:testUser2.Id]; List<Account> lstOldAcc = [select id, name, ownerId from Account where ownerId =:testUser1.Id]; map<Id, Account> oldmap = new map<Id, Account>(); map<Id, Account> newmap = new map<Id, Account>(); for(Account oldAccts : lstOldAcc) { oldmap.put(oldAccts.Id, oldAccts); } for(Account newAct : lstNewAcc) { Account oldAc = oldmap.get(newAct.Id); if(newAct.OwnerId != oldAc.OwnerId){ newAct.Previous_Account_Owner__c = oldAc.OwnerId; system.assert(newAct.OwnerId != oldAc.OwnerId); newmap.put(newAct.Id, newAct); } } system.debug('*********************************** Account oldmap: '+ oldmap); test.stopTest(); } } *************************************************************************************************** This is the trigger: trigger AccOwnerChange on Account (before update) { if(INTLStaticObjectHelper.isAccOwnerChangeExecuted){ return; } INTLStaticObjectHelper.isAccOwnerChangeExecuted = true; Set<Id> setUserIds = new Set<Id>(); Map<Id, User> mapUserObj = new Map<Id, User>(); for(Account a : Trigger.new) { Account oldObj = Trigger.oldmap.get(a.id); if(a.ownerId != oldObj.ownerId){ setUserIds.add(a.OwnerId); setUserIds.add(oldObj.ownerId); } } system.debug('test ###' + setUserIds); if(setUserIds.size()>0){ List<User> lstUser = [select Id, Name, ManagerId from User where Id in :setUserIds AND isActive = true]; for(User usrObj : lstUser){ mapUserObj.put(usrObj.Id, usrObj); } } system.debug('test ###' + mapUserObj); for(Account a : Trigger.new) { Account oldObj = Trigger.oldmap.get(a.id); if(a.ownerId != oldObj.ownerId){ a.Previous_Account_Owner__c = oldObj.ownerId; if(mapUserObj.get(a.Previous_Account_Owner__c)!=null){ a.Previous_Account_Owner_s_Manager__c = mapUserObj.get(a.Previous_Account_Owner__c).ManagerId; } if(mapUserObj.get(a.ownerId) != null){ a.New_Account_Owner_s_Manager__c = mapUserObj.get(a.ownerId).ManagerId; } } }
- Febe Nagy
- February 18, 2015
- Like
- 0
Apex governor limit warning/Debug logs
Hi,
I have been recieving an Apex governor limit warning (Number of SOQL queries: 97 out of 100) after making an update on an Opportunity and decided to look into reasons behind it. Now I am confused and need help.
Here is the deal. We have 3 or 3 different triggers on an Opportunity object, but for now lets concentrate on one. Trigger name is "Update_Split_Quota" and it is after update type trigger. Here is the code (I know it is not idel, it is still work in proggress):
Attached is a small snapshot of the Debug log file showing how my trigger is called and the number of time it is being called
I have been recieving an Apex governor limit warning (Number of SOQL queries: 97 out of 100) after making an update on an Opportunity and decided to look into reasons behind it. Now I am confused and need help.
Here is the deal. We have 3 or 3 different triggers on an Opportunity object, but for now lets concentrate on one. Trigger name is "Update_Split_Quota" and it is after update type trigger. Here is the code (I know it is not idel, it is still work in proggress):
trigger Update_Split_Quota on Opportunity (After Update) { Opportunity[] OppIdNew = Trigger.new; Opportunity[] OppIdOld = Trigger.old; if (Trigger.isAfter){ List<Opportunity> olis = [SELECT Id,AccountId FROM Opportunity WHERE Id IN: Trigger.newMap.keySet()]; for(Opportunity opp: olis){ List<OpportunitySplit> oppsplit = [SELECT Id, OpportunityId, SplitOwnerId, Sales_Quota__c, Legal_Accepted_Date__c FROM OpportunitySplit WHERE OpportunityId = :opp.id]; Account[] account = [Select OwnerId FROM Account Where ID = :opp.AccountID]; if(OppIdNew[0].Order_Type__c=='Services Only'&& OppIdNew[0].StageName == 'Closed Won'){ opp.OwnerId = account[0].OwnerId; //update opp; } for (OpportunitySplit os:oppsplit) { if(os.Legal_Accepted_Date__c != null) { //Only run the trigger if legal accepted date Month_Start = os.Legal_Accepted_Date__c.toStartOfMonth(); //date Month_End = Month_Start.addMonths(1); List<Sales_Quota__c> sales = [SELECT Id, User__C,Month__c, Quarter__c FROM Sales_Quota__c WHERE (User__C = :os.SplitOwnerId) AND (Month__c=:Month_Start) LIMIT 1];//(Quarter__c = THIS_YEAR) AND (User__C = :oppsplit.SplitOwner.id) if(sales.size()!=0) { //for users who do not have quotas Sales_Quota__c s = sales.get(0); os.Sales_Quota__c=s.ID;//Sales_Quota__c = s.ID; update oppsplit; } } } } } }But when I do an update on an Opportunity it does exactly what I want it to do, and I immidiatly get an email with governor limit warning. So I decided to run a debug log to see what is going on, and this is the confusing part. In the log I see that this trigger is being called 6 different time. Each time it is called 3 Select statements inside it are run, and it add up to a lot (18 out 100 possible). My question is WHY DOES IT GET CALLED 6 DIFFERENT TIMES if I only update a single Opportunity (I update an existing Opp, not creating a new one. I simply switch the stage to "Closed Won").
Attached is a small snapshot of the Debug log file showing how my trigger is called and the number of time it is being called
- Art Smorodin
- February 18, 2015
- Like
- 0
Visualforce Error - Formula Expression is required on the action attributes
Hi
On my commandButton action I call custom controller method. I have all code in method commented (except return statement). And still get Formula Expression is required on the action attributes error whe I submit. See alot of post on this but none helping..
Here is VF page
<apex:page controller="pickListScholarshipController" >
<apex:form >
<apex:pageBlock title="Schoalrship Application Assignment " id="out">
<apex:pageBlockButtons >
<apex:commandButton value="Assign Readers" action="{!insertScoringRecords}" rerender="out" status="actStatusId"/>
<apex:commandButton value="Email Readers" action="{!submit}" rerender="out" status="actStatusId"/>
<apex:actionStatus id="actStatusId">
<apex:facet name="start">
<img src="/img/loading.gif" />
</apex:facet>
</apex:actionStatus>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Select Scholarship then Save button" collapsible="false">
<apex:selectList value="{!selectedScholarship}" multiselect="false" size="1">
<apex:selectOption itemValue="{!selectedScholarship}" itemLabel="{!selectedScholarship}" />
<apex:selectOption itemValue="Alumni Endowed Scholarship" itemLabel="Alumni Endowed Scholarship"/>
<apex:selectOption itemValue="Danny Burkett Memorial Scholarship" itemLabel="Danny Burkett Memorial Scholarship"/>
<apex:selectOption itemValue="Kyle O'Connell Memorial Scholarship" itemLabel="Kyle O'Connell Memorial Scholarship"/>
<apex:selectOption itemValue="Senior Class Legacy Scholarship" itemLabel="Senior Class Legacy Scholarship"/>
<apex:selectOption itemValue="Kyle O'Connell Memorial Scholarship" itemLabel="Kyle O'Connell Memorial Scholarship"/>
<apex:selectOption itemValue="Terry Whitcomb Scholarship" itemLabel="Terry Whitcomb Scholarship"/>
<apex:selectOption itemValue="Beckman Program Application" itemLabel="Beckman Program Application"/>
<apex:selectOption itemValue="SURE Scholarship" itemLabel="SURE Scholarship"/>
<apex:selectOption itemValue="PURE Scholarship" itemLabel="PURE Scholarship"/>
</apex:selectList>
<apex:outputText value="{!selectedScholarship}" label="You have selected:"/>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>
And controller:
public class pickListScholarshipController {
public String selectedScholarship;
public pickListScholarshipController (){
}
public PageReference save(){
return null;
}
public PageReference submit() {
return null;
}
public String getSelectedScholarship() {
return selectedScholarship;
}
public void setSelectedScholarship(String s) {
selectedScholarship = s;
}
public String insertScoringRecords() {
/*
USD_Scholarship_Scoring__c[] scoringRecs;
USD_Roles__c[] readers;
Date today = Date.today();
Integer year = today.year();
String yearToQuery = year+'-'+year+1;
Integer len, i;
ID contact;
List<USD_Scholarship_Scoring__c> scholarshipExists = new List<USD_Scholarship_Scoring__c>([SELECT ID, SUID__c FROM USD_Scholarship_Scoring__c ]);
Set<Id> setIds = new Set<Id>();
for (USD_Scholarship_Scoring__c obj:scholarshipExists){
setIds.add(obj.SUID__c);
}
List<USD_Scholarship__c> scholarshipList = new List<USD_Scholarship__c>();
scholarshipList = ([SELECT ID
FROM USD_Scholarship__c
WHERE Submit_Term_Year__c = :yearToQuery
AND name = :selectedScholarship
AND SUID__c NOT IN :setIds] );
readers= ([SELECT ID, Contact__c
FROM USD_Roles__c
WHERE Scholarship_Name__c = :selectedScholarship
AND Start_Date__c <= TODAY
AND End_Date__c > TODAY] );
len = readers.size();
for(USD_Scholarship__c s : scholarshipList) {
if(i>len){
i=0;
}
// assign application to next 3 readers
if ( len>0 ) {
// scoringRecs = new USD_Scholarship_Scoring__c[]{new USD_Scholarship_Scoring__c(Reader_Contact__c=readers[i++].Contact__c, ScholarshipSUID__c=s.ID),
// new USD_Scholarship_Scoring__c(Reader_Contact__c=readers[i++].Contact__c, ScholarshipSUID__c=s.ID),
// new USD_Scholarship_Scoring__c(Reader_Contact__c=readers[i++].Contact__c, ScholarshipSUID__c=s.ID) };
}
}
if ( len>0 ) {
// insert scoringRecs;
}
*/
return 'success';
}
}
Thanks for everyone's help,
Jon
On my commandButton action I call custom controller method. I have all code in method commented (except return statement). And still get Formula Expression is required on the action attributes error whe I submit. See alot of post on this but none helping..
Here is VF page
<apex:page controller="pickListScholarshipController" >
<apex:form >
<apex:pageBlock title="Schoalrship Application Assignment " id="out">
<apex:pageBlockButtons >
<apex:commandButton value="Assign Readers" action="{!insertScoringRecords}" rerender="out" status="actStatusId"/>
<apex:commandButton value="Email Readers" action="{!submit}" rerender="out" status="actStatusId"/>
<apex:actionStatus id="actStatusId">
<apex:facet name="start">
<img src="/img/loading.gif" />
</apex:facet>
</apex:actionStatus>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Select Scholarship then Save button" collapsible="false">
<apex:selectList value="{!selectedScholarship}" multiselect="false" size="1">
<apex:selectOption itemValue="{!selectedScholarship}" itemLabel="{!selectedScholarship}" />
<apex:selectOption itemValue="Alumni Endowed Scholarship" itemLabel="Alumni Endowed Scholarship"/>
<apex:selectOption itemValue="Danny Burkett Memorial Scholarship" itemLabel="Danny Burkett Memorial Scholarship"/>
<apex:selectOption itemValue="Kyle O'Connell Memorial Scholarship" itemLabel="Kyle O'Connell Memorial Scholarship"/>
<apex:selectOption itemValue="Senior Class Legacy Scholarship" itemLabel="Senior Class Legacy Scholarship"/>
<apex:selectOption itemValue="Kyle O'Connell Memorial Scholarship" itemLabel="Kyle O'Connell Memorial Scholarship"/>
<apex:selectOption itemValue="Terry Whitcomb Scholarship" itemLabel="Terry Whitcomb Scholarship"/>
<apex:selectOption itemValue="Beckman Program Application" itemLabel="Beckman Program Application"/>
<apex:selectOption itemValue="SURE Scholarship" itemLabel="SURE Scholarship"/>
<apex:selectOption itemValue="PURE Scholarship" itemLabel="PURE Scholarship"/>
</apex:selectList>
<apex:outputText value="{!selectedScholarship}" label="You have selected:"/>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>
And controller:
public class pickListScholarshipController {
public String selectedScholarship;
public pickListScholarshipController (){
}
public PageReference save(){
return null;
}
public PageReference submit() {
return null;
}
public String getSelectedScholarship() {
return selectedScholarship;
}
public void setSelectedScholarship(String s) {
selectedScholarship = s;
}
public String insertScoringRecords() {
/*
USD_Scholarship_Scoring__c[] scoringRecs;
USD_Roles__c[] readers;
Date today = Date.today();
Integer year = today.year();
String yearToQuery = year+'-'+year+1;
Integer len, i;
ID contact;
List<USD_Scholarship_Scoring__c> scholarshipExists = new List<USD_Scholarship_Scoring__c>([SELECT ID, SUID__c FROM USD_Scholarship_Scoring__c ]);
Set<Id> setIds = new Set<Id>();
for (USD_Scholarship_Scoring__c obj:scholarshipExists){
setIds.add(obj.SUID__c);
}
List<USD_Scholarship__c> scholarshipList = new List<USD_Scholarship__c>();
scholarshipList = ([SELECT ID
FROM USD_Scholarship__c
WHERE Submit_Term_Year__c = :yearToQuery
AND name = :selectedScholarship
AND SUID__c NOT IN :setIds] );
readers= ([SELECT ID, Contact__c
FROM USD_Roles__c
WHERE Scholarship_Name__c = :selectedScholarship
AND Start_Date__c <= TODAY
AND End_Date__c > TODAY] );
len = readers.size();
for(USD_Scholarship__c s : scholarshipList) {
if(i>len){
i=0;
}
// assign application to next 3 readers
if ( len>0 ) {
// scoringRecs = new USD_Scholarship_Scoring__c[]{new USD_Scholarship_Scoring__c(Reader_Contact__c=readers[i++].Contact__c, ScholarshipSUID__c=s.ID),
// new USD_Scholarship_Scoring__c(Reader_Contact__c=readers[i++].Contact__c, ScholarshipSUID__c=s.ID),
// new USD_Scholarship_Scoring__c(Reader_Contact__c=readers[i++].Contact__c, ScholarshipSUID__c=s.ID) };
}
}
if ( len>0 ) {
// insert scoringRecs;
}
*/
return 'success';
}
}
Thanks for everyone's help,
Jon
- jonpilarski1.3914448382645588E12
- February 18, 2015
- Like
- 0
Calling generic methods for different object of same type.
Hi,
I wanted something like this in my code
I got this using single controller with few methods and and one visualforce page.
Now what I want is :
But I want to use single controller which will operate on different lists.
So planning to have somethink like this
1) 1 Visual force
2) controller A has got different objects like multiselect1, multiselect2 and multiselect3 (These 3 objects are of type multiselect)
3) one generic controller/class 'multiselect' which will store information related to data in left panel, right panel, selected and unselected and some functions to move data from one panel to another. I can call these methods from controller A by calling methods using specific objects (like we do in Java).
How I can make this work?
So basically, what I want is visualforce page calls methods on particular object which will get pass to controller A and controller A will again call method from multiselect class on the same object passed by visualforcepage.
Current visualforcepage code :
Please let me know if my question is confusing.
Best Regards,
Abhishek
I wanted something like this in my code
I got this using single controller with few methods and and one visualforce page.
Now what I want is :
But I want to use single controller which will operate on different lists.
So planning to have somethink like this
1) 1 Visual force
2) controller A has got different objects like multiselect1, multiselect2 and multiselect3 (These 3 objects are of type multiselect)
3) one generic controller/class 'multiselect' which will store information related to data in left panel, right panel, selected and unselected and some functions to move data from one panel to another. I can call these methods from controller A by calling methods using specific objects (like we do in Java).
How I can make this work?
So basically, what I want is visualforce page calls methods on particular object which will get pass to controller A and controller A will again call method from multiselect class on the same object passed by visualforcepage.
Current visualforcepage code :
<apex:panelGrid columns="3" id="abcd"> <apex:selectList id="sel1" value="{!leftselected}" multiselect="true" style="width:100px" size="5"> <apex:selectOptions value="{!unselectedvalues}" /> </apex:selectList> <apex:panelGroup > <br/> <apex:image value="{!$Resource.moveRight}"> <apex:actionSupport event="onclick" action="{!selectclick}" reRender="abcd"/> </apex:image> <br/><br/> <apex:image value="{!$Resource.moveLeft}"> <apex:actionSupport event="onclick" action="{!unselectclick}" reRender="abcd"/> </apex:image> </apex:panelGroup> <apex:selectList id="sel2" value="{!rightselected}" multiselect="true" style="width:100px" size="5"> <apex:selectOptions value="{!SelectedValues}" /> </apex:selectList> </apex:panelGrid>
Please let me know if my question is confusing.
Best Regards,
Abhishek
- Abhishek Kedari
- August 04, 2014
- Like
- 1
Calling generic methods for different object of same type.
Hi,
I wanted something like this in my code
I got this using single controller with few methods and and one visualforce page.
Now what I want is :
But I want to use single controller which will operate on different lists.
So planning to have somethink like this
1) 1 Visual force
2) controller A has got different objects like multiselect1, multiselect2 and multiselect3 (These 3 objects are of type multiselect)
3) one generic controller/class 'multiselect' which will store information related to data in left panel, right panel, selected and unselected and some functions to move data from one panel to another. I can call these methods from controller A by calling methods using specific objects (like we do in Java).
How I can make this work?
So basically, what I want is visualforce page calls methods on particular object which will get pass to controller A and controller A will again call method from multiselect class on the same object passed by visualforcepage.
Current visualforcepage code :
Please let me know if my question is confusing.
Best Regards,
Abhishek
I wanted something like this in my code
I got this using single controller with few methods and and one visualforce page.
Now what I want is :
But I want to use single controller which will operate on different lists.
So planning to have somethink like this
1) 1 Visual force
2) controller A has got different objects like multiselect1, multiselect2 and multiselect3 (These 3 objects are of type multiselect)
3) one generic controller/class 'multiselect' which will store information related to data in left panel, right panel, selected and unselected and some functions to move data from one panel to another. I can call these methods from controller A by calling methods using specific objects (like we do in Java).
How I can make this work?
So basically, what I want is visualforce page calls methods on particular object which will get pass to controller A and controller A will again call method from multiselect class on the same object passed by visualforcepage.
Current visualforcepage code :
<apex:panelGrid columns="3" id="abcd"> <apex:selectList id="sel1" value="{!leftselected}" multiselect="true" style="width:100px" size="5"> <apex:selectOptions value="{!unselectedvalues}" /> </apex:selectList> <apex:panelGroup > <br/> <apex:image value="{!$Resource.moveRight}"> <apex:actionSupport event="onclick" action="{!selectclick}" reRender="abcd"/> </apex:image> <br/><br/> <apex:image value="{!$Resource.moveLeft}"> <apex:actionSupport event="onclick" action="{!unselectclick}" reRender="abcd"/> </apex:image> </apex:panelGroup> <apex:selectList id="sel2" value="{!rightselected}" multiselect="true" style="width:100px" size="5"> <apex:selectOptions value="{!SelectedValues}" /> </apex:selectList> </apex:panelGrid>
Please let me know if my question is confusing.
Best Regards,
Abhishek
- Abhishek Kedari
- August 04, 2014
- Like
- 1