Key Prefix | Object Type |
---|---|
000 | Empty Key |
001 | Account |
002 | Note |
003 | Contact |
005 | User |
006 | Opportunity |
007 | Activity |
008 | OpportunityHistory |
00B | ListView / View |
00D | Organization |
00E | UserRole |
00G | Group |
00I | Partner Also OpportunityPartner, which "is automatically created when a Partner object is created for a partner relationship between an account and an opportunity" |
00J | OpportunityCompetitor |
00K | OpportunityContactRole |
00N | CustomFieldDefinition - Setup > Create > Objects > [Your Object] > [Your Field] |
CF00N | Custom Field Id using in the query string. Note the keyprefix isn't actually CF0. In this case "CF" has been appended to the "00N" of the Custom Field Definition. |
00O | Report |
00P | Attachment |
00Q | Lead |
00S | ImportQueue |
00T | Task |
00U | Event |
00X | EmailTemplate |
00Y | EmailTemp |
00a | CaseComment or IdeaComment Use caution as there are at least two object types exposed via the partner API with the same keyPrefix! |
00a | IdeaComment or CaseComment Use caution as there are at least two object types exposed via the partner API with the same keyPrefix! |
00b | WebLink - Custom Button or Link |
00c | Training |
00e | Profile |
00h | Layout - Page Layout |
00i | Pricebook |
00j | Product |
00k | OpportunityLineItem |
00l | Folder |
00o | OpportunityLineItemSchedule Represents information about the quantity, revenue distribution, and delivery dates for a particular OpportunityLineItem. Products, Price Books, and Schedules Overview |
00p | UserTeamMember |
00q | OpportunityTeamMember - "This object is available only in organizations that have enabled team selling." |
00r | AccountShare |
00s | AccountOwnerSharingRule |
00t | OpportunityShare |
00u | OpportunityOwnerSharingRule |
00v | CampaignMember |
010 | CaseSolution |
011 | GroupMember |
012 | RecordType |
013 | RecordTypePicklist |
014 | ProfileRecordType |
015 | Document |
016 | BrandTemplate (Letterhead) |
018 | EmailStatus |
019 | BusinessProcess |
01A | BusinessProcessPicklist |
01B | LayoutSection |
01C | LayoutItem |
01D | UserAccountTeamMember |
01G | ProfileLayout |
01H | MailmergeTemplate |
01I | Custom Object |
01J | PicklistMaster |
01N | Scontrol |
01P | ProfileTabConfiguration |
01Q | WorkflowRule - AssignmentRule |
01R | RuleFilter |
01S | RuleFilterItem |
01T | RuleFilterAction |
01U | ActionAssignEscalate |
01V | ActionTask |
01W | ActionEmail |
01X | ActionEmailRecipient |
01Y | CampaignMemberStatus |
01Z | Dashboard |
01a | DashboardComponent |
01b | ListViewCriterion |
01c | ListViewDisplayColumn |
01e | PicklistSet |
01h | Translation |
01j | LocalizedValue |
01k | FieldPermissions |
01l | ActionResponse |
01m | BusinessHours |
01n | CaseShare |
01o | LeadShare |
01p | ApexClass |
01q | ApexTrigger |
01r | CustomTabDefinition - Visualforce Tab |
01s | Pricebook2 |
01t | Product2 |
01u | PricebookEntry |
01v | PricebookShare |
01w | OpportunityUpdateReminder |
01y | CaseOwnerSharingRule |
01z | CaseEscalation |
020 | EventAttendee |
022 | FiscalYearSettings |
023 | Calendar |
024 | CalendarShare |
025 | ListLayoutItem |
026 | Period |
02A | LeadOwnerSharingRule |
02B | LabelDefinition |
02C | LabelData |
02D | CaseHistory2 |
02F | CustomFieldMap |
02T | CustomPage |
02U | CustomPageItem |
02V | PageComponent |
02X | CustomPageProfile |
02Y | UserComponentData |
02Z | AccountContactRole |
02a | ContractContactRole |
02b | ComponentResourceLink |
02c | Sharing Rule |
02f | DelegateGroup |
02g | DelegateGroupMember |
02h | DelegateGroupGrant |
02i | Asset |
02k | ListLayout |
02m | CustomIndex |
02n | CategoryNode |
02o | CategoryData |
02p | DivTransferEvent |
02q | LayoutItemColumn |
02r | OpportunityAlert |
02t | EmailRoutingAddress |
02u | TabSet |
02v | TabSetMember |
02w | LoginIpRange |
02x | LoginHours |
02y | ReportAggregate |
02z | ReportColorRange |
033 | AllPackage - Package being built in the developer org |
034 | PackageMember |
035 | SelfServiceUser |
036 | JobQueue |
037 | ReportColumn |
038 | ReportFilterItem |
039 | ReportBreak |
03D | ContactOwnerSharingRule |
03G | AccountCriteriaSharingRule |
03H | ContactCriteriaSharingRule |
03I | CaseCriteriaSharingRule |
03J | ChatterMessage |
03K | ChatterMessageThread |
03M | ChatterConversation |
03N | ChatterConversationMember |
03a | DependentPicklist |
03c | LayoutRightPanel |
03d | ValidationFormula - Validation Rule |
03e | CustomSetupDefinition |
03f | CustomSetup |
03g | QueueSobject |
03i | ConsoleConfig |
03j | CaseContactRole |
03k | ConsoleConfigItem |
03n | ApexClassIdentifier |
03q | ApexClassIdentifierRelationship |
03s | ContactShare |
03u | UserPreference |
040 | ReportParam |
043 | OutboundField |
044 | ExternalizedReference |
045 | PartnerNetworkSetup |
04Y | ActionFieldUpdate - Field Update |
04Z | EntityLock |
04a | ProcessDefinition |
04b | ProcessNode |
04c | ProcessTransition |
04d | ProcessTransitionCondition |
04e | ProcessActionItem |
04f | ProcessWorkitemProperties |
04g | ProcessInstance |
04h | ProcessInstanceStep |
04i | ProcessInstanceWorkitem |
04j | ProcessAllowedSubmitter |
04k | ActionOutboundMessage - Outbound Message Id |
04l | OutboundMessage - Outbound Notification Id |
04m | AdditionalNumber |
04n | SoftphoneLayout |
04o | SoftphoneLayoutSection |
04p | SoftphoneLayoutItem |
04q | SoftphoneLayoutInfoField |
04r | SoftphoneLayoutCallType |
04s | AsyncRequest - AsyncResult, DeployResult |
04t | AllPackageVersion - Install Package |
04u | ActionOverride |
04v | CallCenter |
04x | PackageExtension |
04z | LayoutItemActionRef |
050 | PackageLicense |
051 | UserPackageLicense |
052 | SfdcOutboundMessage |
053 | WorkflowTimeTrigger |
054 | WorkflowTimeAction |
055 | WorkflowTimeQueue |
056 | ContentTagName |
057 | ContentDocumentSubscription |
058 | ContentWorkspace |
059 | ContentWorkspaceDoc |
05A | ContentWorkspaceMembership |
05B | CampaignCriteriaSharingRule |
05C | ContentVersionComment |
05G | IpWhitelist |
05I | CampaignSharingRuleFilterItem |
05J | ContentVersionRating |
05K | ContentVersionRenditionContent |
05L | DBCThumbnailFilter |
05N | ContentVersionTagName |
05P | ContentWorkspacePermission |
05Q | ContentTagSubscription |
05R | ContentWorkspaceSubscription |
05S | ContentUserSubscription |
05T | ContentContent |
05U | EntityFeedLayout |
05V | ContentNotification |
05W | ContentNotificationParam |
05X | DocumentAttachmentMap |
05Z | ContentWorkspaceRecentEvent |
05t | CustomEntityTranslation |
060 | Portal |
061 | PortalAccount |
062 | PortalStyleConfig |
063 | MobileConfig |
064 | QuerySet |
065 | QuerySetItem |
066 | ApexPage |
067 | PortalMember |
068 | ContentVersion |
069 | ContentDocument |
06A | ContentDocumentLink |
06B | ContentWorkspaceAllowedRecType |
06G | CustomConsoleComponent |
06N | ApplicationDependency |
06O | ServiceDeskAttributes |
06P | Application - Connected App |
070 | CustomReportType |
071 | CrtObject |
072 | CrtColumn - Related to reports in some way. |
073 | CrtLayoutSection |
076 | RateLimitingNotification |
078 | ApiUsage |
079 | MobileMarkedRecord |
07A | MassMail |
07D | FeedPostTemplate |
07E | Sandbox |
07F | FeedFavorite |
07G | SummaryRecalcQueue |
07J | ComponentObjectDependency |
07K | ComponentFeatureDependency |
07L | ApexLog |
07M | ApexTestResult |
07O | Canvas |
07P | EntitySizeJob |
07R | DataCategoryMapping |
07T | AuthConfig |
07U | AuthConfigProviders |
07V | ActionSend |
07Y | BatchOrgSizeJob |
07Z | EntityDataSize |
07e | FeedPostTemplateItem |
07n | ApexExecutionOverlayResult |
080 | PacCrudPermission |
081 | StaticResource |
082 | UninstallExport - Data from Uninstalled Packages? A zip containing CSVs. |
083 | Vote |
084 | VoteConfig |
085 | VoteStats |
086 | MobileDevice |
087 | Idea |
08E | AddressCountry |
08F | AddressState |
08a | CronJobDetail |
08d | CampaignOwnerSharingRule |
08e | CronTrigger |
08g | CronFiredTrigger |
08s | CampaignShare |
090 | MobileExcludedField |
091 | EmailServicesFunction |
092 | Weekly Data Export |
093 | EmailServicesAddress |
094 | MobileView |
095 | MobileViewSortColumn |
096 | MobileViewDisplayColumn |
097 | MobileViewFilter |
099 | ApexComponent |
09A | FeedPollChoice |
09B | FeedPollVote |
09D | QuickActionDefinition |
09F | DatacloudPurchaseUsage |
09H | ConnectedApplication2 |
09I | QuickActionListItem |
09J | QuickActionList |
09S | AsyncRequestFFX |
09T | AsyncRequestFFXResult |
09U | DomainCookieStore |
09V | DashboardStickyFilter |
09a | Community |
0A0 | ReportJob |
0A1 | ReportJobFieldMap |
0A2 | DevelopmentPackageVersion - Change Set |
0A3 | InstalledPackageVersion - Installed Package |
0A4 | ProcessTransitionApprover |
0A5 | AllManagedPackageMember |
0A7 | CustomShareRowCause |
0A8 | ReportJobRun |
0A9 | ReportJobRunError |
0AB | ProfilePortalDelegate |
0AD | PackageEvent |
0AH | CompactLayout |
0AI | FirehoseCheckpoint |
0AL | ExternalSocialAccount |
0AM | CompactLayoutItem |
0AN | CompactLayoutMapping |
0AT | EventLogFile |
0AU | AuthSecurityLevel |
0AW | CanvasFeedItem |
0AX | ConsolePersonalization |
0AZ | ActionApex |
0Af | DeployRequest |
0Ai | DeployMessage |
0Aj | AsyncApiTransformationSpec |
0Ak | AuthSession |
0Al | DeployTestResult |
0B0 | MobileEntitySetting |
0B1 | MessageIdentifier |
0B2 | PortalLanguageConfig |
0B3 | PortalLanguageTabConfig |
0B9 | MobileTab |
0BA | CustomDataType |
0BB | CustomDataTypeComponent |
0BC | CustomFieldDataColumn |
0BE | FileFieldData |
0BF | ComponentAppVersion |
0BG | CampaignInfluenceAdjustment |
0BH | AllManagedClassRelationship |
0BI | ContentVersionMap |
0BJ | ActionAssignTeam |
0BL | PackageIdMapping |
0BM | Connection - Salesforce to Salesforce |
0BR | LogSearchResult |
0BV | OpportunityCriteriaSharingRule |
0BW | MobilePushDevice |
0BX | HistoricalEntityConfig |
0BY | MqSlaRequest |
0BZ | EmailBrand |
0Ba | LoginBrandAsset |
0Bb | LoginBrand |
0Bc | MqSlaJob |
0Bd | HistoricalFieldConfig |
0Be | HistoricalTransactionPrefix |
0Bf | HistoricalStaging |
0Bi | HistoricalSelectorValue |
0Bk | HistoricalSelector |
0Bl | BlacklistedConsumer |
0C0 | Holiday |
0C2 | MobileSession |
0C8 | LongJob |
0CC | SiteChangelistComponent |
0CF | ChatterNowUserFavorites |
0CI | EntityImplements |
0CJ | FieldImplements |
0CL | SiteChangelist |
0CS | ChatterNowUserSettings |
0Ci | AppManifest |
0D1 | DataCategoryGroup |
0D2 | OrgWideEmailAddress |
0D3 | OrgEmailAddressSecurity |
0D4 | LeadCriteriaSharingRule |
0D5 | FeedItem or NewsFeed or UserProfileFeed Use caution as there are at least three object types exposed via the partner API with the same keyPrefix! |
0D6 | FeedTrackedChange |
0D7 | FeedComment |
0D8 | AllManagedMemberOption |
0D9 | LeadSharingRuleFilterItem |
0DA | EntityCategoryGroup |
0DC | ProcessTransitionAction |
0DD | SynonymGroup |
0DE | Synonym |
0DF | VersionSet |
0DG | NamedFilter |
0DH | FieldAttributes |
0DM | Site |
0DN | SitePageOverride |
0DR | AndroidPushApplicationSetup |
0DS | AppMenuItem |
0DT | IdeaReputationLevel |
0DU | LimitUsageHistory |
0DV | PushUpgradeRequest |
0DX | PushUpgradeJob |
0DY | PushUpgradeJobError |
0Db | ForecastingType |
0Df | InstanceSizeJob |
0E0 | EmailSyncConfig |
0E1 | EmailSyncEntitySetting |
0E2 | EmailSyncFieldMapping |
0E3 | EmailSyncValueMapping |
0E4 | EmailConfigEntitySetting |
0E5 | EmailUserEntitySetting |
0E6 | EmailSyncAdvancedSetting |
0E8 | EntitySubscription |
0EA | PackageVersionPatchOrg |
0EB | Renderer |
0EG | ReportChart |
0EH | SummaryLayout |
0EI | SummaryLayoutItem |
0EJ | SummaryLayoutSliceInfo |
0EM | ContentReference - Appears next to refid query string parameter when pulling images. See rtaimage servlet parameters…what does the refid refer to? |
0EO | PicklistItemProperty |
0EP | Inbound Change Set? |
0EQ | CategoryJobTask |
0ER | RichTextAreaFieldData |
0EV | AllInstalledPackageVersion |
0Eb | ModuleDependency |
0Ee | HistoricalDataFilter |
0Ef | HistoricalDataFilterItem |
0Eg | GlobalDbKey |
0F0 | EmailTempAttachmentMap |
0F3 | ReportBlock |
0F5 | PhotoItem |
0F7 | FeedPost |
0F8 | SoftphoneScreenPopOption |
0F9 | CollaborationGroup |
0FA | CsnDomain |
0FB | CollaborationGroupMember |
0FG | MobilePushServiceDevice |
0FH | LinkReference |
0FM | FeedMapping |
0FO | OrgSizeJob |
0FP | ReportRunTracker |
0FQ | TrialMaster |
0FR | PackageOperationError |
0FT | TopicAssignment |
0Fa | ContextFieldAttributes |
0G1 | FeedFieldHistory |
0G8 | ReportBucketField |
0G9 | AccountSharingRuleFilterItem |
0GC | EmailDisclaimer |
0GD | ReportBucketFieldValue |
0GE | ReportBucketFieldSourceValue |
0GH | SchemaBuilderLayout |
0GI | SchemaBuilderLayoutItem |
0GJ | ApplePushApplicationSetup |
0H0 | SiteRedirectMapping |
0H1 | CollaborationInvitation |
0H4 | ConnectedApplication |
0H7 | PackageSupportAccess |
0HF | PublishEvent |
0HG | EntitySharingModel |
0HI | ReportBlockAggregate |
0HN | TwoFactorInfo |
0HO | MobilePushSetupRegistry |
0HR | MetricsTransmissionHistory |
0Hi | AppIpRange |
0Hj | AppManifestVersion |
0Hk | ConnectivityDevConfig |
0Hl | ConnectivityAttributes |
0I0 | FeedLike |
0I2 | SiteAsset |
0I3 | SiteComponent |
0I4 | Domain |
0I5 | CollaborationGroupMemberRequest |
0I6 | OpportunitySharingRuleFilterItem |
0I7 | CaseSharingRuleFilterItem |
0I8 | ContactSharingRuleFilterItem |
0I9 | ReportObjectFilterItem |
0IA | KnowledgeLanguageConfig |
0IB | DashboardFilter |
0IC | DashboardFilterItem |
0ID | DashboardFilterRepCol |
0IF | PushTopic |
0II | FeedCrossReference |
0IO | BrandingValue |
0IS | ApexComponentAttribute |
0IV | LogSearch |
0IX | FieldSet |
0IY | FieldSetItem |
0Ih | ServiceDeskComponent |
0Ii | PushProfileMapping |
0Ij | PushIntent |
0Ik | Module |
0In | PhoenixDataSync |
0Io | RawEmail |
0J0 | SetupEntityAccess |
0J2 | Personalization |
0J4 | SPSamlAttributes |
0J5 | PredictiveModel |
0J8 | ServiceDeskHotkey |
0JS | JigsawSavedSearch |
0Jf | DomainSite |
0K0 | ActionKnowledgeSubmit |
0K2 | ActionChatterPost |
0K3 | ActionChatterPostRecipient |
0LD | RecalcCampaignStats |
0LG | ReportInstance |
0LN | StorageSizeJob |
0M1 | SocialUserAuth |
0ME | SessionLevelPolicy |
0MF | SynonymDictionary |
0MJ | SystemStreamingChannel |
0O0 | XinstanceInfo |
0P0 | FlowVariableAssignment |
0P1 | Certificate |
0P2 | CertificateIp |
0PF | ParallelJobItemData |
0PL | PermissionSetLicense |
0PQ | ProcessTimeQueue |
0PS | PermissionSet - Permission set metadata |
0Pa | PermissionSetAssignment |
0Q0 | Quote |
0Qc | ActionQuickCreate |
0RA | ActivityRelation |
0RE | EventRelation |
0RT | TaskRelation |
0SO | AuthProvider |
0TI | TopicIndex |
0TO | Topic |
0TY | TopicOntology |
0Tt | TopicTerm |
0XC | ExternalDataSource |
0XU | ExternalDataUserAuth |
0Ya | LoginHistory |
0Ym | SetupAuditTrail |
0Ys | ParallelJobStatus |
0Yu | IdpEventLog |
0Yw | UserLogin |
0ca | ChatterActivity |
0cs | OauthConsumerScope |
0e1 | ProfileClientSettings |
0eb | EntityBlacklist |
0hc | HashtagCount |
0hd | HashtagDefinition |
0ht | Hashtag |
0in | Influence |
0ns | ProcessNodeSecurity |
0rp | RemoteProxy |
0sp | ServiceProvider |
0tR | TopicRecordSetting |
0tS | TopicSuggestionSetting |
0te | TopicUserEvent |
0tg | TopicGroupActivity |
0tr | TrendingTopic |
0ts | ProcessTransitionSecurity |
0tu | TopicUserActivity |
100 | UserLicense |
101 | ExternalString - Custom Label |
102 | FeatureLicense |
10y | TaskRecurrenceException |
10z | EventRecurrenceException |
110 | ObjectPermissions |
111 | EventComments |
112 | ProposedEventTime |
113 | ProposedEventResponse |
11a | DBCThumbnail |
1ci | Integration |
1cl | ChangeList |
1dc | MetadataContainer - from the Tooling AP |
1de | IDEWorkspace |
1do | ApexExecutionOverlayAction |
1dp | IDEPerspective |
1dr | ContainerAsyncRequest - from the Tooling API |
204 | SfdcPartner |
2LA | PermissionSetLicenseAssign |
300 | InteractionDefinition |
301 | InteractionDefinitionVersion |
308 | InteractionCondition |
309 | InteractionOperand |
30A | InteractionAllocator |
30C | InteractionChoice |
30D | InteractionDecision |
30F | InteractionForm |
30L | InteractionConnector |
30Q | InteractionQuestion |
30R | InteractionReference |
30S | InteractionStatement |
30V | InteractionVariable |
30a | InteractionAllocation |
30c | InteractionConstant |
30d | InteractionDataColumn |
30f | InteractionFormula |
30g | InteractionLayoutGroup |
30m | InteractionApexCall |
30r | InteractionResource |
30t | InteractionTodo |
30v | InteractionValueList |
310 | InteractionLayoutDetail |
31A | Subinteraction |
31C | SubinteractionVariableAssignment |
31S | InteractionSwitch |
31V | InteractionFieldValue |
31c | InteractionChoiceLookup |
31d | InteractionDataSource |
31i | InteractionDataInput |
31o | InteractionDataOutput |
31v | InteractionValueListEntry |
3M1 | OrgObjectsMetrics |
3M3 | ChatterMetrics |
3M4 | ChatterOrgWideMetrics |
3M5 | NetworkCustomerLoginMetrics |
3M6 | NetworkPartnerLoginMetrics |
3MA | PermissionSetMetricsByOrg |
3MC | OpportunityMetrics |
3MD | ContentMetrics |
3MF | SharingRowCauseMetrics |
3MG | SharingMetrics |
3MH | IdeaMetrics |
3MI | UserDimMetrics |
3MJ | PermissionSetLicenseMetrics |
400 | ApexClassMember |
401 | ApexTriggerMember |
402 | ApexPageMember |
403 | ApexComponentMember |
4A0 | MetadataCheckout |
4F0 | ApexClassVersion |
4F1 | ApexTriggerVersion |
4F2 | ApexPageVersion |
4F3 | ApexComponentVersion |
500 | Case |
501 | Solution |
5Sp | SegmentSpace |
608 | ForecastShare |
6AA | AssociationQueueItem |
6AB | EventAssociationItem |
6AC | MailAssociationItem |
6AD | TaskAssociationItem |
701 | Campaign |
707 | AsyncApexJob |
708 | BatchApexRelationship |
709 | ApexTestQueueItem |
710 | LoginIp |
711 | ApiLoginKey |
712 | LoginIpEmail |
713 | ClientBrowser |
714 | ApexCodeCoverage |
715 | ApexCodeCoverageAggregate |
716 | ApexOrgWideCoverage |
729 | Photo |
737 | FieldHistory |
750 | AsyncApiJob - Bulk Query Job |
751 | AsyncApiBatch - Bulk Query Batch |
752 | AsyncApiQueryResult - Bulk Query Result |
753 | TempStore |
754 | AsyncApiJobOptions |
766 | UiStyleDefinition |
777 | UiStyle |
7tf | TraceFlag |
800 | Contract |
806 | Approval |
80D | OrganizationValue |
888 | OauthConsumer - Remote Access |
Wednesday, December 11, 2013
List of the Salesforce Object Key Prefixes
Labels:Interview Questions
Apex,
Interview Questions,
VisualForce
System.Exception: SObject row does not allow errors
Scenario:
Error: System.Exception: SObject row does not allow errors
This Exception is thrown when your adding an error message to particular record in a list which is looping through For Loop and that list gets records from the Trigger.oldMap context variable in Trigger.You can you use the addError method for only those records that are available in Trigger Context.
Trigger Example:
trigger BeforeDeleteConatct on Contact (Before Delete)
{
Set<Id> conSet=Trigger.OldMap.keyset();
List<Contact> listCon=[select id,phone from contact where id in:conset];
for(Contact c:listCon)
{
if(c.Phone!=null)
{
System.debug('.......c......'+c);
c.addError('you cant delete this contact because it conatins Phone Number');
}
}
}
When you click on delete button of a particular contact it throws below error
Validation Errors While Saving Record(s) |
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger BeforeDeleteConatct caused an unexpected exception, contact your administrator: BeforeDeleteConatct: execution of BeforeDelete caused by: System.FinalException: SObject row does not allow errors: Trigger.BeforeDeleteConatct: line 11, column 1". |
Work Around to Resolve This Error:
trigger BeforeDeleteConatct on Contact (Before Delete)
{
Set<Id> conSet=Trigger.OldMap.keyset();
List<Contact> listCon=[select id,phone from contact where id in:conset];
for(Contact c:listCon)
{
if(c.Phone!=null)
{
System.debug('.......c......'+c);
Add below line of code to resolve Error
Contact actualRecord = Trigger.oldMap.get(c.Id);
actualRecord.addError('you cant delete this contact bcz it conatins Phone Number');
}
}
}
Validation Errors While Saving Record(s) |
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "you can't delete this contact because it conatins Phone Number". |
Labels:Interview Questions
Apex,
Errors,
Interview Questions,
VisualForce
Test Class for Before Trigger in Salesforce
Test Class:
In the previous post I have posted one Before Trigger .For that Trigger the test class is given Below.
Test Class Code:
@IsTest
In the previous post I have posted one Before Trigger .For that Trigger the test class is given Below.
Test Class Code:
@IsTest
private class Account_Trigger_Test { private static testMethod void testDelete() { Account acc=new Account(Name='Test Account;); insert acc; // should succeed delete acc; } private static testMethod void testDeleteFail() { Account acc=new Account(Name='Test Account', Client_ID__c='Should fail'); insert acc; try { delete acc; // should throw an exception - the following assertion will cause an error if the code carries on System.assert(false); } catch (DMLException e) { // expected - could assert the message here } } }
Labels:Interview Questions
Apex,
Interview Questions,
VisualForce
Before Delete Trigger in Salesforce
Scenario:
Write a Trigger on Account Object, All it does is to prevents the Delete of an Account if a particular field(i.e.,Client_ID__c) is not Null.
Trigger Code:
trigger AccountTrigger on Account (before delete)
{
if(System.Trigger.IsDelete)
{
for (Account acc : trigger.old)
{
if (String.isNotBlank(acc.Client_ID__c))
{
acc.addError('You cannot delete This Account Please contact your Salesforce.com Administrator for assistance.');
}
}
}
}
Notes:
Trigger.old | Returns a list of the old versions of the sObject records.Note that this sObject list is only available in update and delete triggers. |
Trigger.isDelete | Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API. |
For more information/samples on trigger please check out here
Please comment or write us if you have any queries/requirements.
Please follow,bookmark,subscribe this site to receive daily updates.
Facebook - https://www.facebook.com/ILoveCodingYou/?ref=bookmarks
Please follow,bookmark,subscribe this site to receive daily updates.
Facebook - https://www.facebook.com/ILoveCodingYou/?ref=bookmarks
Hope this helps you..Enjoy..!
Labels:Interview Questions
Apex,
Interview Questions,
Triggers
Friday, November 29, 2013
Test Class Example For Messaging.IndboundEmail Class
Apex Class:
global class inBoundEmail implements Messaging.InboundEmailHandler
{
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope)
{
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
String subToCompare = 'Create Contact';
if(email.subject.equalsIgnoreCase(subToCompare))
{
Contact c = new Contact();
c.Email=email.fromAddress;
// capture phone number and city also from incoming email.
// Splits each line by the terminating newline character
// and looks for the position of the phone number and city
String[] emailBody = email.plainTextBody.split('\n', 0);
c.LastName=emailBody[0].substring(0);
c.Phone = emailBody[1].substring(0);
c.Title = emailBody[2].substring(0);
insert c;
// Save attachments, if any
if (email.textAttachments != null)
{
for(Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments)
{
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = c.Id;
insert attachment;
}
}
//Save any Binary Attachment
if (email.binaryAttachments != null)
{
for(Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
Attachment attachment = new Attachment();
attachment.Name = bAttachment.fileName;
attachment.Body = bAttachment.body;
attachment.ParentId = c.Id;
insert attachment;
}
}
}
result.success = true;
return result;
}
}
Test Class For Above Class:
@isTest(seeAllData=true);
Private Class InBoundEmailTest()
{
//Test Method for main class
static testMethod void TestinBoundEmail()
{
Test.startTest();
// create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
// setup the data for the email
email.subject = 'Create Contact';
email.fromAddress = 'someaddress@email.com';
email.plainTextBody = 'email body\n2225256325\nTitle';
// add an Binary attachment
Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
attachment.body = blob.valueOf('my attachment text');
attachment.fileName = 'textfileone.txt';
attachment.mimeTypeSubType = 'text/plain';
email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
// add an Text atatchment
Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
attachmenttext.body = 'my attachment text';
attachmenttext.fileName = 'textfiletwo3.txt';
attachmenttext.mimeTypeSubType = 'texttwo/plain';
email.textAttachments = new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
// call the email service class and test it with the data in the testMethod
inBoundEmail testInbound=new inBoundEmail ();
testInbound.handleInboundEmail(email, env);
}
}
global class inBoundEmail implements Messaging.InboundEmailHandler
{
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope)
{
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
String subToCompare = 'Create Contact';
if(email.subject.equalsIgnoreCase(subToCompare))
{
Contact c = new Contact();
c.Email=email.fromAddress;
// capture phone number and city also from incoming email.
// Splits each line by the terminating newline character
// and looks for the position of the phone number and city
String[] emailBody = email.plainTextBody.split('\n', 0);
c.LastName=emailBody[0].substring(0);
c.Phone = emailBody[1].substring(0);
c.Title = emailBody[2].substring(0);
insert c;
// Save attachments, if any
if (email.textAttachments != null)
{
for(Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments)
{
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = c.Id;
insert attachment;
}
}
//Save any Binary Attachment
if (email.binaryAttachments != null)
{
for(Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
Attachment attachment = new Attachment();
attachment.Name = bAttachment.fileName;
attachment.Body = bAttachment.body;
attachment.ParentId = c.Id;
insert attachment;
}
}
}
result.success = true;
return result;
}
}
Test Class For Above Class:
@isTest(seeAllData=true);
Private Class InBoundEmailTest()
{
//Test Method for main class
static testMethod void TestinBoundEmail()
{
Test.startTest();
// create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
// setup the data for the email
email.subject = 'Create Contact';
email.fromAddress = 'someaddress@email.com';
email.plainTextBody = 'email body\n2225256325\nTitle';
// add an Binary attachment
Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
attachment.body = blob.valueOf('my attachment text');
attachment.fileName = 'textfileone.txt';
attachment.mimeTypeSubType = 'text/plain';
email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
// add an Text atatchment
Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
attachmenttext.body = 'my attachment text';
attachmenttext.fileName = 'textfiletwo3.txt';
attachmenttext.mimeTypeSubType = 'texttwo/plain';
email.textAttachments = new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
// call the email service class and test it with the data in the testMethod
inBoundEmail testInbound=new inBoundEmail ();
testInbound.handleInboundEmail(email, env);
}
}
Labels:Interview Questions
Apex,
VisualForce
Thursday, November 21, 2013
Like Operator in SOQL Query
Like Operator:
Like Operator in SOQL act as a Comparison operator for String Field Expression.Expression is true if the value in the specified fieldName matches the characters of the text string in the specified value. It provides a mechanism for matching partial text strings and includes support for wildcards.
Notes:
%-->Specifies that Zero ,One or more characters
_ --> Specifies that only One character.
SOQL Query Examples for Like Operator
Example, the following query matches Appleton, Apple, and Bappl , but not Appl:
SELECT Id, Name FROM Widget__c WHERE Name LIKE 'appl_%'
Example 1:Withou Using Variable
1.[Select Id,FirstName form User where FirstName LIKE 'srinivas'];
2.[Select Id,FirstName form User where FirstName LIKE '%srinivas'];
3.[Select Id,FirstName form User where FirstName LIKE '%srinivas_'];
Example 2:Like Using Variable need to use (:) bind Variavble
User object contains FirstName as below Records:
1. srinivasa
2. msrinivasa
3. srinivas
String firstname ='srinivas';
User u= [SELECT Id , FirstName,LastName FROM User where FirstName LIKE : firstName LIMIT 9];
This query returns Users record from User object where FirstName of user is srinivas only.
output: srinivas record only number3
Example 2:Using variable with % and _ wildcard characters
String firstname ='srinivas';
String str='%'+firstname +'%';
User u= [SELECT Id , FirstName,LastName FROM User where FirstName LIKE : firstName LIMIT 9];
This query will return Users record from User object where FirstName of User contains srinivas
output:It returns Three Records 1. srinivasa 2. msrinivasa 3. srinivas
Like Operator in SOQL act as a Comparison operator for String Field Expression.Expression is true if the value in the specified fieldName matches the characters of the text string in the specified value. It provides a mechanism for matching partial text strings and includes support for wildcards.
Notes:
- The % and _ wildcards are supported for the LIKE operator.
- The % wildcard matches zero or more characters.
- The _ wildcard matches exactly one character.
- The text string in the specified value must be enclosed in single quotes.
- The LIKE operator is supported for string fields only.
- The LIKE operator performs a case-insensitive match, unlike the case-sensitive matching in SQL.
- The LIKE operator in SOQL and SOSL supports escaping of special characters % or _.
- Do not use the backslash character in a search except to escape a special character.
%-->Specifies that Zero ,One or more characters
_ --> Specifies that only One character.
SOQL Query Examples for Like Operator
Example, the following query matches Appleton, Apple, and Bappl , but not Appl:
SELECT Id, Name FROM Widget__c WHERE Name LIKE 'appl_%'
Example 1:Withou Using Variable
1.[Select Id,FirstName form User where FirstName LIKE 'srinivas'];
2.[Select Id,FirstName form User where FirstName LIKE '%srinivas'];
3.[Select Id,FirstName form User where FirstName LIKE '%srinivas_'];
Example 2:Like Using Variable need to use (:) bind Variavble
User object contains FirstName as below Records:
1. srinivasa
2. msrinivasa
3. srinivas
String firstname ='srinivas';
User u= [SELECT Id , FirstName,LastName FROM User where FirstName LIKE : firstName LIMIT 9];
This query returns Users record from User object where FirstName of user is srinivas only.
output: srinivas record only number3
Example 2:Using variable with % and _ wildcard characters
String firstname ='srinivas';
String str='%'+firstname +'%';
User u= [SELECT Id , FirstName,LastName FROM User where FirstName LIKE : firstName LIMIT 9];
This query will return Users record from User object where FirstName of User contains srinivas
output:It returns Three Records 1. srinivasa 2. msrinivasa 3. srinivas
Labels:Interview Questions
Apex,
Integration,
VisualForce
Thursday, October 24, 2013
Working with Custom SOAP and REST Services in .NET Applications
The Force.com platform gives developers a multitude of choices for accessing data. The SOAP API and REST API
provide complete access to standard and custom Force.com objects.
However, the need often arises to extend built-in functionality in order
to support unique business requirements. Fortunately for Force.com
developers, it's simple to create powerful, custom services that can be
consumed in any platform.
This article explains how developers can build custom Force.com SOAP and REST services and consume them in .NET applications.
For More information please Click Here.
This article explains how developers can build custom Force.com SOAP and REST services and consume them in .NET applications.
For More information please Click Here.
Labels:Interview Questions
Apex,
Integration,
WebServices
Friday, October 11, 2013
Editing Multiple Records at a Time using the RecordSetVar
Scenario:
You want to edit multiple records at a time ,Don't worry .Salesforce also provided Standard List Controllers(RecordSetVar) along with Standard ,Custom and Extension Controllers.By using RecordSetVar we can achieve it.
RecordSetVar:
This attribute indicates that the page uses a set-oriented standard controller. The value of the attribute indicates the name of the set of records passed to the page. This record set can be used in expressions to return values for display on the page or to perform actions on the set of records. For example, if your page is using the standard accounts controller, and recordSetVar is set to "accounts".
Standard list controllers can be used with the following objects:
VisualForce Page:
You want to edit multiple records at a time ,Don't worry .Salesforce also provided Standard List Controllers(RecordSetVar) along with Standard ,Custom and Extension Controllers.By using RecordSetVar we can achieve it.
RecordSetVar:
This attribute indicates that the page uses a set-oriented standard controller. The value of the attribute indicates the name of the set of records passed to the page. This record set can be used in expressions to return values for display on the page or to perform actions on the set of records. For example, if your page is using the standard accounts controller, and recordSetVar is set to "accounts".
Standard list controllers can be used with the following objects:
- Account
- Asset
- Campaign
- Case
- Contact
- Contract
- Idea
- Lead
- Opportunity
- Order
- Product2
- Solution
- User
- Custom objects
VisualForce Page:
<apex:page standardController="Opportunity"
recordSetVar="opportunities"
tabStyle="Opportunity" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageMessages />
<apex:pageBlockButtons >
<apex:commandButton value="Save"
action="{!save}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!opportunities}"
var="opp">
<apex:column HeaderValue="Oppty Name">
<apex:inputField value="{!opp.name}"/>
</apex:column>
<apex:column headerValue="Stage">
<apex:inputField value="{!opp.stageName}"/>
</apex:column>
<apex:column headerValue="Close Date">
<apex:inputField value="{!opp.closeDate}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Note:
By default the RecordSetVar only displays 20 records at a time.If you want change
the number of records displayed you can use the extension controller to set the size.
ScreenShots:
Before changing the AB oppty stage from NeedAnalysis to ProposalPriceQuote |
After changing the AB oppty stage from NeedAnalysis to ProposalPriceQuote |
Monday, September 30, 2013
Submit a Form with the Enter Key
Problem
You've created a form in Visualforce. When pushing enter while using the form, the page refreshes instead of submitting your form. It's an easy fix with a small bit of JavaScript, which does wonders for your app's user experience.Solution
In your Visualforce page, define this JavaScript function. It intercepts key presses on your form elements.01 | <script type= 'text/javascript' > |
02 | function noenter(ev) { |
03 | if (window.event && window.event.keyCode = = 13 || ev.which = = 13 ) { |
04 | doSearchAF(); |
05 | return false; |
06 | } else { |
07 | return true; |
08 | } |
09 | } |
10 | </script> | | | | | | | | | | | |
Also, define this ActionFunction and tie it to your submit method in your controller.
1 | <apex:actionFunction name= 'doSearchAF' action= '{!doSearch}' / > |
Lastly, this 'onkeypress' event should be added to every textual form element that should intercept a press of the enter key.
1 | <apex:inputtext value= '{!settings.searchStr}' id= 'searchStr' styleclass= 'searchStr' onkeypress= 'return noenter(event);' / > |
Discussion
Make sure the ActionFunction name matches up with the JavaScript function you're calling from noEnter(). When someone hits Enter, the noEnter() JavaScript function will get called, which in turn will call the doSearchAF ActionFunction, which invokes your forms submit action, in this case doSearch().
Labels:Interview Questions
Apex,
VisualForce
How to Hide the Current Date Link on an Inputfield
Problem
The standard apex:inputfield component for a date field generates a link next to the input field, taking a lot of space. The link allows someone to easily enter the current date. However, when you use multiple date fields within a table component, it can be confusing for the user to have these extra links (see Screenshots). This recipe solves this by creating a Visualforce component that uses CSS to remove the link.
Note the extra links next to each and every date field.
Modified Behavior: Using a Visualforce component to remove the current date link
As you can see, this is a much more compact view.
Discussion
This code is dependent on the standard salesforce look and feel - and in particular dependent on it not changing. By examining the standard CSS, we know that the current date link is in a span.dateInput span.dateFormat CSS element. So this may be a little fickle depending on UI changes - but it should be easy to change if the standard UI CSS does ever change.
The standard apex:inputfield component for a date field generates a link next to the input field, taking a lot of space. The link allows someone to easily enter the current date. However, when you use multiple date fields within a table component, it can be confusing for the user to have these extra links (see Screenshots). This recipe solves this by creating a Visualforce component that uses CSS to remove the link.
Screenshots
Default Behavior: Current date link is renderedNote the extra links next to each and every date field.
Modified Behavior: Using a Visualforce component to remove the current date link
As you can see, this is a much more compact view.
Visualforce Component Code
Here's the code for the Visualforce component. It wraps the component body in an HTML div tag, and adds styling to hide a part of that wrapped component. <apex:component access="global">
<style>
div.hideCurrDate span.dateInput span.dateFormat{
display:none;
}
</style>
<div class="hideCurrDate">
<apex:componentBody />
</div>
</apex:component>
How to use the component
Here's a simple Visualforce page to demonstrate component usage: <apex:page standardController="Opportunity">
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<c:noDateLink>
<apex:inputField value="{!Opportunity.CloseDate}"/>
<c:noDateLink>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Discussion
This code is dependent on the standard salesforce look and feel - and in particular dependent on it not changing. By examining the standard CSS, we know that the current date link is in a span.dateInput span.dateFormat CSS element. So this may be a little fickle depending on UI changes - but it should be easy to change if the standard UI CSS does ever change.
Enjoy.....!!
Labels:Interview Questions
Apex,
Salesforce,
VisualForce
Friday, September 27, 2013
Most Important OnLine Tool for Coding and Decoding(i.e.,For Conversion)
Coder's Tool Box:
The Coder’s Toolbox contains all the little tools you never know where to find.
- Time conversion – convert between Unix timestamp, ISO8601 and RFC 2822 formats
- String conversion – encode/decode Base64-encoding; escape XML, URL's and ECMAScript; translate to UTF-8
- Number conversion – convert between decimal, hexadecimal, octal and binary numbers
- Network – calculate netmasks, broadcast addresses and do DNS lookups
- Bandwidth – calculate the duration of file transfer
- XPath debugger – test your XPath expressions
http://coderstoolbox.net/string/#!encoding=base64&action=encode&charset=iso_8859_1
Labels:Interview Questions
Apex,
Integration,
WebServices,
Xml Parsing
Displaying Selected Records Below With Help of Action Support Function
Scenario:
I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.
VisualForce Page:
<apex:page controller="wrapperClassController">
<apex:form >
<apex:pageBlock >
<!-- In our table we are displaying the cContact records -->
<apex:pageBlockTable value="{!contacts}" var="c" >
<apex:column >
<apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
<!-- This is our selected Boolean property in our wrapper class -->
<apex:inputCheckbox value="{!c.selected}" />
</apex:actionSupport>
</apex:column>
<!-- This is how we access the contact values within our cContact container/wrapper -->
<apex:column value="{!c.con.Name}" />
<apex:column value="{!c.con.Email}" />
<apex:column value="{!c.con.Phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock id="test">
<apex:outputPanel id="pbt2">
Total No of Selected Records :<apex:outputText value="{!value }"/>
<apex:pageBlockTable value="{!SelectedContacts}" var="c" >
<apex:column value="{!c.Name}" />
<apex:column value="{!c.Email}" />
<apex:column value="{!c.Phone}" />
</apex:pageBlockTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller Class:
public class wrapperClassController
{
//Our collection of the class/wrapper objects cContact
public List<cContact> contactList {get; set;}
public List<Contact> selectedContacts{get;set;}
public Integer value {get;set;}
public List<cContact> getContacts()
{
if(contactList == null) {
contactList = new List<cContact>();
for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
{
//As each contact is processed we create a new cContact object and add it to the contactList
contactList.add(new cContact(c));
}
}
return contactList;
}
public PageReference processSelected()
{
//We create a new list of Contacts that we be populated only with Contacts if they are selected
selectedContacts = new List<Contact>();
//We will cycle through our list of cContacts and will check to see if the selected
//property is set to true, if it is we add the Contact to the selectedContacts list
for(cContact cCon : getContacts())
{
if(cCon.selected == true)
{
selectedContacts.add(cCon.con);
}
}
value = selectedContacts.size();
System.debug('printing listcontc'+selectedContacts.size());
// Now we have our list of selected contacts and can perform any type of logic we want,
// sending emails, updating a field on the Contact, etc
return null;
}
//This is our wrapper/container class. A container class is a class,a data structure,or an
//abstract data type whose instances are collections of other objects. In this example a
//wrapper class contains both the standard salesforce object Contact and a Boolean value
public class cContact
{
public Contact con {get; set;}
public Boolean selected {get; set;}
//This is the contructor method. When we create a new cContact object we pass a Contact
//that is set to the con property. We also set the selected value to false
public cContact(Contact c)
{
con = c;
selected = false;
}
}
}
ScreenShot:
I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.
VisualForce Page:
<apex:page controller="wrapperClassController">
<apex:form >
<apex:pageBlock >
<!-- In our table we are displaying the cContact records -->
<apex:pageBlockTable value="{!contacts}" var="c" >
<apex:column >
<apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
<!-- This is our selected Boolean property in our wrapper class -->
<apex:inputCheckbox value="{!c.selected}" />
</apex:actionSupport>
</apex:column>
<!-- This is how we access the contact values within our cContact container/wrapper -->
<apex:column value="{!c.con.Name}" />
<apex:column value="{!c.con.Email}" />
<apex:column value="{!c.con.Phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock id="test">
<apex:outputPanel id="pbt2">
Total No of Selected Records :<apex:outputText value="{!value }"/>
<apex:pageBlockTable value="{!SelectedContacts}" var="c" >
<apex:column value="{!c.Name}" />
<apex:column value="{!c.Email}" />
<apex:column value="{!c.Phone}" />
</apex:pageBlockTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller Class:
public class wrapperClassController
{
//Our collection of the class/wrapper objects cContact
public List<cContact> contactList {get; set;}
public List<Contact> selectedContacts{get;set;}
public Integer value {get;set;}
public List<cContact> getContacts()
{
if(contactList == null) {
contactList = new List<cContact>();
for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
{
//As each contact is processed we create a new cContact object and add it to the contactList
contactList.add(new cContact(c));
}
}
return contactList;
}
public PageReference processSelected()
{
//We create a new list of Contacts that we be populated only with Contacts if they are selected
selectedContacts = new List<Contact>();
//We will cycle through our list of cContacts and will check to see if the selected
//property is set to true, if it is we add the Contact to the selectedContacts list
for(cContact cCon : getContacts())
{
if(cCon.selected == true)
{
selectedContacts.add(cCon.con);
}
}
value = selectedContacts.size();
System.debug('printing listcontc'+selectedContacts.size());
// Now we have our list of selected contacts and can perform any type of logic we want,
// sending emails, updating a field on the Contact, etc
return null;
}
//This is our wrapper/container class. A container class is a class,a data structure,or an
//abstract data type whose instances are collections of other objects. In this example a
//wrapper class contains both the standard salesforce object Contact and a Boolean value
public class cContact
{
public Contact con {get; set;}
public Boolean selected {get; set;}
//This is the contructor method. When we create a new cContact object we pass a Contact
//that is set to the con property. We also set the selected value to false
public cContact(Contact c)
{
con = c;
selected = false;
}
}
}
ScreenShot:
Labels:Interview Questions
Apex,
VisualForce
Displaying Selected Records Below With Help of Action Support Function
Scenario:
I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.
VisualForce Page:
<apex:page controller="wrapperClassController">
<apex:form >
<apex:pageBlock >
<!-- In our table we are displaying the cContact records -->
<apex:pageBlockTable value="{!contacts}" var="c" >
<apex:column >
<apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
<!-- This is our selected Boolean property in our wrapper class -->
<apex:inputCheckbox value="{!c.selected}" />
</apex:actionSupport>
</apex:column>
<!-- This is how we access the contact values within our cContact container/wrapper -->
<apex:column value="{!c.con.Name}" />
<apex:column value="{!c.con.Email}" />
<apex:column value="{!c.con.Phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock id="test">
<apex:outputPanel id="pbt2">
Total No of Selected Records :<apex:outputText value="{!value }"/>
<apex:pageBlockTable value="{!SelectedContacts}" var="c" >
<apex:column value="{!c.Name}" />
<apex:column value="{!c.Email}" />
<apex:column value="{!c.Phone}" />
</apex:pageBlockTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller Class:
public class wrapperClassController
{
//Our collection of the class/wrapper objects cContact
public List<cContact> contactList {get; set;}
public List<Contact> selectedContacts{get;set;}
public Integer value {get;set;}
public List<cContact> getContacts()
{
if(contactList == null) {
contactList = new List<cContact>();
for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
{
//As each contact is processed we create a new cContact object and add it to the contactList
contactList.add(new cContact(c));
}
}
return contactList;
}
public PageReference processSelected()
{
//We create a new list of Contacts that we be populated only with Contacts if they are selected
selectedContacts = new List<Contact>();
//We will cycle through our list of cContacts and will check to see if the selected
//property is set to true, if it is we add the Contact to the selectedContacts list
for(cContact cCon : getContacts())
{
if(cCon.selected == true)
{
selectedContacts.add(cCon.con);
}
}
value = selectedContacts.size();
System.debug('printing listcontc'+selectedContacts.size());
// Now we have our list of selected contacts and can perform any type of logic we want,
// sending emails, updating a field on the Contact, etc
return null;
}
public List<Contact> getSelectedContacts()
{
System.debug('printing listcontc inside get'+selectedContacts.size());
if(selectedContacts.size()>0)
return selectedContacts;
else return null;
}
//This is our wrapper/container class. A container class is a class,a data structure,or an
//abstract data type whose instances are collections of other objects. In this example a
//wrapper class contains both the standard salesforce object Contact and a Boolean value
public class cContact
{
public Contact con {get; set;}
public Boolean selected {get; set;}
//This is the contructor method. When we create a new cContact object we pass a Contact
//that is set to the con property. We also set the selected value to false
public cContact(Contact c)
{
con = c;
selected = false;
}
}
}
ScreenShot:
I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.
VisualForce Page:
<apex:page controller="wrapperClassController">
<apex:form >
<apex:pageBlock >
<!-- In our table we are displaying the cContact records -->
<apex:pageBlockTable value="{!contacts}" var="c" >
<apex:column >
<apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
<!-- This is our selected Boolean property in our wrapper class -->
<apex:inputCheckbox value="{!c.selected}" />
</apex:actionSupport>
</apex:column>
<!-- This is how we access the contact values within our cContact container/wrapper -->
<apex:column value="{!c.con.Name}" />
<apex:column value="{!c.con.Email}" />
<apex:column value="{!c.con.Phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock id="test">
<apex:outputPanel id="pbt2">
Total No of Selected Records :<apex:outputText value="{!value }"/>
<apex:pageBlockTable value="{!SelectedContacts}" var="c" >
<apex:column value="{!c.Name}" />
<apex:column value="{!c.Email}" />
<apex:column value="{!c.Phone}" />
</apex:pageBlockTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller Class:
public class wrapperClassController
{
//Our collection of the class/wrapper objects cContact
public List<cContact> contactList {get; set;}
public List<Contact> selectedContacts{get;set;}
public Integer value {get;set;}
public List<cContact> getContacts()
{
if(contactList == null) {
contactList = new List<cContact>();
for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
{
//As each contact is processed we create a new cContact object and add it to the contactList
contactList.add(new cContact(c));
}
}
return contactList;
}
public PageReference processSelected()
{
//We create a new list of Contacts that we be populated only with Contacts if they are selected
selectedContacts = new List<Contact>();
//We will cycle through our list of cContacts and will check to see if the selected
//property is set to true, if it is we add the Contact to the selectedContacts list
for(cContact cCon : getContacts())
{
if(cCon.selected == true)
{
selectedContacts.add(cCon.con);
}
}
value = selectedContacts.size();
System.debug('printing listcontc'+selectedContacts.size());
// Now we have our list of selected contacts and can perform any type of logic we want,
// sending emails, updating a field on the Contact, etc
return null;
}
public List<Contact> getSelectedContacts()
{
System.debug('printing listcontc inside get'+selectedContacts.size());
if(selectedContacts.size()>0)
return selectedContacts;
else return null;
}
//This is our wrapper/container class. A container class is a class,a data structure,or an
//abstract data type whose instances are collections of other objects. In this example a
//wrapper class contains both the standard salesforce object Contact and a Boolean value
public class cContact
{
public Contact con {get; set;}
public Boolean selected {get; set;}
//This is the contructor method. When we create a new cContact object we pass a Contact
//that is set to the con property. We also set the selected value to false
public cContact(Contact c)
{
con = c;
selected = false;
}
}
}
ScreenShot:
Labels:Interview Questions
Apex,
VisualForce
Subscribe to:
Posts (Atom)