- Michael Dsoza
- NEWBIE
- 290 Points
- Member since 2011
- Consultant
- Cognizant Technology India Pvt Ltd
-
ChatterFeed
-
7Best Answers
-
0Likes Received
-
0Likes Given
-
77Questions
-
118Replies
Pass picklist selected value from visualforce page to apex class
I have some records listing on visualforce page . I want to filter these records based on selected value of custom picklist. I am not able to get selected value of this picklist in apex class.
My visualforce page is:
<apex:page standardController="Line_Item__c" extensions="LineItemPackagesExtensions" recordSetVar="lineitems" > <apex:pageBlock title="Search for Packages"> <apex:outputLabel >Packages Category</apex:outputLabel> <apex:inputField value="{!prdcat.Product_Category__c}" > <apex:actionSupport event="onchange" rerender="packagesList" action="{!filterPackages}"/> </apex:inputField> <apex:outputPanel id="packagesList"> <apex:pageBlockTable value="{!Packages}" var="a"> <apex:column value="{!a.Name}"/> <apex:column value="{!a.Product_Category__c}"/> <apex:column value="{!a.Cost__c}"/> <apex:column value="{!a.Stay__c}"/> <apex:column value="{!a.Activity__c}"/> <apex:column value="{!a.Description__c}"/> </apex:pageBlockTable> </apex:outputPanel> </apex:pageBlock> </apex:page>
Apex class is:
public class LineItemPackagesExtensions { public Package__c pkgs; public List<Package__c> Packages { get; set; } public Package__c prdcat{get;set;} public LineItemPackagesExtensions(ApexPages.StandardSetController controller) { Packages = [SELECT Name,Product_Category__c,Cost__c,Stay__c,Activity__c,Description__c FROM Package__c ]; } public List<Package__c> getPackages(){ Packages = [SELECT Name,Product_Category__c,Cost__c,Stay__c,Activity__c,Description__c FROM Package__c ]; return Packages; } public void filterPackages() { Packages = [SELECT Name,Product_Category__c,Cost__c,Stay__c,Activity__c,Description__c FROM Package__c where Product_Category__c=:prdcat.Product_Category__c ]; } }
When I change the value of picklist it throws the following error
Attempt to de-reference a null object
Error is in expression '{!filterPackages}' in page addopportunitylineitem1: Class.LineItemPackagesExtensions.filterPackages: line 35, column 1
Please help to achieve this.
Thanks
Rohitash
- rohitash yadav
- May 29, 2016
- Like
- 0
- Continue reading or reply
SOQL Subquery not working
I created the below query to:
1. Get 5 accounts (doesn't matter which ones)
2. For each of these Accounts bring back Opportunity id, name, and Account ID
SELECT id, Name, Account.id from Opportunity WHERE Account.id IN (SELECT Account.id FROM Account LIMIT 5)
When I execute the query I get back "Unknown Error parsing the query".
I found that hardcoding in some valid account ID's instead of using the sub select works.
Any ideas why this wouldn't work?
Thanks,
Mike
- Mike Lee PCL
- March 03, 2016
- Like
- 0
- Continue reading or reply
Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id:
Error is in expression '{!genDoc2}' in component <apex:commandButton> in page doccontrolgather: Class.DocControlQuery.SavePDF: line 203, column 1
Class.DocControlQuery.genDoc2: line 120, column 1
I need help with this apex code. I am not a coder :-S
- Jeanette Albert 15
- March 03, 2016
- Like
- 1
- Continue reading or reply
I'm getting a error while executing the code ,can anyone help me below issue?
public with sharing class inlinecontroller {
Public contact conRec{get;set;}
Public id accRecId;
Public account accRec{get;set;}
public inlinecontroller(ApexPages.StandardController controller) {
accRecId = [select id,accountid from contact where id=:ApexPages.currentPage().getParameters().get('id')].accountid;
if(accRecId != null)
{
accRec = [select id,name,accountnumber,annualrevenue from account where id =:accRecId];
}
}
}
Visualforce:
<apex:page standardController="contact" extensions="inlinecontroller">
<apex:form >
<apex:pageBlock title="My Inline Visualforce page">
Account Name <apex:outputField value="{!accRec.name}"/><br/>
Account Number <apex:outputField value="{!accRec.accountnumber}"/><br/>
Annual Revenue <apex:outputField value="{!accRec.annualrevenue}"/><br/>
</apex:pageBlock>
</apex:form>
</apex:page>
Error:
Visualforce Error
Help for this Page
System.QueryException: List has no rows for assignment to SObject
Class.inlinecontroller.<init>: line 6, column 1
- SREENIVASULU.C
- August 26, 2014
- Like
- 0
- Continue reading or reply
Error in creating trigger
Iam getting an error in the line highlighted below.Is this the correct way to write it
trigger updateGroupLookup on Case (before insert) {
for (Case c : Trigger.new) {
if(c.groupid__c!= null){
c.group_Account__c = [select id from account where Group_ID__c =c.groupid__c];
}
}
- Sabah Farhana
- June 03, 2014
- Like
- 0
- Continue reading or reply
Update is not happening in Trigger
Hi,
I wrote a trigger below to update opportuntiy from custom object based on condition but is not updating please help
Code below highlighted in bold is not updating
trigger Temp_Asset2_Opp on Temp_Assets__c (after insert )
{
List<OpportunityLineItem> OppLineItems = new List<OpportunityLineItem>();
List<Temp_Assets__c> CurrentAssetOpp = [Select Id, Name, Asset_Id__c, Serial_Number__c, AccountId__c, Product__c, Service_Start_Date__c,
Service_End_Date__c ,Install_Date__c ,Reseller__c,Distributor__c ,
Incumbent_Reseller__c,Education__c,Expiry_Date__c,Existing_Opportunity__c,
New_Opportunity__c,Expiry_Term__c,Bundle_Support__c, X5_Year_SKU_Code__c, X3_Year_SKU_Code__c,
X1_Year_SKU_Code__c, Monthly_SKU_Code__c, X5_year_SKU__c ,X3_year_SKU__c, X1_year_SKU__c,
Total_in_Months__c, Support_Only_5_Year_SKU__c, Support_Only_3_Year_SKU__c, Support_Only_1_Year_SKU__c,
Support_Only_Monthly_SKU__c, DaysRemaining_Months__c
From Temp_Assets__c
Where CreatedById = :userinfo.getUserId() Limit 1];
List<Temp_Assets__c> CurrentAssetOppLine = [Select Id, Name, Asset_Id__c, Serial_Number__c, AccountId__c, Product__c, Service_Start_Date__c,
Service_End_Date__c ,Install_Date__c ,Reseller__c,Distributor__c ,
Incumbent_Reseller__c,Education__c,Expiry_Date__c,Existing_Opportunity__c,
New_Opportunity__c,Expiry_Term__c,Bundle_Support__c, X5_Year_SKU_Code__c, X3_Year_SKU_Code__c,
X1_Year_SKU_Code__c, Monthly_SKU_Code__c, X5_year_SKU__c ,X3_year_SKU__c, X1_year_SKU__c,
Total_in_Months__c, Support_Only_5_Year_SKU__c, Support_Only_3_Year_SKU__c, Support_Only_1_Year_SKU__c,
Support_Only_Monthly_SKU__c, DaysRemaining_Months__c
From Temp_Assets__c
Where CreatedById = :userinfo.getUserId()];
Pricebook2 prBook= [select id from Pricebook2 where Name=: 'NAM Price Book'];
RecordType renewal_RT = [Select id, Name, sObjectType from RecordType where sObjectType= 'Opportunity' and Name = 'Renewal Opportunity' ];
Opportunity Opp = new Opportunity();
for ( Temp_Assets__c TA : CurrentAssetOpp )
{
// If New Opportunity is Created
if ( TA.Existing_Opportunity__c == NULL && TA.New_Opportunity__c != NULL )
{
// Insert Opportunity with all mandatory fields
Opp.Name = TA.New_Opportunity__c;
Opp.Type = 'Existing Customer';
Opp.AccountId = TA.AccountId__c;
Opp.CloseDate = system.today().addDays(+30); // default Sysdate + 30
Opp.Government_Contract__c = 'None';
Opp.Renewal_Opportunity__c = 'Yes';
Opp.StageName = 'Renewal';
//Opp.Lost_Reason__c = 'Other'; // not required
Opp.Primary_Competitor__c = 'No Competitor';
Opp.ForecastCategoryName = 'Pipeline';
Opp.LeadSource = 'Renewal';
Opp.Primary_Reseller__c = TA.Reseller__c;
Opp.Primary_Distributor__c = TA.Distributor__c;
Opp.Renewal_Incumbant_Reseller__c = TA.Incumbent_Reseller__c;
Opp.Renewal_K_12__c = TA.Education__c;
//Assigning the new Opportunity to the Renewal Record Type
opp.recordtypeId = renewal_RT.id;
Insert Opp;
}
if ( TA.Existing_Opportunity__c == NULL && TA.New_Opportunity__c != NULL )
{
List<Opportunity> OpptUp = [select Id from Opportunity where id = :TA.Existing_Opportunity__c ];
for ( Opportunity OppUpd : OpptUp ) {
OppUpd.test__c = 'Sudhir';
OppUpd.Primary_Reseller__c = TA.Reseller__c;
OppUpd.Primary_Distributor__c = TA.Distributor__c;
OppUpd.Renewal_Incumbant_Reseller__c = TA.Incumbent_Reseller__c;
OppUpd.Renewal_K_12__c = TA.Education__c;
//change the RecordType of this existing Opportunity to Renewal Opportunity Record Type
OppUpd.recordtypeId = renewal_RT.id;
}
Update OpptUp;
}
}
List<Temp_Assets__c> TempAsset = [SELECT Id From Temp_Assets__c Where CreatedById = :userinfo.getUserId()];
//delete TempAsset ;
}
Thanks
Sudhir
- Sudhir_Meru
- May 27, 2014
- Like
- 0
- Continue reading or reply
Not able to select User Id in Process Builder
I am trying to create an action of type "Post to Chatter" but whenever I go to select "User Id" from lookup then I don't see any Id value there.
I see recusion there as it always show me reference value & I am not able to select any user Id (OwnerId, CreatedById etc.).
It seems like BUG & do let me know if everyone is facing the same issue OR any workaround to resolve this.
- Michael Dsoza
- July 15, 2017
- Like
- 0
- Continue reading or reply
ENTITY_IS_LOCKED, the entity is locked for editing: [] -- Insert Failed
We have implemented one solution using Master Detail Relationship. While submitting Master Record for an approval, we create it's detail records. It's functionality is working fine as per requirement but while writing its test classes, we are getting "ENTITY_IS_LOCKED, the entity is locked for editing: [] -- Insert Failed".
We are running test method using business user who actually creates master record & its detail records gets automatically created as per business logic.
As I understand, Master record gets automatically locked when submitted for an approval & hence detail object also gets locked (Controlled by Parent sharing setting). That's why while creating record for detail object, we are getting "ENTITY_IS_LOCKED, the entity is locked for editing: [] -- Insert Failed".
Also, Why am I not getting this error while testing actual implementation ??
Kindly let me know how can we fix this test class issues.
Thanks.
Michael Dsoza
- Michael Dsoza
- January 03, 2017
- Like
- 0
- Continue reading or reply
Access global class static variable directly on visualforce page like $User.CompanyName
As having past java experience, we usually create separate file for CONSTANTS & their VALUES. Since we have "CUSTOM LABELS" in Salesforce to get String KEY & VALUE but we don't want these CONSTANTS to be change in future from SETUP. Also, Hard-Coding values are always bad practice and we have kept all this CONSTANTS in separate global class named "Global_Constants" where each constants is marked with static, final & assigned with value.
Also, I had created getter method to access this static constant variable but whenever we try to access this, we receive error message as "variable_name does not exist".
Can you please let us know, How can we create global page class like $User, $Label in Apex ?? OR
How can we access these CONSTANTS on VFPage without using these class as "Controller / Extensions" (Since I want to make it separate, global & to be accessible in every page)
Thanks.
- Michael Dsoza
- October 25, 2016
- Like
- 0
- Continue reading or reply
pass apex list recipient to standard email alert
How can I pass list of recepient from apex code into standard email alert ?
Actually we want to avoid limit exception for apex email alert & we decided to send report using standard email alert but I could not able to find way to set recepient in standard email alert.
Also, let me know if any other idea to send an email using standard email alert to email Ids generated by apex code.
Thanks.
- Michael Dsoza
- May 29, 2016
- Like
- 0
- Continue reading or reply
Give Document folder access to external application
How can SAP get these files from Salesforce without using any third party middleware.
Thanks.
- Michael Dsoza
- March 08, 2016
- Like
- 0
- Continue reading or reply
Save Exported File into network path location
On clicking button, I am exporting an excel file (using VFPage) & it saves to default user's downloads folder. I want to save this exported excel file to custom location (network path / shared location). Kindly let me know how can I achieve this in salesforce.
Thanks.
- Michael Dsoza
- March 07, 2016
- Like
- 0
- Continue reading or reply
Trigger code coverage showing 0% while deployment
I have one trigger (before update) & its test class. When I run its test class from Apex Test Execution (In Production) then I get trigger code coverage as 70%. But when I try to deploy the same trigger with its test class (same as Production) from UAT to Production then all test method passes but I get code coverage as 0%.
Is their anything in settings which restrict us to count code coverage while deploying ??
- Michael Dsoza
- March 03, 2016
- Like
- 0
- Continue reading or reply
custom date parameter in standard report
I have to pass paramter as from date and to date in standard report.
Also, I want to schedule the report on specific day.
I can set the parameter using custom link with pv0 to pvN as parameter. But how can I pass the same parameter while scheduling ??
- Michael Dsoza
- November 17, 2015
- Like
- 0
- Continue reading or reply
Test class for ProcessInstanceWorkItem
How to write Test class for ProcessInstanceWorkItem ?
Currently we are firing query to ProcessInstanceWorkItem table to get the workitem Id and updating those records to Approve or Reject as per requirements.
Since we are not able to insert ProcessInstanceWorkItem records Also, In test class, I submiited record for an approval but in next line when I query to ProcessInstanceWorkItem for the same targetObjectId then also I am receiving 0 records.
Please help me in this to resolve this asap.
Thanks
- Michael Dsoza
- September 30, 2015
- Like
- 0
- Continue reading or reply
Test Data for User Territory Hierarchy
How can we create test data for User Territory Hierarchy. Since UserTerritory object does not allow DML operation and we can't assign Territory to the User. Do we need to create data (User, Territory & UserTerriotry) manually before running test class ??
Thanks.
- Michael Dsoza
- September 15, 2015
- Like
- 0
- Continue reading or reply
Update few fields with value but rest of the fields with NULL value
I have one custom object records where every field is updated with value and I want to update this record with few fields but rest of fields should be updated with NULL value.
Since custom object is having more than 100 fields so that I can not set null value into the fields manually. So please guide me how can I achieve this...
Thanks
- Michael Dsoza
- August 14, 2015
- Like
- 0
- Continue reading or reply
EmployeeNumber field of User object is not accessible
Not accessible EmployeeNumber field of User object from Attachment Query whereas Name, Alias are accessible.
Plesae explain why am I not able to access EmployeeNumber.
API Version - 33.0
My Query is - SELECT Id,Name, CreatedBy.EmloyeeNumber FROM Attachment
Error - INVALID_FIELD:
SELECT Id,Name, CreatedBy.EmloyeeNumber FROM Attachment
^
ERROR at Row:1:Column:17
No such column 'EmloyeeNumber' on entity 'Name'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.
Thanks.
- Michael Dsoza
- June 06, 2015
- Like
- 0
- Continue reading or reply
View State Error (Crossing 135 KB size)
In my VF page, I am displaying list of images (Attachments) using pageBlockTable. While displaying images, At some images, it takes very small size to display image but in some images it takes very huge size of KB's as a result view state error appears as it is crossing view state limit of 135KB.
common.udd.object.EncryptableF... size takes 0.27 kb
core.filemanager.ByteBlobValue... size takes 27.45 kb
Thanks
- Michael Dsoza
- May 27, 2015
- Like
- 0
- Continue reading or reply
On button click, generate an excel sheet visualforce page
Requirement - On click on "Generate Excel" button, export pageBlockTable data into excel.
Solution Used - Created 2 VF Page, On button click of 1st VF page, redirecting it to 2nd VF page (page contentType="application/vnd.ms-excel#ExportToExcel.xls" cache="true") which is downloding as excel sheet.
Problem - Excel sheet downloads correctly as expected but 1st VF page gets disabled and I have to hit the URL again to work it properly.
Please help me to resolve it.
- Michael Dsoza
- April 16, 2015
- Like
- 0
- Continue reading or reply
Folder not created in ant deployment
I was doing deployment from sandbox environment to production environment and Deployment was succesful but the folders of which reports, dashboards, workflows & email alerts were not created in production.
What settings I need do to create folder too ??
Many Thanks
- Michael Dsoza
- November 21, 2014
- Like
- 0
- Continue reading or reply
How to enable D&BCompany object in salesforce ?
How to enable D&BCompany in my previous salesforce account ??
Because it has created relationship with Account, Lead & Contact as a result, it is giving me deployment error as 'D&BCompnay sObject is not found. If it is custom object then append __c at the end'.
So please let me know how can I enable it in my previous salesforce account ??
Thanks & Regards,
Michael
- Michael Dsoza
- September 07, 2014
- Like
- 0
- Continue reading or reply
Enable Quote sObject from Apex Code
I am using Quote sObject in Rest API call but in new instance, I have to enable Quote sObject manually by clicking checkbox in Setup -> Quote -> Settings -> Enable Quote.
How can I enable it from Apex Code ??
I tried to find Quote sObject (before enable) in Schema.getGlobalDescribe().values() but there is NO such Quote sObject Type.
Please let me know how can I enable it from Apex Code.
Thanks
Michael
- Michael Dsoza
- August 26, 2014
- Like
- 0
- Continue reading or reply
Visualforce email template images are showing in preview but not at receiver email.
I have created one visualforce email template to send email alert.
In Preview, banner images are showing but whenever i receive email, instead of image it shows blank box.
Code used
<img src="https://c.ap1.content.force.com/servlet/servlet.FileDownload?file=01590000004wqi7" width="100%" height="100"/> OR
<apex:image url="https://c.ap1.content.force.com/servlet/servlet.FileDownload?file=01590000004wqjZ" width="100%" />
Also, How can we use Letterhead in visualforce email templates ??
Thanks :)
- Michael Dsoza
- August 19, 2014
- Like
- 0
- Continue reading or reply
Login retricted as invalid location or password
I am not able to login into my salesforce developer instance and getting error message as "Your login attempt has failed. The username or password may be incorrect, or your location or login time may be restricted. Please contact the administrator at your company for help."
I am administrator of my free developer account and I sat Login IP Ranges with my machine current IP address. after that I logged out and tried to login again but I am unable to login and getting above error message.
Kindly help me to resolve this because my developer instance contains my developement data too. :(
Thanks :)
- Michael Dsoza
- June 30, 2014
- Like
- 0
- Continue reading or reply
OAuth implementation in Salesforce
I want to implment OAuth security in salesforce and for that I have created connected app and I am able to access data from third party application by using Bearer token (generated by using client id and client secret). but i have following doubts as,
1) When we create connected app then is it available/mandotary for all services to authorize oAuth connected app ??
2) Can we restrict oAuth for some/limited services like lead, case services only ?
please help me to solve it.
Thanks :)
- Michael Dsoza
- June 20, 2014
- Like
- 0
- Continue reading or reply
Not able to select User Id in Process Builder
I am trying to create an action of type "Post to Chatter" but whenever I go to select "User Id" from lookup then I don't see any Id value there.
I see recusion there as it always show me reference value & I am not able to select any user Id (OwnerId, CreatedById etc.).
It seems like BUG & do let me know if everyone is facing the same issue OR any workaround to resolve this.
- Michael Dsoza
- July 15, 2017
- Like
- 0
- Continue reading or reply
ENTITY_IS_LOCKED, the entity is locked for editing: [] -- Insert Failed
We have implemented one solution using Master Detail Relationship. While submitting Master Record for an approval, we create it's detail records. It's functionality is working fine as per requirement but while writing its test classes, we are getting "ENTITY_IS_LOCKED, the entity is locked for editing: [] -- Insert Failed".
We are running test method using business user who actually creates master record & its detail records gets automatically created as per business logic.
As I understand, Master record gets automatically locked when submitted for an approval & hence detail object also gets locked (Controlled by Parent sharing setting). That's why while creating record for detail object, we are getting "ENTITY_IS_LOCKED, the entity is locked for editing: [] -- Insert Failed".
Also, Why am I not getting this error while testing actual implementation ??
Kindly let me know how can we fix this test class issues.
Thanks.
Michael Dsoza
- Michael Dsoza
- January 03, 2017
- Like
- 0
- Continue reading or reply
Access global class static variable directly on visualforce page like $User.CompanyName
As having past java experience, we usually create separate file for CONSTANTS & their VALUES. Since we have "CUSTOM LABELS" in Salesforce to get String KEY & VALUE but we don't want these CONSTANTS to be change in future from SETUP. Also, Hard-Coding values are always bad practice and we have kept all this CONSTANTS in separate global class named "Global_Constants" where each constants is marked with static, final & assigned with value.
Also, I had created getter method to access this static constant variable but whenever we try to access this, we receive error message as "variable_name does not exist".
Can you please let us know, How can we create global page class like $User, $Label in Apex ?? OR
How can we access these CONSTANTS on VFPage without using these class as "Controller / Extensions" (Since I want to make it separate, global & to be accessible in every page)
Thanks.
- Michael Dsoza
- October 25, 2016
- Like
- 0
- Continue reading or reply
Add List Values to a MAP
I am passing a LIST<ID> to the function. The trouble appears on the highlighted lines below
LIST<TASK> objTasks = [SELECT WHOID, count(ID) FROM TASK WHERE WHOID IN :ContactIDs]; LIST<EVENT> objEvents = [SELECT WHOID, count(ID) FROM EVENT WHERE WHOID IN :ContactIDs];
The Error I get is:
Field must be grouped or aggregated: WhoId
But if I try and group it, it gives me errors as well
LIST<TASK> objTasks = [SELECT WHOID, count(ID) FROM TASK WHERE WHOID IN :ContactIDs GROUP BY WHOID]; LIST<EVENT> objEvents = [SELECT WHOID, count(ID) FROM EVENT WHERE WHOID IN :ContactIDs GROUP BY WHOID];This gives the error
Illegal assignment from List<AggregateResult> to List<Task>
The Function
PUBLIC VOID updateActivityCount( LIST<ID> listContacts ) { LIST<ID> ContactIDs = NEW LIST<ID>(); ContactIDs = listContacts; INTEGER tmpTasks = 0; INTEGER tmpEvents = 0; LIST<CONTACT> contactUpdate = NEW LIST<CONTACT>(); MAP<ID, INTEGER> contactTasks = NEW MAP<ID, INTEGER>(); MAP<ID, INTEGER> contactEvents = NEW MAP<ID, INTEGER>(); LIST<TASK> objTasks = [SELECT WHOID, count(ID) FROM TASK WHERE WHOID IN :ContactIDs]; LIST<EVENT> objEvents = [SELECT WHOID, count(ID) FROM EVENT WHERE WHOID IN :ContactIDs]; FOR(TASK thisTask : objTasks) { contactTasks.put(thisTask[0], thisTask[1]); } FOR(EVENT thisEvent : objEvents) { contactEvents.put(thisEvent[0], thisEvent[1]); } LIST<CONTACT> objContacts = [SELECT ID FROM Contact WHERE ID IN :ContactIDs]; FOR(CONTACT thisContact : objContacts) { IF( contactTasks.containsKey( thisContact.Id ) ) { tmpTasks = contactTasks.get( thisContact.Id ); } ELSE { tmpTasks = 0; } IF( contactEvents.containsKey( thisContact.Id ) ) { tmpTasks = contactEvents.get( thisContact.Id ); } ELSE { tmpEvents = 0; } thisContact.activity_this_cfy__c = tmpTasks + tmpEvents; contactUpdate.add( thisContact ); } //-- Execute the update for contactUpdate //------------------------------------------------------------------------------------------------------------------------------ if ( !contactUpdate.isEmpty() ) { TRY{ update contactUpdate; } CATCH ( Exception ex ) { SYSTEM.DEBUG(thisPage + 'Could not update Contact. Cause: ' + ex.getCause() ); } } } //-- END updateActivityCount
- Andrew Telford
- September 23, 2016
- Like
- 0
- Continue reading or reply
date.daysBetween method works only "after update" in Trigger?
I am new to APEX. I am just writing a trigger that uses the date (DaysBetween) method. The trigger shall run after insert of a new record or update of an existing record. In my understanding I should use here "after insert, before update". However, the part when the record is updated (before update) does not work correctly when the date field is updated. The date.daysbetween method does not count according to the new date value but still calculates with the old date value. When I change the to "after update" the trigger works fine. But is this correctlike this? I believe for record updates I shold use "before update" as I have already the record Id.
Here is my code:
trigger updatePressesTrigger on Press__c (after insert, before update) { List <Press__c> presses = [Select Id, Production_Start_Date__c,Survey_6_Mth_After_Handover__c From Press__c Where Survey_6_Mth_After_Handover__c = False AND Production_Start_Date__c !=Null AND RecordTypeId ='01220000000YE4U' AND (Production_start_status__c = 'F' OR Production_start_status__c = 'I')]; If(presses.size() >0){ List <Press__c> pressesToUpdate = new List<Press__c>(); //Determine Presses where Production Start Date > 6 month For(Press__c press : presses){ date prodStartDate = press.production_start_date__c; date todayDate = date.today(); integer daysDifference = prodStartDate.daysBetween(todayDate); if(daysDifference > 180){ press.Survey_6_Mth_After_Handover__c = True; pressesToUpdate.add(press); } update pressesToUpdate; } } }
And here is the Test Class:
@isTest public class testUpdatePressesTrigger { static testMethod void testUpdatePressTrigger(){ //Create Account Account a = new Account(); a.name = 'Prospecta'; a.recordtypeid = '01220000000YE4P'; a.Market_segments__c = 'Industrial Printer'; insert a; //Create Press Press__c p = new Press__c(); p.Name = 'RA105'; p.RecordTypeId = '01220000000YE4U'; p.Year__c = '2015'; p.Survey_6_Mth_After_Handover__c = False; p.Production_start_date__c = Date.newInstance(2016,5,1); p.Account__c = a.Id; p.Production_start_status__c = 'F'; insert p; //Update press p.Production_start_date__c = p.Production_start_date__c - 200; update p; } }
Thanks for your advice!
- Michael Haase 9
- May 29, 2016
- Like
- 0
- Continue reading or reply
Pass picklist selected value from visualforce page to apex class
I have some records listing on visualforce page . I want to filter these records based on selected value of custom picklist. I am not able to get selected value of this picklist in apex class.
My visualforce page is:
<apex:page standardController="Line_Item__c" extensions="LineItemPackagesExtensions" recordSetVar="lineitems" > <apex:pageBlock title="Search for Packages"> <apex:outputLabel >Packages Category</apex:outputLabel> <apex:inputField value="{!prdcat.Product_Category__c}" > <apex:actionSupport event="onchange" rerender="packagesList" action="{!filterPackages}"/> </apex:inputField> <apex:outputPanel id="packagesList"> <apex:pageBlockTable value="{!Packages}" var="a"> <apex:column value="{!a.Name}"/> <apex:column value="{!a.Product_Category__c}"/> <apex:column value="{!a.Cost__c}"/> <apex:column value="{!a.Stay__c}"/> <apex:column value="{!a.Activity__c}"/> <apex:column value="{!a.Description__c}"/> </apex:pageBlockTable> </apex:outputPanel> </apex:pageBlock> </apex:page>
Apex class is:
public class LineItemPackagesExtensions { public Package__c pkgs; public List<Package__c> Packages { get; set; } public Package__c prdcat{get;set;} public LineItemPackagesExtensions(ApexPages.StandardSetController controller) { Packages = [SELECT Name,Product_Category__c,Cost__c,Stay__c,Activity__c,Description__c FROM Package__c ]; } public List<Package__c> getPackages(){ Packages = [SELECT Name,Product_Category__c,Cost__c,Stay__c,Activity__c,Description__c FROM Package__c ]; return Packages; } public void filterPackages() { Packages = [SELECT Name,Product_Category__c,Cost__c,Stay__c,Activity__c,Description__c FROM Package__c where Product_Category__c=:prdcat.Product_Category__c ]; } }
When I change the value of picklist it throws the following error
Attempt to de-reference a null object
Error is in expression '{!filterPackages}' in page addopportunitylineitem1: Class.LineItemPackagesExtensions.filterPackages: line 35, column 1
Please help to achieve this.
Thanks
Rohitash
- rohitash yadav
- May 29, 2016
- Like
- 0
- Continue reading or reply
Return results of two soql queries into a single blocktable row
I'm trying to retrieve the latest attachment from Job_Applicants__c and the latest attachment from from Applied_Applicants__c and combine into a single blocktable row. The requirement i'm trying to achieve is that a job applicant can attach a resume to their account record but they need to attach a customized cover letter for each job they apply to. So far i'm just tampering around with soql code so any suggestions are very much appreciated.
Records = [Select Name,First_Name__c,Last_Name__c, (Select Id, LastModifiedDate From Attachments Order By LastModifiedDate DESC)
From Job_Applicants__c t where Id in (select Applicant__c from Applied_Applicants__c where JobPosting__c=:A and Status__c not in ('Offered','Taken'))];
Applicants =[Select Id, (Select Id, LastModifiedDate From Attachments Order By LastModifiedDate DESC)
from Applied_Applicants__c where JobPosting__c=:A and Status__c not in ('Offered','Taken')];
- Salvatore Gomez
- May 27, 2016
- Like
- 0
- Continue reading or reply
what is the use of {} Curly braces and [] Square brackets in soql query ?
can you pls explaine me with query exampls.
thanks in advance.
- Royal
- March 08, 2016
- Like
- 0
- Continue reading or reply
Login to sandbox verification email
I am trying to login to the sandbox, and I am prompted to enter the verification code but the email seems to have sent to a different email (*******@****le.com) than the email (*******@****nk.com) I have in Salesforce personal information. The verification email was sent to the correct email when I login to the Salesforce.com account the first time. I have verified my email in the personal information page. Any idea what is going wrong? I can't access the sandbox without the verification code. Thanks!
- Eric Delgado
- March 03, 2016
- Like
- 0
- Continue reading or reply
Redundant List
In the follwing code, how can I avoid using the con List.
Is there a way in which you can use SOQL query on trigger.new directly instead of bringing in another List ??
trigger ContactTest on Contact (before insert, before update) {
List<Contact> con = [Select Id, Account.Phone from Contact where Id in : trigger.new];
for(Contact c: trigger.new)
{
for(Integer i=0; i< trigger.new.size() ; i++)
{
c.OtherPhone = con[i].Account.Phone;
}
}
}
Also, can the above update be done with WOrkflow Rules ??
Thanks,
Murthy
- BP Murthy
- March 03, 2016
- Like
- 0
- Continue reading or reply
Trigger code coverage showing 0% while deployment
I have one trigger (before update) & its test class. When I run its test class from Apex Test Execution (In Production) then I get trigger code coverage as 70%. But when I try to deploy the same trigger with its test class (same as Production) from UAT to Production then all test method passes but I get code coverage as 0%.
Is their anything in settings which restrict us to count code coverage while deploying ??
- Michael Dsoza
- March 03, 2016
- Like
- 0
- Continue reading or reply
Multiple Approvers in Approval Process
What would be the best way to handle this ? I'm thinking of different scenarios which would require different levels of approval and what not, but I think I may be overlooking an easier solution.
Any help would be appreciated.
- Zoom_V
- March 03, 2016
- Like
- 0
- Continue reading or reply
Utilizing relationship feature for leads
- Robert Reed 30
- March 03, 2016
- Like
- 0
- Continue reading or reply
Workflow rule criteria that evaluate if a date field is empty
Using the rule criteria builder, the rule is supposed to run if the formula evaluates to true, but I tried many formulas with no luck. Examples of what I tried are:
c4g_Contact__r.c4g_Primary_Enrollment__r.c4g_Actual_Discharge_Date__c = NULL
ISBLANK( c4g_Contact__r.Primary_Enrollment_Discharged_Date__c )
ISBLANK( c4g_Contact__r.Primary_Enrollment_Discharged_Date__c ) = TRUE
Any idea what I could be missing here? Thanks for any help.
- Renier F Navas
- March 03, 2016
- Like
- 0
- Continue reading or reply
Error at merging Database.MergeResult[]
I am developing a merging app but I cannot find to way to merge what I need. A have a multiple selection for all the accounts I want to merge and the Master Account.
Here is the code:
public class MyAccountListCntrlr { // PROPERTIES public List<AccountWrapperCls> acctList {get;set;} public Set<String> selAccountNames {get;set;} public Boolean hasSelAcct {get;set;} public static List<Account> accts; // MESSAGE public static Boolean showMessage {get;set;} public static String message {get;set;} public static List<Account> acct;//Account 1 public static List<Account> acct2;//Account 2 public static String sAccount{set;get;}//Selection of the Master Account //See the method getItems // CONSTRUCTOR public MyAccountListCntrlr(){ acctList = new List<AccountWrapperCls>(); selAccountNames = new Set<String>(); showMessage = false; for(Account a : [SELECT AccountNumber, CreatedDate, name, id, phone, fax, website, type, industry, description, NumberOfEmployees, BillingCity, AnnualRevenue from account ORDER BY Account.Name]){ acctList.add(new AccountWrapperCls(a)); } } // SELECTING MASTER public List<SelectOption> getItems() { List<Account> lstAcc = [select id, name from account ORDER BY Account.Name]; List<SelectOption> options = new List<SelectOption>(); for(Account acc : lstAcc) { options.add( new SelectOption( acc.id, acc.Name)); options.sort(); } return options; } public Account masterAcc = new account(name = sAccount); // METHODS public void displaySelectedAccountNumbers(){ //selAccountNames.clear(); //masterAcc = [Select name from Account where name = :sAccount]; hasSelAcct = false; for(AccountWrapperCls cWrapper : acctList){ if(cWrapper.isSelected){ hasSelAcct = true; selAccountNames.add(cWrapper.cAccount.name); //showMessage = true; //message = 'The following error has ocurred: \n' + cWrapper.cAccount.id; //accts.add(cWrapper.cAccount); } if(selAccountNames.size() > 1) { for(Integer i = 1; i < selAccountNames.size(); i++) { showMessage = true; message = 'The selected accounts are: \n' + selAccountNames; acct = [Select id, name, phone FROM Account where id = :selAccountNames]; //acct2 = [Select id, name, phone FROM Account where id = :selAccountNames ORDER BY Account.CreatedDate]; message = 'The selected query is: \n' + acct; if(selAccountNames.size() > 1) { try { //acct.get(i).description = '\nAccount Name: ' + acct.get(0).Name; Database.MergeResult[] results = Database.merge(masterAcc, acct, false); //merge acct.get(0) acct2.get(i); //merge acct2.get(i) master.get(1); //If the first Account was created first than 2nd one then do not merge /*if(acct.get(0).CreatedDate < acct.get(i).CreatedDate) { acct.get(0).description = '\nAccount Name: ' + acct.get(i).Name; merge acct.get(i) acct2.get(0); } else { acct.get(i).description = '\nAccount Name: ' + acct.get(0).Name; merge acct.get(0) acct2.get(i); }*/ } catch(Exception e) { showMessage = true; message = 'The following error has founded: ' + e; } } } showMessage = true; message = 'Congratulations, you have merge successfully your accounts, please refresh the site to see changes. '; } } } public PageReference PreviousPag() { return Page.LCA; } }
Can somebody help me out with this issue?
Thanks in advace.
- Rodolfo Calvo 3
- March 03, 2016
- Like
- 0
- Continue reading or reply
Edit/Save issue with the salesforce 1 Mobile
My user running his mobile Salesforce1 then showing this Error.
"There's a problem saving this record. You might not have permission to edit, or might have been deleted or archived."
I also checked his profile, he is Salesforce 1 User. How can help this user to edit/ Save via Salesforce1 on the case ?
- Praveen Bonalu
- March 03, 2016
- Like
- 0
- Continue reading or reply
Reg:Page Reference
I have two visualforce page and one controller in my scenario,
First page I give two input industry and product,its given the result certain group of company picture in href link.If I click one image it gives some relevent detail about the company its like https://www.salesforce.com/customers/.
VFP-1
<apex:page sidebar="false" showheader="false" controller="sfdctest" tabStyle="account">
<apex:form >
<apex:pageMessages id="pId"/>
<apex:image url="{!imageURL}">
</apex:image>
<apex:pageBlock title="Select a Industry & Product" >
<apex:selectList value="{!searchStr}" size="1">
<apex:selectOptions value="{!Industrynames}" />
</apex:selectList>
<apex:selectList size="1" value="{!productName}">
<apex:selectOptions value="{!items}"/>
</apex:selectList>
<apex:outputPanel id="myRerender">
<apex:commandButton value="Submit" action="{!soslDemo_method}" ReRender="pgId,pId" />
</apex:outputPanel>
</apex:pageBlock>
<apex:pageBlock title="Customer details" id="pgId">
<apex:repeat value="{!acc}" var="account">
<style>
body {margin:50px;}
div.img {
-webkit-align-items: baseline;
align-items:baseline;
margin: 10px;
border: 1px solid #ccc;
float: left;
width: 220px;
margin-bottom:25px;
box:0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
}
div.img:hover {
border: 1px solid #777;
}
div.img img {
max-width:100%;
width: 100%;
height: 150px;
}
div.desc {
font-family:"arial";
background-color : lightgrey;
padding: 10px 20px;
height: 50px;
text-align: justify;
}
</style>
<body>
<div class="img" >
<apex:outputLink target="_blank" value="{!$Page.custrefdetail}" id="tst" > <!-- custrefdetail it is my second vfp -->
<apex:image value="{!account.photo__c}" height="150" width="200" />
</apex:outputLink>
<div class="desc"><h1>
{!account.Name}
</h1>
<p>
{!account.Description}
</p>
</div>
</div>
</body>
</apex:repeat>
</apex:pageBlock>
</apex:form>
</apex:page>
VFP: 2
<apex:page sidebar="false" showHeader="false" controller="sfdctest" action="{!hello1}" >
<apex:form >
<apex:pageBlock >
<apex:repeat value="{!accprd}" var="accs">
<p>
{!accs.Detail__c}
</p>
</apex:repeat>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller
Public with sharing class sfdctest{
Public List<Account> acc{get;set;}
Public List<accproducts__c> accprd{get;set;}
public ApexPages.StandardSetController setController { get; set;}
public String imageURL{get;set;}
Public String searchStr{get;set;}
public string productName{get;set;}
public Void hello1(){
accprd = New List<accproducts__c>();
accprd = [SELECT Detail__c from accproducts__c where Product__r.name =:productName and account__c in (select ID from Account where industry=:searchStr)];
System.debug(productName);
}
public List<selectoption> getIndustrynames()
{
list<selectoption> options = new list<selectoption>();
Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
list<schema.picklistentry> values = fieldResult.getPickListValues();
options.add(new SelectOption('select','Select Industry'));
for (Schema.PicklistEntry a : values)
{
options.add(new SelectOption(a.getLabel(), a.getValue()));
}
return options;
}
public List<SelectOption> getItems() {
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('selectprd','Select Product'));
for(product2 c : [select ID, name from product2 where ID IN( select Product__c from accproducts__c )]){
options.add(new SelectOption(c.ID, c.name));
}
return options;
}
public sfdctest()
{
acc = New List<Account>();
imageURL='/servlet/servlet.FileDownload?file=';
List< document > documentList=[select name from document where Name='logo'];
if(documentList.size()>0)
{
imageURL=imageURL+documentList[0].id;
}
}
Public void soslDemo_method(){
System.debug(searchStr);
if(searchStr.length() > 1 && searchStr != 'select'){
acc = [SELECT Name,image__c,photo__c,Description,website from Account where industry=:searchStr and Id in (select account__c from accproducts__c where Product__c = :productName ) ];
System.debug('product');
if(acc.size() == 0) {
apexPages.addmessage(new apexpages.message(apexpages.severity.WARNING, 'Sorry, data not found'));
return;
}
}
else{
acc = [SELECT Name,image__c,photo__c,Description,website from Account where Id in (select account__c from accproducts__c ) ];
}
}
}
I try to display the hello1 method detail__c value in my vfp2.
Thanks,
M. Sivasankari.
- Sivasankari Muthu
- March 03, 2016
- Like
- 0
- Continue reading or reply
more record Not saved at a time
I am facing one problem like i have created a vf page for record saving.when i am saving one record it is saving
but when i am saving more than one record at a time it is not saving.can any one help me..
public class BankBookTestPage { public String message = System.CurrentPagereference().getParameters().get('msg'); public List<AccountWrapper> wrappers {get; set;} public List<AccountWrapper> wrappers1 {get; set;} public List<MasterTest__c> master {get; set;} public List<BankBookTest__c> bankbook {get; set;} public static Integer toDelIdent {get; set;} public static Integer addCount {get; set;} private Integer nextIdent=1; public BankBookTestPage(){ init(); } private void init(){ wrappers=new List<AccountWrapper>(); Wrappers1=new List<AccountWrapper>(); for (Integer idx=0; idx<1; idx++){ wrappers.add(new AccountWrapper(nextIdent++)); wrappers1.add(new AccountWrapper(nextIdent++)); } } public void delWrapper(){ Integer toDelPos=-1; for (Integer idx=0; idx<wrappers.size(); idx++){ if (wrappers[idx].ident==toDelIdent){ toDelPos=idx; } } if (-1!=toDelPos){ wrappers.remove(toDelPos); } } /* public void delWrapper() { Integer toDelPos = -1; for( Integer idx = 0; idx < wrappers.size(); idx++ ) { if( wrappers[idx].ident == toDelIdent ) { toDelPos = idx; } } if( toDelPos != -1 ) { BankBookTest__c bk = wrappers.get( toDelPos ).acc; wrappers.remove( toDelPos ); delete bk; } }*/ public void addRows(){ List<BankBookTest__c> accs=new List<BankBookTest__c>(); for (AccountWrapper wrap : wrappers){ accs.add(wrap.acc); } // Upsert accs; AccountWrapper objAccWrapper; for (Integer idx=0; idx<addCount; idx++){ objAccWrapper = new AccountWrapper(nextIdent++); if(!wrappers.isEmpty()){ objAccWrapper.acc.BankAccount__c= wrappers[0].acc.BankAccount__c; objAccWrapper.acc.Date__c= wrappers[0].acc.Date__c; objAccWrapper.acc.Transaction_Type__c= wrappers[0].acc.Transaction_Type__c; } wrappers.add(objAccWrapper); } } public PageReference save(){ try{ List<BankBookTest__c> accs=new List<BankBookTest__c>(); for (AccountWrapper wrap : wrappers){ accs.add(wrap.acc); } Upsert accs; //return new PageReference('/' + Schema.getGlobalDescribe().get('BankBookTest__c').getDescribe().getKeyPrefix() + '/o'); init(); } catch(Exception e) { //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Sorry...... You have entered DUPLICATE MASTER CODE' ); // ApexPages.addMessage(myMsg); Apexpages.addMessage(new Apexpages.message(ApexPages.Severity.Error,'Please enter the field value')); } return null; } public class AccountWrapper{ public BankBookTest__c acc {get; private set;} public Integer ident {get; private set;} public AccountWrapper(Integer inIdent){ ident=inIdent; acc=new BankBookTest__c(); } } }
- Salesforce Test 5
- March 03, 2016
- Like
- 0
- Continue reading or reply