Translate Success Of Your career With Salesforce Training

Understanding the structure of Salesforce can help you get the most out of the platform. Regardless of whether you are a sales representative looking forward to closing more deals or are an account administrator, Salesforce training can help you with the plethora of benefits. Training is an important part of success in any organization. Training is required for someone to gets introduced to a new job or roll out a business change. Implementing a new technology solution is not an exception, and proper training is required in the field. It is often an overlooked component of sales force rollout.

Salesforce training in Hyderabad

In many organizations today, resources are limited. A team might have the internal expertise to train others on a new system, but they might have several other priority projects to handle. It is because of this reason that you should get in touch with us for the best Salesforce training in Hyderabad. There are hosts of benefits available with training. You can look forward to training your employees to use a new business technology without experiencing any issues with the complexities. The training involves using and defining business processes that are specific to the organization.

About Us:

We are one of the leading institutions in Hyderabad for offering Salesforce training. We have offered this training service since a long time, and consequently, it has benefited lots of organizations to date. We have wide varieties of classes available for all roles. These include end users, administrators, implementers, developers, and architects. Whether you approach us as an individual or an organization, we are ready to offer you the best training courses so that it helps you in the future. We have options for both online and traditional classes and these are led by experienced and qualified faculty.  Our courses are up to date and thorough mostly covering all the topics necessary for users to learn this platform.

The courses that we offer are of a very short time. As a result, you need not leave your job to enroll in our course. As our courses are finished, we issue the certification that will prove to be highly beneficial for now and the future. Through our training courses, users will get an idea of what is happening and acquire real-world experience required for understanding the platform. We also offer tailor-made programs for individual students so that it can help them improve their learning curve and establish a great career prospect in the years to come.

Why This Salesforce training Course:

There are several reasons for which Salesforce training course is recommended in this cutting-edge competition. It is ideal for system administrators managing the configuration and maintaining the salesforce application in an organization. In addition to that, courses are also available for experienced administrators to create an impact dashboard and report along with automating intricate business processes. This in turn will help in getting the most out of Salesforce. The trail. The consequent program is also designed in such a way so that it will help in building applications and customize multi-user cloud applications a few clicks few clickety, it will help in automating your business processes.

We are confident in what we offer, and, therefore, we are sure that if you enroll for our training, you will have no looking back. Since the course duration is of a very short time, it will not be difficult for you to acquire the same. We have certified trainers to guide you and assist you through the course. Moreover, we have three different delivery models along with hands-on lab facilities that will work wonders for you, as a whole.

Advantage Of Learning This Course:

As mentioned, there are innumerable benefits that you will obtain by learning salesforce training in Hyderabad.

  • It will help in managing, measuring and growing business on a single dashboard.
  • It will boost productivity and sales performance.
  • The effectiveness of sales will improve that will drive more revenue growth to a new height.
  • It is not only easy to use but also easy to deploy and implement.

It is estimated that users of Salesforce have achieved 45% of returns on investment within the first few months. Therefore, if you and your organization enroll for the training, you will have endless possibilities of earning now and in the future.

Our institute is the number 1 choice for students and professionals in Hyderabad and many other parts of India. We schedule programs with updated methodologies and offer them, as per the convenience of the candidates. There is no denying that it is a globally recognized certification with great job prospects anywhere in the world. We also offer the option of customized training model providing all the more flexibility and array of choices to our students. Successful reporting and higher user adoption requires organizations to use technology, in the same way. The training program helps in building the Salesforce environment, according to the specific business processes.

Job Opportunities:

By now, most organizations are well aware of the huge buzz of Salesforce consulting. Consequently, they have created the demand for qualified professionals in this field. If you acquire training from us, we can assure you some of the best jobs in the top companies in India and abroad.  Salesforce is an investment and the solution must drive real business value to offset costs. Salesforce training promotes higher user adoption. The more the people using the system correctly, the better it will function to meet the goals. The knowledge and skills that you acquired from our institution will work wonders for your career.

Not only can you find some of the best jobs, but also make use of the knowledge among the employees in your company. The entire team will work forward with it promoting the betterment of your organization, as a whole. Your team wants to do the best job with the tools you provide. Hence, it enables them to bring higher value to the company with better compensation, advancements, opportunities, and benefits. Therefore, it is high time that you enroll for our Salesforce training and reap the benefits of the same.

You can contact us for Salesforce training in Hyderabad, Ameerpet

 

SalesForce Course Syllabus

 

Cloud Computing

  • What is Cloud Computing?
  • SAAS/PAAS/IAAS
  • Types of cloud
  • Examples (Companies/Products)

CRM/ERP

  • What is CRM/ERP
  • Different Segment of CRM
  • CRM Entities
  • CRM Process Flow

Salesforce Overview

  • What is salesforce?
  • About the company their product.
  • Existing Competitors.

 

Force.com Platform

  • Overview
  • Creating Developer Environment
  1. Types of license and instances of salesforce
  •                                                                  Administration

User management

  1. Profiles Creation
  2. User Creation
  3. Permission Sets

Security management

  • Login Access
  1. IP Access
  2. Hours Access
  • Field Level security
  1. Profile
  • Object Level security
  1. Profile
  • Record level security.
  1. OWD(Organisational Wide Default)
  2. Role Hierarchy
  3. Sharing Rules

 

Email Templates

Email Management

Mass operation on standard objects

Connect with google app, outlook

Duplicate Management

 

  •                                                                            Development

 Salesforce Customization

  1. Standard and Custom Objects
  2. Standard and Custom Fields
  3. Object Relationships
  4. Page Layouts
  5. Record Type
  6. List view
  7. Workflow rules
  8. Approval  Process
  9. Validation rules
  10. Static Resources
  11. Custom Settings
  12. Custom Permissions
  13. Salesforce App
  14. Reports and Dashboards

 

Console Environment /Development mode.

What is Visualforce?

Visualforce Page / Components

What is APEX?

Apex triggers/Classes/Controllers

Where Apex classes can be used

Use of JavaScript in VF Page

Making Responsive (Mobile Devices Compatible) Pages

Salesforce Sites

Schema Builder

                                                                                               Integration

  • What is Integration?
  1. Inbound
  2. Outbound
  • Declarative Integration:
  1. Salesforce to Salesforce
  2. Outbound Messaging
  • Programmatic Integration
  1. SOAP API
  2. REST API
  3. BULK API
  • Authentication
  1. OAuth 2.0
  2. SOAP
  • Using Workbench
  • App Exchange

 

 

Project Implementation

  • CRM project(Campaign management, Lead management, Opportunity management)
  • CMS Project.

 

Faculties Profiles:

 

PRASANT Garu:-

Meticulous and highly accomplished professional with 4+ years of experience in the areas of Software Development and in enhancement of projects in SalesForce.com and .Net technologies.

 Credited with experience in developing User Interface, Page Layouts, Tabs, Custom fields, Custom objects, Validation Rules, Triggers, Reports, Dashboards etc.

 Worked on Salesforce Apps like Conga Composer, Echo Sign and Attachment Manager.

 Adept at using data migration tools like Apex Data Loader, Salesforce Import and Export Wizard.

 Working knowledge on Custom Permissions.

 Basic Overview on Lightning components.

 Adept in using Informatica Cloud for integration Salesforce with Oracle Database.

 Adroit in translating business process into custom objects and creating look-up relationships and master-detail relationships.

 Excellent knowledge of programming and database like .Net and PL/SQL.

 Sound knowledge of all phases of SDLC.

 

SAMRAT  Guru:-

Around 4+ years of experience in Software Development Life Cycle (SDLC) which involves requirement gathering,requirement analysis, design, development, implementation & enhancement of Projects in both SalesForce.com and Microsoft.NET technologies.

 Experience in Administration, Configuration, Implementation and support experience with Salesforce.com platform.

 SFDC Configurations/Customizations – User Interface, Page Layouts, Tabs, Custom fields, Custom objects, Validation Rules, Triggers, etc.

 Experience in SFDC related technologies such as Apex, Visual Force.

 Extensive experience over creating workflows, approval processes, validation rules and sharing & security rules.

 Experience in web Development using C#.NET, ASP.NET, SQL server.

 Excellent domain knowledge on Accounting Application.

 Excellent domain knowledge on CRM functionality like Campaign, Lead, Account, Opportunity, Case management.

 Having experience in development, maintenance and enhancement of Continuous Integration for daily builds using Jenkins server.

 Experience in following Agile (Scrum Methodology) for software Development.

 

SalesForce Classroom Notes

[sociallocker]

Introduction

Cloud Computing:

Cloud Computing is a crowd/ group of UN know resources that are giving for a specific purpose to the user.

  • It is a concept of pay per use of each IT Service.
  • Cloud Computing is a concept of accessing infrastructure, platform and software as a service over the internet by paying the each use of the IT Services.

There are three services in cloud computing. They are called cloud services.

  1. IAAS (Infrastructure As A Service):

Accessing infrastructure such as application server, storage server over the internet is called IAAS.

  1. PAAS (Platform As A Service):

It is the concept of accessing a platform such as any programming language on which an application is built provided as service over the internet is called PAAS.

Example: Force. Com – The platform used by the Sales force Google App Engine

  1. SAAS (Software As A Service):

It is the concept of accessing a software application over the internet is called SAAS.

Ex:

Sales force CRM

MS CRM

 

Advantages:

  • It reduces the cost.
  • Increased Storage
  • Simple User interface that is well received by users.
  • Flexibility:

No need to install any software and no need to buy any Licences.

We can access from any Location.

  • Every small industries can also use Sales force CRM because of low cost.
  • Low Maintains and Low Risk.
  • Sales force will have Multi – tent ant Architecture.
  • Sales force adds extra features for every release. They are three types of Releases.
  1. Summer Release
  2. Winter Release
  3. Spring Release

Different Products of Sales force:

Salesforce.com offers everything we need to transform our business into a social Enterprise, So we can connect to customers and employees like never before. With no software or hardware to install, we are up and running and seeing a positive impact on business quickly with salesforce.com

  • Force.com – Force.com is the cloud platform to automate and extend the business by developing the applications.
  • Radian6 – It is the social media monitoring and engagement platform. This will be responsible for Listen, Analyze and engagement in conversations with customers on public Social web.
  • Site.com – Design a publish websites, social pages, templates with the first web in the cloud. It’s built for social, so we can easily add twitter streams, face book likes and more…
  • Heroku – Heroku  is a cloud application platform a new way of building and deploying web pages
  • Data.com – it deals with correct data.
  • Database.com – it is the only database service natively built for social enterprise.
  • App Exchange – App exchange is the directory where we can get the in- built applications. We can directly download the application from the App exchange and we can use it.
  • Chatter – it will boost employee productivity with a private and secure social network for company for internal communication.

What is Sales force Automation?

  • Sales force Automation is on- demand customer Relationship Management System CRM.
  • Out – of –box functionality.

Sales force Automation includes:

* Marketing Management.

* Sales Automation

* Customer Support Management.

 

Diagram: 1

 

Sales force marketing includes:

Campaign Management

Lead Management

Search Marketing

Contact Management

Sales Automation includes:

Opportunity Manage

Account Management

Customer Support Management includes:

Case Management

Solutions Management

I.e. Logging cases

Suggesting and delivering solutions.

Customer Portal

 

Campaigns:

A campaign is any marketing project that we want to plan, manage, and track in sales force.

 

Leads:

A Lead is any person, organization or company that may be interested in our products. Sometimes leads are referred to as Prospects or Suspects. Leads are not yet Customers.

 

Accounts:

An Account is an Organization, individual or company involved with business such as customers, competitors and partners that wish to track in sales force.

 

Contacts:

A contact is any individual or influence associated with an account that we want to track in sales force.

 

Opportunities:

An Opportunity is any potential revenue- generated event (“Sales deal” ) that we want to track in sales force.

 

Cases:

A Case is a detailed description of a customer’s feedback, problem or question.

 

Solutions:

A Solution is a detailed description of a customer issue and the resolution of that issue. The collection of organization’s Solution is sometimes referred to as the solution knowledge base.

 

Forecasts:

A forecast is best estimate of how much revenue we can generate in a quarter.

 

Reports:

Reports are summaries and analyses of data, which we can display or print.

 

Dashboards:

Dashboards give us a real- time snap shot of corporate metrics and key performance indicators. Dashboard is a group of different charts (Or components) that graphically display custom report data.

 

Calendar and Task:

Activities are both tasks and schedule Calendar events. We can define and track activities for many different objects, including campaigns, accounts, contacts, and leads.

 

Profiles:  And Users:

A)

  • A profile is a collection of settings and permissions that define how a user access records.
  • Profiles Control a user’s permissions to perform different functions in sales force.
  • A profile can have many users but a user can have only one profile.

 

Users:

The people who have authenticated user name and password to log on to sales force successfully.

Each Sales force user must be assigned a profile.

There are two types of profiles

  1. Standard Profiles and
  2. Custom Profiles.

Standard Profiles are provided with Force.com and cannot be renamed or deleted. Custom profiles have the same functionality as Standard profiles but can be named. They Can also be deleted if there are no users assigned to them.

  • To manage profiles, Click Set up, and in the Administration setup Area, Click Mange users – Profiles.

B) What does a profile Control?

Profiles control the following:

  1. Page Layouts: Which page layout the user sees
  2. Field Level Security: The FLS restricts user’s access to view and edit fields.
  3. Custom Apps: Which standard and custom apps the user can view.
  4. Tabs: which tabs the user can view.
  5. Record Types: Which record types are available to the user
  6. Login: the hours and IP Addresses from which the user can log 1n.
  7. Administrative, General and object permissions.

 

Object permissions:

The object permissions are divided into two sections, one for standard objects and another for custom Objects. The Permissions are,

Read: The Read Permission allows users to view records of the object.

Create:

The create permission permits Read Access and the permission to create the records to the object

Edit:

Edit Permission allows records in this object to be read and modified.

Delete:

This permission enables user to read, edit and remove records from this object. Deleted records are moved to the recycle Bin, Where they can be UN deleted or permanently erased.

 

View All and Modify All:

It allows users to view and modify all the fields of all records in object, overriding every other security measure.

 

*** Note:

If we give view all and modify all permissions at a profile level, then the security controls will not work, these permissions overrides the security Controls.

 

Field – Level Security:

  • Restricts users access to view and edit fields
  • Overrides any less – restrictive field access settings in page layouts and search layouts.
  • Controls which fields users can access in related lists, list views, reports, email and mail merge templates custom links.

Tab Settings:

The following are the tab settings options.

Default ON: if we want a tab to be displayed.

Default OFF: If we want a tab not to appear on the tab panel but still allowing a user assigned to the profile the choice to turn the tab back on.

Tab Hidden:

If we want the tab to be hidden without an option to the user to turn the tab back on.

List of Standard Profiles:

There are six (6) Standard Profiles:

  1. System Administrator.
  2. Standard User
  3. Solution Manager
  4. Marketing user
  5. Contract Manager
  6. Read Only.

 

  • Standard profiles cannot be edited, but the Tab settings and apps for standard profiles are always configurable.

System Administrator:

“Super User” – Can Customize everything in the application.

Standard User:

Can View edit, and delete their own records.

Solution Manger:

Standard User permissions + can manage published solutions + can manage solution categories.

Marketing User:

Standard User permissions + Can import leads for the Organization.

Contract Manager:

Standard user permissions + can edit, approve, activate and delete contracts.

Read Only:

Can only view records.

  • Enterprise, Developer and unlimited system Administrators can create an unlimited number of custom profiles from scratch However, the recommended method to create a custom profiles is to “Clone” and modify an existing profile.

Login Hours and Login IP Ranges:

  • Set the hours when users with a particular profile can use the system.
  • Sets the IP Addresses from which users with a particular profile can log in.

 

***** We cannot delete the user from the salesforce.com.

  • We can deactivate the user, so user can not able to login to salesforce.com.

 

Permission Sets:

  • A permission set is a collection of settings and permissions that give users access to various functions. The settings and permissions in permission sets are also found in profiles, but permission sets extended user’s functional access without changing their profiles.
  • For example, to give users to a custom object, create a permission set with the required permissions for the object, and assign the permission set to the users.
  • We never have to change profiles, or create a profile for a single use case.

While users can have only one profile, they can have multiple permission sets.

Permission Sets include the following:

  • Object and field permissions
  • App Permissions
  • Apex Class access
  • Visual force page access
  • System Permissions

 

*The Profile will have many users, if we give any permissions at the profile level then all the users assigned to that profile will effect.

If we want to give the permissions to only one user without changing the profile, then we have to create permission sets and assign to the users.

 

Note:

  • A profile has many users. But a user must have assigned to the single profile
  • Many permission sets we can assign it to single user.

Creating Permission Sets:

Go to the following path:

You’re Name:

Setup: Administration Setup: Mange Users: Permission Sets:

  1. Click on “New” Button
  2. Enter Labe, API Name and Description of permission set.
  3. Select “Sales force” as user license in the select the type of users who will use this permission set section
  4. Click on “Save” button
  5. Select either object and Field, App, Apex class, VF Page permissions
  6. Select the Object which we want to give permissions,
  7. Click on “Edit” button and give the related permissions
  8. Click on “Save” button.

 

Assigning Permission Sets:

From the user details page, we can assign permission sets or remove a permission set assignment.

Go to the following path for assigning permission sets to user.

Click Your Name – Setup- Manage Users – Users –

  1. Select the user which we want to assign permission set.
  2. In the permission set assignments related list, click “Edit Assignments”.
  3. To assign a permission set, select if from the available permission sets box and click “Add”.

To remove a permission set assignment, select it from the enables permission sets box and click “Remove” button.

Apps:

An application is a logical container for all of the objects tabs, processes and services associated with a given business function.

  • An app is a group of tabs that work as a unit to provide functionality.
  • We can customize existing app to match the way to work, or build new apps by grouping standard and custom tabs.
  • A Force.com custom app consists of a name, a description an ordered list of tabs, and optionally a custom logo and a landing page.
  • Sales force provides standard apps such as

*Sales

* Call Centre

* Marketing

* Community

* Users can switch between apps using the Force.com app drop – down menu at the top – right corner of every page.

There are two types of applications

  1. Custom App
  2. Service Cloud Console.

Creating a Custom Application:

Path for creating a custom application is

You’re Name: Setup – App Set up – Create – Apps – “New” button.

Step1:

Select the type of the application to create and click on “Next” button.

Step2:

Enter a label for the applications, a name, and a description, and then click the “Next” button.

Example: Institute, Pharmacy.. Etc.

Step3:

Optionally, select an image to be displayed as the logo for our application. This image is shown in the upper left corner when our application is active.

Tip:  To prepare an image for use as an application logo, first go to the documents tab and click the new button. Check the externally available image check box, centre a name to identify the image check box, centre a name to identify the image and click the browse button to locate a file on your computer click the save button to upload the image.

Step 4:

This screen is for selecting the tabs to be included in the custom application. Click on the “Next” button.

Diagram: 2

  • If we want to add the tabs to your application then select the particular tabs from the available tabs and click on “Add” arrow mark, so that we can see those tabs in the selected tabs.

Step 5:

This screen shows the restrict access to our application by profile. Choose the user profiles for which this custom app will be visible in Force.com menu.

  • We can specify this custom app as the default custom app of a profile, meaning that new users who have the profile will see this custom app when they log in for the first time.
  • If a custom app is set as the default for a profile, then we cannot make it invisible for that profile.
  • The click on the “Save” button.
  • After clicking on the “Save” button, we are returned to the list of applications, but it now contains our new application. If we active our application by selecting it from the list of applications, but it now contains our new application. If we active our application by selecting it from the list in the upper – right corner drop down , we can see the list of tabs which we have selected before in the Step 4.

Service Cloud Console:

The service cloud console is designed for users in fast – paced environments who need to find, update and create records in Sales force quickly.

  • The service cloud console displays all the records as tabs so that users can quickly find, update and create records on one screen.
  • Primary tab display the main record to work on, like an account

Sub tabs display related records, like cases or contacts on an account.

 

Objects:

 

There are two types of objects

  1. Standard Objects
  2. Custom Objects
  • Objects are data base tables that allow us to store data  specific to organization in Salesforce.com

 

Standard Objects:

The objects provided by salesforce.com are called standard objects.

AccountsCampaignsContracts
ContactsCasesForecasts
OpportunitiesSolutionsUsers
LeadsReportsIdeas
ProductsDashboardsAnswers

 

Custom Objects:

*Custom Objects are the heart of any application – Custom objects provide a structure for storing data.

Custom Objects have properties such as:

  • Custom fields
  • Relationship to other objects
  • Page Layouts
  • A Custom user interface tab (optional)

Creating Custom Object:

The following procedure we have to follow for creating a custom object.

Click on your name – Set Up – App Setup – Create – Objects – Click on “New Custom Object” button

Diagram 3

Record Name – According to the Data type we have selected below, the Record Name will work.

Text

Auto Number

  • Allow Reports – If we check this check box, going forward we can create Reports for this Object.

Allow Activities:

If we check this checkbox, we can create Activities for this object

Activities:

New Task, New Event

Track Field History:

If we check this check this check box, we can track every change made to fields in records for a table.

  • We can track up to 20 fields for an Object.

In development: If we check this check box, development only completed but without testing.

Deployed: if we check this check box, both development and testing completed and it is ready for deployment into the production environment.

The following options are available only when a custom Object is first created.

  • Add Notes and Attachments related list.
  • Launch New Custom tab wizard after saving this Custom Object.

Click on “Save” button.

Note: if we do not check the option called Launch New Custom Tab Wizard from above step, the object will save without tab appearance, then we have to create tab again for this object.

If we check the option, then the object will save and tab will created and appeared.

Tabs:

  • Every tab serves as the starting point for viewing, editing and entering information for a particular object. When we click a tab at the top of the page, the corresponding homepage for the object appears.

Custom Tabs:

A Custom tab is a user interface component we create to display custom object data or other web content embedded in the application.

There are two types of Custom tabs.

Custom Object Tabs:

Display the data of our custom object in a user interface tab.

Web Tabs:

Display any external web based application or web page in a user interface tab

  • Custom Tabs will have a Tab Style (Colour Scheme and  icon)

Visual force Tabs:

Allow us to embed VF pages.

Note:  New Custom Tabs extend Salesforce.com functionality or to build new application functionality.

Path for Creating a Tab:

You’re Name – Setup – App Set Up – Create – Tabs

Click on the “New” button

In the Object drop down list, select the object

  • Click the tab style look up icon to launch the tab style selection.
  • Click on the “Next” button, here we have to add the new custom tab to profiles for the availability to a user.
  • Click on the “Next” button; here choose the custom apps for which the new custom tab will be available.
  • Click on save button.
  • By default for every Custom Object , four fields are created those are,

1. Created By

2. Last Modified By (Both fields are used for audit fields.

3. Owner

4. Record Name.

Field Creation:

  • A field is like a database column. Object fields store the data for our object records.
  • Custom Objects automatically include some standard fields which I mentioned above.
  • Create Custom fields to store additional information.

There are two types of fields.

  1. Standard fields
  2. Custom fields.
Standard FieldsCustom Fields
  1. We cannot delete
  2. We can delete Custom fields
  3. We cannot create any more standard fields.
2.     We can create more custom fields.
  1. Don’t have API Name
         3.   Have API Name.

 

API means Application Program Interface:

We have to add this in formula fields and variables whatever we want to declare is called API Names.

Example:  Field Name = Active

API Name = Active __C

Path for creating fields for Standard Objects:

Your Name – Set Up – App Set Up – Customize – Select the Object – Click on Fields – Go to Custom fields and Relationships – Click on “New” button.

Path for Creating fields for Custom Objects:

You’re Name – setup – App Set Up – Create – Objects – Click on Any Object – Go to the Custom Fields & Relationships section – Click on “New” Button.

Steps for creating a field:

Step1:

Choose the field type which specifies the type of information that the Custom field will contain.

  1. Auto Number:

A System generated sequence number that uses a display format we define. The number is automatically incremented for each new record.

Example: If the display format is

Acc – {000}

Starting Number = 000

For the first record, the field value is Acc – {000}

And for the second record, the field value is Acc – {001}… and so on…

 

  1.  Check box:

Allow users to select a True (Checked) or False (Unchecked) Value.

The user interface should be like,

Checked (True)

UN Checked (False)

  1. Currency:

Allows users to enter a dollar or other currency amount value and automatically formats the fields as a Currency amount.

If the field value is 1000, then in the detail page it automatically adds the dollar symbol before the value

Example: $ 1000, we can enter up to 18 digits 14 integer, 4 decimals

 

  1. Date:

Allow users to enter a date or pick a date from a popup calendar.

Example:  4/2/2012

  1. Date/ Time:

Allow users to enter a date and time, or pick a date from a popup calendar. When users click a date in the popup, that date and the current time are entered into the Date / Time field.

Example: 4/2/2015 08:08 PM

 

  1. Email:

Allows users to enter an email address, which is validated to ensure proper format.

The User must specify the proper format for the Email field in order to save the record.

Example:  xyz@gmail..com

vii. Number:

Allows users to enter any number. Leading zeros are removed.
We can enter up to 18 digits.
14 digits for integer place and 4 digits for decimal place.
Example:
123456 ….. 14 digits .6789
(14 digits) (4 digits)
viii. Percent:
Allows users to enter a percentage number.
Example: If we enter “50” as a field Value, it automatically adds the percent sign to the number (50%)

ix. Phone:
Allows users to enter any phone number. Automatically formats it as (905) 275 – 7414

x. Pick List:
Allows users to select a value from a list we define.
• The maximum length of the text values is 40 Characters,
• We can give max of 300 pick list values.

xi. Pick List (Multi – Select):
The pick list (multi – select) field allows users to choose more than one pick list value from a set of pre-defined text values.
• The maximum length of the text values is 40 characters.
• After saving a record, the data is stored as text along with semi- colons which are used to separate the individual pick list values.
xii. Text:
The Text field allows entering any combination of alphanumeric characters.
Or
Allows users to enter any combination of letters and numbers.
• The maximum length of the text value is 255 Characters.
xiii. Text Area:
The Text Area field allows users to enter alpha numeric Characters on separate lines.

• The maximum length of text area value is 255 Characters on the separate lines.
xiv. Text Area (Long):
The Text Area (Long) provides for the storage of up to 32, 768 Characters that display on separate lines similar to a text Area field.
• This data type is not available for activities or products on opportunities.
• Every time we press Enter with in a long text area field, a line break, and a return character are added to the text. These two character count towards the 32, 768 Character limit.
xv. Text Area (Rich):
The Text Area (Rich) data type allows the users to enter a text value with formatted and add images and links up to 32, 768 Characters we can enter on separate lines.
• Also allows the users to undo, redo, bold, italicize, underline, strike- out, upload or link to an image.
• The maximum size for uploaded image is 1MB and only GIF, JPEG and PNG file types are supported.
xvi. Text (Encrypted):
• Allows users to enter any combination of letters and numbers and store them in encrypted form.
• The maximum length of the text value is 255 characters.
• For encrypted text, we can set a maximum length of up to 175 Characters.
xvii. URL:
Allows users to enter any valid website address.
When users click on the field value in the detail page, the URL will open in a separate browser window to show the web page.
• The URL field can store up to 255 characters. However, only the first 50 characters are displayed on the record detail pages.

Step 2:
Enter the details.
i. Give the Field Label with meaningful name, once we click Tab, then Field Name will be automatically pop up from the label. It is used to refer the field in Apex code, formula fields, and validation rules.
• Force.com appends the field Name with “__C” to differentiate it from standard fields.
• It’s good practice to give a description for the field which describes about the purpose of using that field.
Help Text:
It is possible to add field level help to a custom field to provide information to users on how to use that field.
If we provide a help text for field help text will be displayed once the mouse moves the icon containing the letter “i”.
Step 3:
Establish field – level Security
• Select the profiles to which we want to grant edit access to this field via field – level security. The field will be hidden from all profiles if we do not add it to field level security.
Step 4:
Add to page Layouts
• Select the page layouts that should include this field. The field will be added as the last field in the first 2 – column section of these page layouts.
• The field will not appear on any pages if we do not select a layout.
• To change the location of the field on the page, we will need to customize the page layout.
• Click on “Save” button to create a field successfully.
• Click on “Save & New” button to create more custom fields.
Important Points about Custom Fields:
• Changing the data type of existing custom fields is possible but doing so may. Cause data loss.
• Deleting a custom field removes both the data and the field.
• Custom fields are stored for 45 days after deletion.
• Changing the data type of existing custom field can cause data loss in the following situations.
i. Changing to or from Date or Date/ Time.
ii. Changing to Number from any other type.
iii. Changing to Percent from any other type.
iv. Changing to Currency from any other type.
v. Changing from Pick list (Multi – Select) from any type except pick list.
vi. Changing from Auto Numbers to any other type.
vii. Changing to Auto Number from any type except Text
viii. Changing from Text Area (Long) to any type except Email, phone, Text, Text Area, or URL.
• If data is Lost, any list view based on the Custom field will be deleted, and assignment and escalation rules may be affected.
Object Relationships:
Object relationships can be set on both standard and custom objects and are used to define how records in one object relate to records in another Object.
Example: Accounts can have a one- to – many relationships with opportunities and these relationships are presented in the application as related lists.
• Sales force provides the following types of relationships.
1) Look up Relationship
2) Master – Detail Relationship
3) Many- to – Many Relationship
4) Hierarchical Relationship

 

 

 

The differences between the Lookup and Master – detail relationships are:
Lookup Relationship Master – Detail Relationship
1. We can create 25 look up relationships for both standard and custom objects. 1. We can create 2 Master Detail relationships for Custom Objects.
1. Look up relationship can be created if records already exist. 2.Master detail relationship can’t be created if records already exists
2. If we deletes the parent record, then Childs will not deleted 3. If we delete the parent record, then Childs will be deleted automatically.
3. Optional 4.Mandatory

4. The Ownership and the sharing of a child record are not determined by the parent record. 5. The ownership and the sharing of a detail record are determined by the Master record.

Steps to test Lookup Relationship:
• Create a field with the data type as lookup Relationship on Account Object.
• Related to solutions (acts as a parent Object)
• After completing all the steps, the Accounts are the related list to solutions.
• Here we can create this relationship if account records already exist.
• Now, delete the solution record then check the accounts associated with the solution.
• Result will be the account records will not delete.
Steps to test Master- Detail Relationship:
Note: We can create M- D relationship on the custom Objects only. We cannot create on standard Objects.
i. Create a field with the data types as Master – Detail on any Custom Object
(Ex: Customer)
ii. Give related to cases (Cases will act as Master Object)
iii. This field will not be create when Customer records exists.
iv. After creating the field, the customers are the related list of cases.
v. Create a one case record, and also create Customer records for that case.
vi. Delete the case record, then check whether the customer’s record is deleted or not.
(Result will be Customer records will be deleted automatically)
Many – to – Many Relationships:
A many – to – many relationship allows each record of one Object to be linked to multiple records from another Object and Vice – Versa.
• When modelling a many – to – many relationships, we use a “Junction Object” to connect the two objects we want to relate to each other.
Junction Object:
A Custom object with two masters – detail relationships. Using a custom junction object, we can model a Many – to – Many relationship between two objects.
Diagram: 4
Example:
i. Create a custom Object called “Bug Case Association” ( Use the auto Number data type)
ii. For above custom object, create two master-detail relationships.
iii. While creating one master- details relationship chooses related to as “Case”.
iv. While Creating Second master-details relationship, choose related to as “Bug” (Custom Object)
v. While Creating “Bug Case Association” record, there we have to select values for two master- detail fields. From this we say that, we are creating a many – to – many relationships between the “case” and “Bug” through the Junction Object called “Bug Case Associations” custom Object.
Hierarchical Relationship:
Allow users to click a lookup icon and select another user from a pop-up-list.
• This type of relationship is a special lookup relationship available only for the user Object. It allows developers to create a Manager Field on the user Object to relate another user.
• This relationship will acts as a self relationships.
Example: If we want to link a custom Object called “Bug” with itself to how two different bugs are related to the same problem.
Formula Fields:
• A read- only field that derives its value from a formula expression we define. The formula is updated when any of the source fields change.
• Supported on standard and custom Objects.
• Can reference standard, custom or other formula fields.
• Can reference (These reference fields are called merge) fields on related objects.
• Number of characters we can enter is 3900 (Space will to one Character)
• The formula compile capacity is 4000 characters.
Building Formulas:
Consider the following steps to create a formula field.
i. Choose the formula data type
ii. Choose the data type for the formula based on the output of the calculation.
• Enter the number of decimal places for currency amount and automatically format the fields as a currency amount.
Date: Calculate a date.
Date/ Time: Calculate a date/time, for example, by adding a number of hours or days to another data/time.
Number: Calculate a numeric value.
Percent: Calculate a percent and automatically add the percent sign to the number.
Text: Create a text String, for example, by concatenating other text fields.
iii) Click “Next” to display the formula creation screen.

Basic formula:
Select the simple Formula tab, choose the field type in the select Field Type drop- down list, and choose one of the fields listed in the insert field drop – down list.
To insert an operator, choose the appropriate operator icon from the “Insert operator” drop down list.
Advanced Formula:
The basic formula feature is quite restricted and we can create more complicated formulas by selecting the advanced formula tab.
Within this tab, click on “insert field”, choose a field, and then click on “insert”.
Click check syntax to check our formula for errors.
• Formula fields:
1) Date & Time Functions:
Date (YYYY, MM, DD): used to display Date in month, Day, year format.
Date value: used to display the date on screen the input can be expression or text.
Date / Time: used to display Date/ Time stamp on the screen and the input can be field, expression, text.
Day: Extracts day from date field
Month: Extracts month from date field
Year: Extracts year from date field
Today(): will display present date.
Now(): it will display present date with time.
2. Text functions:
Begins:
Syntax: Begins (text, Compare- text)
Checks it text begins with specified character an returns True if it matches otherwise returns

Contains:
Syntax: Contains (text, compare-text)
Checks it text contains specified characters, and returns TRUE if it does, otherwise, returns FALSE
Find:
Syntax: find (search-text, [Start-num])
Returns the position of the Search- text String in text.
Includes:
Syntax: includes ( multiselect_picklist_field, text_literal)
Determines if any value selected in a multi –select pick list field equals a text literal you specify.
Is PICK VAL:
Syntax: isPICKval (picklist_field, text_literal)
Checks whether the value of a pick list field is equal to a String literal.

LEFT:
Syntax: LEFT (Text, number-chars)
Returns the specified number of characters from the start of a string from left side.

RIGHT:
Syntax: RIGHT (text, number-chars)
Returns the specified number of characters from the start of string from right side
MID:
Syntax: MID (text, start_num, num_chars)
Returns the characters from the middle of a text string mentioned number of characters from the starting position
LEN:
Syntax: LEN (text)
Returns the number of characters in a text String.

LOWER:
Syntax: LOWER (text)
Converts all letters in the value to lower case.
UPPER:
Syntax: UPPER (text)
Converts all letters in the value to upper case.

UPAD:
Syntax: LPAD (text, padding_ length, pad_String)
Pad the left side of the value with spaces or the optional pad String

RPAD:
Syntax: RPAD (text, padding_length, pad_String)
Pad the right side of the value with spaces or the optional pad String.

Substitute:
Syntax: Substitute (text, old-text, new-text)
Substitute new-text for old- text in a text String.
Text:
Syntax: Text (Value)
Converts a value to text using standard display format.

TRIM:
Syntax: TRIM (text)
Removes all spaces from a text sting expect for single spaces between words.
Math Functions:
ABS:
Syntax: ABS (number)
Returns the Absolute value of a number, a number without sign.
CEILING:
Syntax: CEILING (number)
Rounds a number to the nearest integer

EXP:
Syntax: Exp (number)
Returns ‘E’ raised to the power of a given number.
FLOOR:
Syntax: FLOOR (number)
Rounds a number down, towards zero to the nearest integer
isBlank:
Syntax: is blank (Expression)
Checks whether an Expression is blank and returns TRUE or FALSE
LN:
Syntax: LN (Number)
Returns the natural logarithm of a number
LOG:
Syntax: LOG (number)
Returns the base 10 log of ‘n’
Max:
Max (num1, num2 , num3 …. )
Returns the greatest of all numbers
MIN:
Min (num1, num2, num3… )
Returns the least of all numbers
Round:
Syntax: Round (number, num_digits)
Rounds a number to a specified number of digital

SQRT:
Syntax: SQRT (number)
Returns the positive square root of a number.

Logical Functions:
AND:
Syntax: AND (logic1, logic2 …)
It all logics are true it will return true otherwise returns false.

OR:
Syntax:
OR(logic1, logic2…)
If anyone logic is true it will return true, if all logics are false it will return false.

CASE:
Syntax: CASE (Expression, value1, result1, value2, result2, value3, result3 else result)
Checks an expression against a series of values it the expression compares equal to any value, the corresponding result is returned. If it is not email to any of the values, the else result is returned.

If:
Syntax: IF (logical-test, value-if-true, value-if-false) checks whether a condition is true, returns one value if true and anther value false.
ISNULL:
Syntax: ISNULL (Expression)
Checks whether an expression is null and returns TRUE (or) FALSE.

ISNUMBER:
Syntax: ISNUMBER (Text)
Returns TRUE it the text value is a number. Otherwise it returns false.

NOT:
Syntax: NOT (logical)
Changes false to TRUE or TRUE to false

NULL VALUE:
Syntax: null value (expression, substitute Expression)
Checks whether expression IS NULL and returns Substitute – expression if it is null. If expression is not null returns the Original expression value.

Roll – Up Summary Field:

A read only field that displays the sum, minimum, or maximum value of a field in a related list or the record count of all records listed in a related list.
• This is only enabling for Masher Detail Relationship that to for Master object.
Master Object:
Example: There are two Objects X an Y.
And we must have Master- Details Relationship between X and Y in order to create the Roll – up summary Field.
Suppose let’s take X – Master
Y – Child
• The Roll – up summary data types will be enabling on only X (Master) object. This is because we can create Roll – up summary field on Master – Object.
• We need to select summarized object (Child Object)
• There is an option to include all records in the roll – up or just records that meet Certain Criteria.
• Now, easy way of defining a Roll – up summary field is, it is used to automatically display the summarized values of the related records. This can be a record count of related records or a calculation of the sum, minimum, or maximum value of the related records. (or)
• A field that display the detail object records data.

Steps for Creating a Roll – Up summary field:
Step 1: Choose the Roll – Up Summary field type on any Master Object and click on “Next” button
Step 2: Enter a field label and any other attribute. Click “Next”.
Step 3: Select the object on the detail side of a Master – Detail relationship. This object contains the records we want to summarize.
• After that select the Roll – Up type.
This roll up type determines the calculation to be performed on the child records and the field of the child object to perform it on.
Types of Roll – Up type:
COUNT: This function gives the total number of related records.
SUM: This function displays the total values in the field we select in the field to Aggregate option. Only Number, Currency and percent fields are available.
MIN: This function displays the lowest value of the field we select in the “Filed to Aggregate” option for all directly related records. Only Number, currency, percent, date and date/ time are available.
MAX:
This function displays the highest value of the highest value of the field we select in the fields to Aggregate option for all directly related records. Only number, currency, percent, date, and data/ time fields are available.
• Enter filter Criteria if we want a selected group of records in summary calculation.
• Click on “Next”.
Step 4:
Set the Field – level Security to determine whether the field should be visible for specific profiles and click “Next”.
Step 5: Choose the page Layouts that display the field. This field is added as the last field in the first two column section on the page Layout.
• Click “Save” to finish or “Save & New” to create more Custom fields.
Note:
Roll up Summary fields will not be visible on Edit page but it will be displayed on Detail page because it is read – only field.
Example for Roll – Up Summary field:
• Create the Object called “Trainings”.
• Create the Object called “ Students”
• Create a “Master – Detail” Relationship on the Students object and related to Trainings.
• After Creation of all above, the students are the related list of Trainings. (For 1 training record, we can create many students)
• Create the “Student Fee” Field on the student object with a data type called “Currency”.
• Now create a roll – up summary field on the Training object.
Steps to be followed:
Step 1:
Select the “Roll –Up Summary” data type.
Step 2:
Enter the Field Label as “Total number of Students”
Step 3:
Select the function “Count” and summarized Object as “Students” and Click on “Next”.
Step 4: Establish field – level Security.
Step 5: Add to page Layouts.
Result:
In the Trainings detail page, the total count of students will get it on “Total number of students” field and it is read only.
Diagram: 5
• Create a Roll up Summary field on the trainings object with a Summarized object as “Students” and function “Sum”.
And select “Student Fee” as field to aggregate.
(Result: The sum of student fee of all the Students for that training will display on Training’s details page = 22000)
• Create a Roll up summary field on the trainings object as above and select the function called “Max”.
(Result: The Maximum Fee among all the Students for that training will display on Training’s detail page.
= 7000
• Create a Roll Up summary field called “Minimum Fee” on the trainings Object as above and select the function called “MIN”.
(Result: The minimum fee among all the students for training will display in “Minimum Fee” field on Training’s detail page
= 4000
Dependent Pick Lists:
• The value chosen in the controlling field affects the values available in the dependent field.
• A dependent field works in conjunction with a controlling field to filter its values.
• Custom pick list fields can be controlling or dependent.
• Standard pick lists fields can only be controlling.
• We can set default value for controlling field but not for dependent pick lists.
• Multi Select pick lists can be dependent pick list but not controlling field.
• Make sure controlling field exist on any page layout that contains their associated dependent pick list, when the controlling field is not on the same page layout, the dependent pick list shows no available values.
If a dependent pick list is required and no values are available for it based on the controlling field value, users can save the record without entering a value. The record is saved with no value for that field.
• The maximum number of values allowed in a Controlling field is 300.
• Field Level Security settings for a Controlling field and dependent pick list are completely dependent. Remember to hide controlling fields when ever its correcting dependent pick lists is hidden.
Path for creating a dependent pick lists:
For Standard Objects, Click Your Name: Setup: Customize: Select the appropriate Object: Click on “Fields”: Go to Custom fields & Relationships and click on “Field Dependencies”.
Click on New Button: Select Controlling Field and Dependent field and click on “Continue” button
For Custom Objects, Click Your Name:
Setup: Create: Objects: select one of the customs Object
Go to “Custom fields” & Relationships and click on Field Dependencies button.
Example:
• Create the pick list field called University. With the following values on Account Object.
OU
JNTU
KU
Nagarjuna
• Create the pick list field called “College” with the following values on Account Object.
• CBIT, VASAVI, Deccan, MGIT, JBIT, SSIT, VBIT, SRT, Vivekananda Eng.College, SVS.
• Now, create the dependent pick list between “University” and “College”.
University – Controlling field
College – Dependent Field.
If we select OU, Then only few values (CBIT, VASAVI MGIT) we can select from dependent field.

OU JNTU KU Nagarjuna
CBIT JBIT SRT SVS
VASAVI SSIT VGC
MGIT VBIT

• Here we can the default value for “University” pick list field but not for “College” pick list field.
• The maximum number of values allowed in a Controlling field (University) is 300.
Page Layouts:
1. Page Layouts determines how detail and edit pages are organized (Field Locations)
2. Page Section Customizations.
3. And which fields, related lists and custom links are in a users view.
* A Page Layout Controls the position and organization of the fields and related lists that are visible to users when viewing a record.
* Page Layouts also help us control the visibility and edit ability of the fields on a record.
* We can set fields as read- only or hidden, and we can also control which fields require users to enter a value and which don’t.
* Page Layouts should never be used to restrict access to sensitive data that a user shouldn’t view or edit. Although we can hide a field from a page Layouts, users can still access that field through parts of the App, such as in Reports or via the API.
* Control the standard and custom buttons display on detail pages and related lists.
Creating a Page Layout:
To create a new page layout or modify a page layout, follow the path, Your Name: Set up: App Set up: Customize, select the appropriate object and click page layouts.
(In the page layouts page, click on “New” button and
Give the existing page Layout to clone (optional)
Type a name for the new layout: Click “Save”
• The following path is used to modifying a page Layout: Click on the Page Layouts: Click on “Edit” Link
• In the page Layout Editor,
SAVE: button is used to save the page Layout after changes made (Return page is page layout page) Quick Save: button is used to the save the page layout after Changes made.
(Return page is same page)
SAVE AS: This is used to cloning the page Layout.
Layout Properties: Used for changing the name of the page Layout.
Customizing Related Lists:
The customizing related lists includes the Customizing buttons, Columns displayed, column order, and record sort order of related lists on record detail pages in Sales force.
• Double Click a related list on the layout to edit it. To Customize the fields that display in related list;
1. Select one or more fields and use the arrows to add or remove the fields to the related list columns on the page layout, and to define the order in which the related list columns display. We can include up to 10 fields per related list.
2. Select the field from the Sort By drop- down list to sort the items in the related list, which will be displayed in ascending order unless we select Descending.
3. Look up fields are not available for display on their corresponding related list. For example, the case look up field on an account page layout is not available when editing the case related list.
4. To Customized which standard buttons display in the related list, select or de select the check box next to any standard button name.
5. To Customize which custom buttons display in related list:
• To add or remove a custom button, select the button and click Add or Remove.
• Sort Custom buttons by selecting them and clicking up or down.
Record Types:
Record Types allows us to provide different set of Object pick lists, different page layout and custom business Processes to specific users based on their profile.
For example:
1. Create record types for Opportunities to differentiate internal sales deals from field sales deals and show different fields and pick list values.
2. Create record types for leads to display different page layouts for tele – sales leads versus internal sales prospecting functions.
3. The Record type called Master is always set for every object and it is not listed under the record types list and it can be assigned as a record type for a profile; provide it is the only assigned record type for that profile.
Creating Record Types:
To create record types on a standard object.
Click Your Name: Set up: Customize: then select an Object: Click Record Types. (Click “New” Button)
Step1: Enter the details.
• Choose Master from the Existing Record type drop down list to copy all available pick list values, or choose an existing record type to clone its pick list values.
• Enter a Record Type Label that’s unique within the Object.
• Enter a Record Type Name, this name can contain only underscores and alphanumeric characters, and must be unique in organization.
• For opportunity case, Lead and solution record Types; select a business process to associate with a record type.
• Enter a description.
• Select Active Check box to activate the record type.
• Select “Enable for profile” next to a profile to make the record types available to users with that profile. Select the check box in the header row to enable it for all profiles.
• Select “Make Default” to make it the default record type for users of that profile. Select the check box in the header row to make it the default for all profiles.
• Click “Next” button
Step 2:
In this step2, choose a page layout option to determine what page layout display for records with this record type.
• To apply a single page layout for all profiles select “Apply one layout to all profiles” and choose the page layout from the drop down list.
• To apply different page layouts based on user profile, select “apply a different layout for each profile” and choose a page layout for each profile.
• Click “Save” button to edit the values of the standard and custom pick lists available for the record type.
• Click “Save and New” to create another record type.
Editing pick lists for Record Types:
To customize the values in record types pick lists.
1. Select the record type and click “Edit” next to one of the pick list fields to customize the values included for the record type.
2. Add any value from the Available values box or remove any values from the selected values box. Users will be able to choose from the list of selected values when creating and editing records.
3. Optionally, choose a default pick list value.
4. Click “Save” Button.

Assigning Record Types to profiles:
• After creating record types and including pick list values, add record types to user profiles and assign a default record type for each profile. When we add a record type to a profile users with that can assign that record type to records they create or edit.
Procedure:
1. Click Your Name: Setup: Manage Users: Profiles.
2. Select a profile. The Record Types available for that profile are listed in the Record Type settings section.
3. Click “Edit” next to the appropriate type of record.
4. Select a record type from the available record Types list and add if to the selected Record Types list and make it available to users with that profile.
“Master” is a System – generated record type that’s used when a record has no Custom record type associated with it. When “Master” is assigned, user’s can’t set a record type to a record, such as during record creation.
5. From the “Default” drop – down list, choose a default record type.
6. Click “Save” Button.
Page Layout Assignment:
The following procedure gives the information about the assigning page layouts from a Customize page layout or Record Type Page.
1. Click Your Name: Set Up : Customize: Select the appropriate object: Click on Page Layouts or Record Types.
2. In the page Layout or record page type list page click Page Layout Assignment.
3. Click “ Edit Assignment”
4. When Selecting Page Layout Assignments.
• Click a cell, column or row heading to select all the table cells in that column or row.
• Press SHIFT + Click to select multiple adjacent table cells, columns, or rows.
• Click any cell and drag to select a range of cells.
• Click “Next” or “Prev” to view another set of record types.
5. Select the page layout Assignments are highlighted. Page Layout Assignments we change are italicized until we save our changes.
6. If necessary, select another page layout to assign from the “Page Layout to Use” drop-down list and repeat the previous step for the new page layout.
7. Click “Save” button.

 

  1. Number:

Allows users to enter any number. Leading zeros are removed.

We can enter up to 18 digits.

14 digits for integer place and 4 digits for decimal place.

Example:

123456 ….. 14 digits .6789

(14 digits)                   (4 digits)

 

 

  1. Percent:

Allows users to enter a percentage number.

Example: If we enter “50” as a field Value, it automatically adds the percent sign to the number (50%)

 

  1. Phone:

Allows users to enter any phone number. Automatically formats it as (905) 275 – 7414

 

  1. Pick List:

Allows users to select a value from a list we define.

  • The maximum length of the text values is 40 Characters,
  • We can give max of 300 pick list values.

 

  1. Pick List (Multi – Select):

The pick list (multi – select) field allows users to choose more than one pick list value from a set of pre-defined text values.

  • The maximum length of the text values is 40 characters.
  • After saving a record, the data is stored as text along with semi- colons which are used to separate the individual pick list values.
  1. Text:

The Text field allows entering any combination of alphanumeric characters.

Or

Allows users to enter any combination of letters and numbers.

  • The maximum length of the text value is 255 Characters.
  1. Text Area:

The Text Area field allows users to enter alpha numeric Characters on separate lines.

 

  • The maximum length of text area value is 255 Characters on the separate lines.
  1. Text Area (Long):

The Text Area (Long) provides for the storage of up to 32, 768 Characters that display on separate lines similar to a text Area field.

  • This data type is not available for activities or products on opportunities.
  • Every time we press Enter with in a long text area field, a line break, and a return character are added to the text. These two character count towards the 32, 768 Character limit.
  1. Text Area (Rich):

The Text Area (Rich) data type allows the users to enter a text value with formatted and add images and links up to 32, 768 Characters we can enter on separate lines.

  • Also allows the users to undo, redo, bold, italicize, underline, strike- out, upload or link to an image.
  • The maximum size for uploaded image is 1MB and only GIF, JPEG and PNG file types are supported.

 

 

  1. Text (Encrypted):
  • Allows users to enter any combination of letters and numbers and store them in encrypted form.
  • The maximum length of the text value is 255 characters.
  • For encrypted text, we can set a maximum length of up to 175 Characters.
  1. URL:

Allows users to enter any valid website address.

When users click on the field value in the detail page, the URL will open in a separate browser window to show the web page.

  • The URL field can store up to 255 characters. However, only the first 50 characters are displayed on the record detail pages.

 

Step 2:

Enter the details.

  1. Give the Field Label with meaningful name, once we click Tab, then Field Name will be automatically pop up from the label. It is used to refer the field in Apex code, formula fields, and validation rules.
  • Force.com appends the field Name with “__C” to differentiate it from standard fields.
  • It’s good practice to give a description for the field which describes about the purpose of using that field.

Help Text:

It is possible to add field level help to a custom field to provide information to users on how to use that field.

If we provide a help text for field help text will be displayed once the mouse moves the icon containing the letter “i”.

Step 3:

Establish field – level Security

  • Select the profiles to which we want to grant edit access to this field via field – level security. The field will be hidden from all profiles if we do not add it to field level security.

Step 4:

Add to page Layouts

  • Select the page layouts that should include this field. The field will be added as the last field in the first 2 – column section of these page layouts.
  • The field will not appear on any pages if we do not select a layout.
  • To change the location of the field on the page, we will need to customize the page layout.
  • Click on “Save” button to create a field successfully.
  • Click on “Save & New” button to create more custom fields.

Important Points about Custom Fields:

  • Changing the data type of existing custom fields is possible but doing so may. Cause data loss.
  • Deleting a custom field removes both the data and the field.
  • Custom fields are stored for 45 days after deletion.
  • Changing the data type of existing custom field can cause data loss in the following situations.
  1. Changing to or from Date or Date/ Time.
  2. Changing to Number from any other type.
  3. Changing to Percent from any other type.
  4. Changing to Currency from any other type.
  5. Changing from Pick list (Multi – Select) from any type except pick list.
  6. Changing from Auto Numbers to any other type.
  7. Changing to Auto Number from any type except Text
  8. Changing from Text Area (Long) to any type except Email, phone, Text, Text Area, or URL.
  • If data is Lost, any list view based on the Custom field will be deleted, and assignment and escalation rules may be affected.

Object Relationships:

Object relationships can be set on both standard and custom objects and are used to define how records in one object relate to records in another Object.

Example: Accounts can have a one- to – many relationships with opportunities and these relationships are presented in the application as related lists.

  • Sales force provides the following types of relationships.

1)      Look up Relationship

2)      Master – Detail Relationship

3)      Many- to – Many Relationship

4)      Hierarchical Relationship

 

 

 

 

 

 

 

The differences between the Lookup and Master – detail relationships are:

Lookup RelationshipMaster – Detail Relationship
  1. We can create 25 look up relationships for both standard and custom objects.
1. We can create 2 Master Detail relationships for Custom Objects.
  1. Look up relationship can be created if records already exist.
2.Master detail relationship can’t be created if records already exists
  1. If we deletes the parent record, then Childs will not deleted
3.  If we delete the parent record, then Childs will be deleted automatically.
  1. Optional
4.Mandatory
  1. The Ownership and the sharing of a child record are not determined by the parent record.
5. The ownership and the sharing of a detail record are determined by the Master record.

 

Steps to test Lookup Relationship:

  • Create a field with the data type as lookup Relationship on Account Object.
  • Related to solutions (acts as a parent Object)
  • After completing all the steps, the Accounts are the related list to solutions.
  • Here we can create this relationship if account records already exist.
  • Now, delete the solution record then check the accounts associated with the solution.
  • Result will be the account records will not delete.

Steps to test Master- Detail Relationship:

Note: We can create M- D relationship on the custom Objects only. We cannot create on standard Objects.

  1. Create a field with the data types as Master – Detail on any Custom Object

(Ex: Customer)

  1. Give related to cases (Cases will act as Master Object)
  2. This field will not be create when Customer records exists.
  3. After creating the field, the customers are the related list of cases.
  4. Create a one case record, and also create Customer records for that case.
  5. Delete the case record, then check whether the customer’s record is deleted or not.

(Result will be Customer records will be deleted automatically)

Many – to – Many Relationships:

A many – to – many relationship allows each record of one Object to be linked to multiple records from another Object and Vice – Versa.

  • When modelling a many – to – many relationships, we use a “Junction Object” to connect the two objects we want to relate to each other.

Junction Object:

A Custom object with two masters – detail relationships. Using a custom junction object, we can model a Many – to – Many relationship between two objects.

Diagram: 4

Example:

  1. Create a custom Object called “Bug Case Association” ( Use the auto Number data type)
  2. For above custom object, create two master-detail relationships.
  3. While creating one master- details relationship chooses related to as “Case”.
  4. While Creating Second master-details relationship, choose related to as “Bug” (Custom Object)
  5. While Creating “Bug Case Association” record, there we have to select values for two master- detail fields. From this we say that, we are creating a many – to – many relationships between the “case” and “Bug” through the Junction Object called “Bug Case Associations” custom Object.

Hierarchical Relationship:

Allow users to click a lookup icon and select another user from a pop-up-list.

  • This type of relationship is a special lookup relationship available only for the user Object. It allows developers to create a Manager Field on the user Object to relate another user.
  • This relationship will acts as a self relationships.

Example: If we want to link a custom Object called “Bug” with itself to how two different bugs are related to the same problem.

Formula Fields:

  • A read- only field that derives its value from a formula expression we define. The formula is updated when any of the source fields change.
  • Supported on standard and custom Objects.
  • Can reference standard, custom or other formula fields.
  • Can reference (These reference fields are called merge) fields on related objects.
  • Number of characters we can enter is 3900 (Space will to one Character)
  • The formula compile capacity is 4000 characters.

Building Formulas:

Consider the following steps to create a formula field.

  1. Choose the formula data type
  2. Choose the data type for the formula based on the output of the calculation.
  • Enter the number of decimal places for currency amount and automatically format the fields as a currency amount.

Date: Calculate a date.

Date/ Time: Calculate a date/time, for example, by adding a number of hours or days to another data/time.

Number: Calculate a numeric value.

Percent: Calculate a percent and automatically add the percent sign to the number.

Text: Create a text String, for example, by concatenating other text fields.

iii) Click “Next” to display the formula creation screen.

 

Basic formula:

Select the simple Formula tab, choose the field type in the select Field Type drop- down list, and choose one of the fields listed in the insert field drop – down list.

To insert an operator, choose the appropriate operator icon from the “Insert operator” drop down list.

Advanced Formula:

The basic formula feature is quite restricted and we can create more complicated formulas by selecting the advanced formula tab.

Within this tab, click on “insert field”, choose a field, and then click on “insert”.

Click check syntax to check our formula for errors.

  • Formula fields:

1)      Date & Time Functions:

Date (YYYY, MM, DD): used to display Date in month, Day, year format.

Date value: used to display the date on screen the input can be expression or text.

Date / Time: used to display Date/ Time stamp on the screen and the input can be field, expression, text.

Day: Extracts day from date field

Month: Extracts month from date field

Year: Extracts year from date field

Today(): will display present date.

Now(): it will display present date with time.

  1. Text functions:

Begins:

Syntax: Begins (text, Compare- text)

Checks it text begins with specified character an returns True if it matches otherwise returns

 

Contains:

Syntax: Contains (text, compare-text)

Checks it text contains specified characters, and returns TRUE if it does, otherwise, returns FALSE

Find:

Syntax: find (search-text, [Start-num])

Returns the position of the Search- text String in text.

Includes:

Syntax: includes ( multiselect_picklist_field, text_literal)

Determines if any value selected in a multi –select pick list field equals a text literal you specify.

 

 

Is PICK VAL:

Syntax:  isPICKval (picklist_field, text_literal)

Checks whether the value of a pick list field is equal to a String literal.

 

LEFT:

Syntax: LEFT (Text, number-chars)

Returns the specified number of characters from the start of a string from left side.

 

RIGHT:

Syntax: RIGHT (text, number-chars)

Returns the specified number of characters from the start of string from right side

MID:

Syntax: MID (text, start_num, num_chars)

Returns the characters from the middle of a text string mentioned number of characters from the starting position

LEN:

Syntax: LEN (text)

Returns the number of characters in a text String.

 

LOWER:

Syntax: LOWER (text)

Converts all letters in the value to lower case.

UPPER:

Syntax: UPPER (text)

Converts all letters in the value to upper case.

 

UPAD:

Syntax:  LPAD (text, padding_ length, pad_String)

Pad the left side of the value with spaces or the optional pad String

 

RPAD:

Syntax: RPAD (text, padding_length, pad_String)

Pad the right side of the value with spaces or the optional pad String.

 

Substitute:

Syntax: Substitute (text, old-text, new-text)

Substitute new-text for old- text in a text String.

Text:

Syntax: Text (Value)

Converts a value to text using standard display format.

 

TRIM:

Syntax: TRIM (text)

Removes all spaces from a text sting expect for single spaces between words.

Math Functions:

ABS:

Syntax: ABS (number)

Returns the Absolute value of a number, a number without sign.

CEILING:

Syntax: CEILING (number)

Rounds a number to the nearest integer

 

EXP:

Syntax:  Exp (number)

Returns ‘E’ raised to the power of a given number.

FLOOR:

Syntax: FLOOR (number)

Rounds a number down, towards zero to the nearest integer

isBlank:

Syntax: is blank (Expression)

Checks whether an Expression is blank and returns TRUE or FALSE

LN:

Syntax: LN (Number)

Returns the natural logarithm of a number

LOG:

Syntax: LOG (number)

Returns the base 10 log of ‘n’

Max:

Max (num1, num2 , num3 …. )

Returns the greatest of all numbers

MIN:

Min (num1, num2, num3… )

Returns the least of all numbers

Round:

Syntax: Round (number, num_digits)

Rounds a number to a specified number of digital

 

SQRT:

Syntax: SQRT (number)

Returns the positive square root of a number.

 

Logical Functions:

AND:

Syntax: AND (logic1, logic2 …)

It all logics are true it will return true otherwise returns false.

 

OR:

Syntax:

OR(logic1, logic2…)

If anyone logic is true it will return true, if all logics are false it will return false.

 

CASE:

Syntax: CASE (Expression, value1, result1, value2, result2, value3, result3 else result)

Checks an expression against a series of values it the expression compares equal to any value, the corresponding result is returned. If it is not email to any of the values, the else result is returned.

 

If:

Syntax: IF (logical-test, value-if-true, value-if-false) checks whether a condition is true, returns one value if true and anther value false.

ISNULL:

Syntax: ISNULL (Expression)

Checks whether an expression is null and returns TRUE (or) FALSE.

 

ISNUMBER:

Syntax: ISNUMBER (Text)

Returns TRUE it the text value is a number. Otherwise it returns false.

 

NOT:

Syntax: NOT (logical)

Changes false to TRUE or TRUE to false

 

NULL VALUE:

Syntax: null value (expression, substitute Expression)

Checks whether expression IS NULL and returns Substitute – expression if it is null. If expression is not null returns the Original expression value.

 

Roll – Up Summary Field:

 

A read only field that displays the sum, minimum, or maximum value of a field in a related list or the record count of all records listed in a related list.

  • This is only enabling for Masher Detail Relationship that to for Master object.

Master Object:

Example: There are two Objects X an Y.

And we must have Master- Details Relationship between X and Y in order to create the Roll – up summary Field.

Suppose let’s take           X – Master

Y – Child

  • The Roll – up summary data types will be enabling on only X (Master) object. This is because we can create Roll – up summary field on Master – Object.
  • We need to select summarized object (Child Object)
  • There is an option to include all records in the roll – up or just records that meet Certain Criteria.
  • Now, easy way of defining a Roll – up summary field is, it is used to automatically display the summarized values of the related records. This can be a record count of related records or a calculation of the sum, minimum, or maximum value of the related records. (or)
  • A field that display the detail object records data.

 

Steps for Creating a Roll – Up summary field:

Step 1: Choose the Roll – Up Summary field type on any Master Object and click on “Next” button

Step 2: Enter a field label and any other attribute. Click “Next”.

Step 3: Select the object on the detail side of a Master – Detail relationship. This object contains the records we want to summarize.

  • After that select the Roll – Up type.

This roll up type determines the calculation to be performed on the child records and the field of the child object to perform it on.

Types of Roll – Up type:

COUNT: This function gives the total number of related records.

SUM: This function displays the total values in the field we select in the field to Aggregate option. Only Number, Currency and percent fields are available.

MIN: This function displays the lowest value of the field we select in the “Filed to Aggregate” option for all directly related records. Only Number, currency, percent, date and date/ time are available.

MAX:

This function displays the highest value of the highest value of the field we select in the fields to Aggregate option for all directly related records. Only number, currency, percent, date, and data/ time fields are available.

  • Enter filter Criteria if we want a selected group of records in summary calculation.
  • Click on “Next”.

Step 4:

Set the Field – level Security to determine whether the field should be visible for specific profiles and click “Next”.

Step 5: Choose the page Layouts that display the field. This field is added as the last field in the first two column section on the page Layout.

  • Click “Save” to finish or “Save & New” to create more Custom fields.

Note:

Roll up Summary fields will not be visible on Edit page but it will be displayed on Detail page because it is read – only field.

Example for Roll – Up Summary field:

  • Create the Object called “Trainings”.
  • Create the Object called “ Students”
  • Create a “Master – Detail” Relationship on the Students object and related to Trainings.
  • After Creation of all above, the students are the related list of Trainings. (For 1 training record, we can create many students)
  • Create the “Student Fee” Field on the student object with a data type called “Currency”.
  • Now create a roll – up summary field on the Training object.

Steps to be followed:

Step 1:

Select the “Roll –Up Summary” data type.

Step 2:

Enter the Field Label as “Total number of Students”

Step 3:

Select the function “Count” and summarized Object as “Students” and Click on “Next”.

Step 4: Establish field – level Security.

Step 5: Add to page Layouts.

Result:

In the Trainings detail page, the total count of students will get it on “Total number of students” field and it is read only.

Diagram: 5

  • Create a Roll up Summary field on the trainings object with a Summarized object as “Students” and function “Sum”.

And select “Student Fee” as field to aggregate.

(Result: The sum of student fee of all the Students for that training will display on Training’s details page = 22000)

  • Create a Roll up summary field on the trainings object as above and select the function called “Max”.

(Result: The Maximum Fee among all the Students for that training will display on Training’s detail page.

= 7000

  • Create a Roll Up summary field called “Minimum Fee” on the trainings Object as above and select the function called “MIN”.

(Result: The minimum fee among all the students for training will display in “Minimum Fee” field on Training’s detail page

= 4000

Dependent Pick Lists:

  • The value chosen in the controlling field affects the values available in the dependent field.
  • A dependent field works in conjunction with a controlling field to filter its values.
  • Custom pick list fields can be controlling or dependent.
  • Standard pick lists fields can only be controlling.
  • We can set default value for controlling field but not for dependent pick lists.
  • Multi Select pick lists can be dependent pick list but not controlling field.
  • Make sure controlling field exist on any page layout that contains their associated dependent pick list, when the controlling field is not on the same page layout, the dependent pick list shows no available values.

If a dependent pick list is required and no values are available for it based on the controlling field value, users can save the record without entering a value. The record is saved with no value for that field.

  • The maximum number of values allowed in a Controlling field is 300.
  • Field Level Security settings for a Controlling field and dependent pick list are completely dependent. Remember to hide controlling fields when ever its correcting dependent pick lists is hidden.

Path for creating a dependent pick lists:

For Standard Objects, Click Your Name: Setup: Customize: Select the appropriate Object: Click on “Fields”: Go to Custom fields & Relationships and click on “Field Dependencies”.

Click on New Button: Select Controlling Field and Dependent field and click on “Continue” button

For Custom Objects, Click Your Name:

Setup: Create: Objects: select one of the customs Object

Go to “Custom fields” & Relationships and click on Field Dependencies button.

Example:

  • Create the pick list field called University. With the following values on Account Object.

OU

JNTU

KU

Nagarjuna

  • Create the pick list field called “College” with the following values on Account Object.
  • CBIT, VASAVI, Deccan, MGIT, JBIT, SSIT, VBIT, SRT, Vivekananda Eng.College, SVS.
  • Now, create the dependent pick list between “University” and “College”.

University – Controlling field

College – Dependent Field.

If we select OU, Then only few values (CBIT, VASAVI MGIT) we can select from dependent field.

 

OU                            JNTU                 KU                         Nagarjuna

CBIT                          JBIT                    SRT                         SVS

VASAVI                   SSIT                    VGC

MGIT                        VBIT

 

  • Here we can the default value for “University” pick list field but not for “College” pick list field.
  • The maximum number of values allowed in a Controlling field (University) is 300.

Page Layouts:

1. Page Layouts determines how detail and edit pages are organized (Field Locations)

2. Page Section Customizations.

3. And which fields, related lists and custom links are in a users view.

* A Page Layout Controls the position and organization of the fields and related lists that are visible to users when viewing a record.

* Page Layouts also help us control the visibility and edit ability of the fields on a record.

* We can set fields as read- only or hidden, and we can also control which fields require users to enter a value and which don’t.

* Page Layouts should never be used to restrict access to sensitive data that a user shouldn’t view or edit. Although we can hide a field from a page Layouts, users can still access that field through parts of the  App, such as in Reports or via the API.

* Control the standard and custom buttons display on detail pages and related lists.

Creating a Page Layout:

To create a new page layout or modify a page layout, follow the path, Your Name: Set up: App Set up: Customize, select the appropriate object and click page layouts.

(In the page layouts page, click on “New” button and

Give the existing page Layout to clone (optional)

Type a name for the new layout: Click “Save”

  • The following path is used to modifying a page Layout: Click on the Page Layouts: Click on “Edit” Link
  • In the page Layout Editor,

SAVE: button is used to save the page Layout after changes made (Return page is page layout page) Quick Save: button is used to the save the page layout after Changes made.

(Return page is same page)

SAVE AS: This is used to cloning the page Layout.

Layout Properties: Used for changing the name of the page Layout.

Customizing Related Lists:

The customizing related lists includes the Customizing buttons, Columns displayed, column order, and record sort order of related lists on record detail pages in Sales force.

  • Double Click a related list on the layout to edit it. To Customize the fields that display in related list;
  1. Select one or more fields and use the arrows to add or remove the fields to the related list columns on the page layout, and to define the order in which the related list columns display.  We can include up to 10 fields per related list.
  2. Select the field from the Sort By drop- down list to sort the items in the related list, which will be displayed in ascending order unless we select Descending.
  3. Look up fields are not available for display on their corresponding related list. For example, the case look up field on an account page layout is not available when editing the case related list.
  4. To Customized which standard buttons display in the related list, select or de select the check box next to any standard button name.
  5. To Customize which custom buttons display in related list:
  • To add or remove a custom button, select the button and click Add or Remove.
  • Sort Custom buttons by selecting them and clicking up or down.

Record Types:

Record Types allows us to provide different set of Object pick lists, different page layout and custom business Processes to specific users based on their profile.

For example:

  1. Create record types for Opportunities to differentiate internal sales deals from field sales deals and show different fields and pick list values.
  2. Create record types for leads to display different page layouts for tele – sales leads versus internal sales prospecting functions.
  3. The Record type called Master is always set for every object and it is not listed under the record types list and it can be assigned as a record type for a profile; provide it is the only assigned record type for that profile.

Creating Record Types:

To create record types on a standard object.

Click Your Name: Set up: Customize: then select an Object: Click Record Types. (Click “New” Button)

Step1: Enter the details.

  • Choose Master from the Existing Record type drop down list to copy all available pick list values, or choose an existing record type to clone its pick list values.
  • Enter a Record Type Label that’s unique within the Object.
  • Enter a Record Type Name, this name can contain only underscores and alphanumeric characters, and must be unique in organization.
  • For opportunity case, Lead and solution record Types; select a business process to associate with a record type.
  • Enter a description.
  • Select Active Check box to activate the record type.
  • Select “Enable for profile” next to a profile to make the record types available to users with that profile. Select the check box in the header row to enable it for all profiles.
  • Select “Make Default” to make it the default record type for users of that profile. Select the check box in the header row to make it the default for all profiles.
  • Click “Next” button

Step 2:

In this step2, choose a page layout option to determine what page layout display for records with this record type.

  • To apply a single page layout for all profiles select “Apply one layout to all profiles” and choose the page layout from the drop down list.
  • To apply different page layouts based on user profile, select “apply a different layout for each profile” and choose a page layout for each profile.
  • Click “Save” button to edit the values of the standard and custom pick lists available for the record type.
  • Click “Save and New” to create another record type.

Editing pick lists for Record Types:

To customize the values in record types pick lists.

  1. Select the record type and click “Edit” next to one of the pick list fields to customize the values included for the record type.
  2. Add any value from the Available values box or remove any values from the selected values box. Users will be able to choose from the list of selected values when creating and editing records.
  3. Optionally, choose a default pick list value.
  4. Click “Save” Button.

 

Assigning Record Types to profiles:

  • After creating record types and including pick list values, add record types to user profiles and assign a default record type for each profile. When we add a record type to a profile users with that can assign that record type to records they create or edit.

Procedure:

  1. Click Your Name: Setup: Manage Users: Profiles.
  2. Select a profile. The Record Types available for that profile are listed in the Record Type settings section.
  3. Click “Edit” next to the appropriate type of record.
  4. Select a record type from the available record Types list and add if to the selected Record Types list and make it available to users with that profile.

“Master” is a System – generated record type that’s used when a record has no Custom record type associated with it. When “Master” is assigned, user’s can’t set a record type to a record, such as during record creation.

  1. From the “Default” drop – down list, choose a default record type.
  2. Click “Save” Button.

Page Layout Assignment:

The following procedure gives the information about the assigning page layouts from a Customize page layout or Record Type Page.

  1. Click Your Name: Set Up : Customize: Select the appropriate object: Click on Page Layouts or Record Types.
  2. In the page Layout or record page type list page click Page Layout Assignment.
  3. Click “ Edit Assignment”
  4. When Selecting Page Layout Assignments.
  • Click a cell, column or row heading to select all the table cells in that column or row.
  • Press SHIFT + Click to select multiple adjacent table cells, columns, or rows.
  • Click any cell and drag to select a range of cells.
  • Click “Next” or “Prev” to view another set of record types.
  1. Select the page layout Assignments are highlighted. Page Layout Assignments we change are italicized until we save our changes.
  2. If necessary, select another page layout to assign from the “Page Layout to Use” drop-down list and repeat the previous step for the new page layout.
  3. Click “Save” button.

 

 

Security Controls:

Record Ownership:

  • The user (or queue for cases and Leads) who controls or has rights to that particular data record.

There are two types of Owners:

  • Users
  • Queues
  • Most records have an associated owner. An owner has the following special privileges:

 

  • View and edit capabilities

 

  • Transfer Capability:

 

  • Change Ownership

 

  • Deletion Capabilities

 

(Record Owners have Full Access)

Import Assumption: object permission enabled.

  • It is possible for a user to own a record and not see it if they don’t have the “Read” permission on the object.
  • Security Controls-

Organization Wide Defaults

Sharing Settings

Role Hierarchy

Organization Wide Defaults:

The following is the path for setting organization- wide Defaults:

Click Your Name: Setup: Security Controls: Sharing Settings: Click Edit in the Organization wide Defaults area: Select the access for each object.

  • Organization wide defaults defines the base line level of access to data records for all users in the Organization.
  • Organization wide defaults are used to restrict access to data.
  • OWD’s can be defined for the custom as well as several standard objects.
  • OWD access Level  actions:

The organization – wide default (OWD) access levels allows the following actions to be applied to object records.

  1. Access Level: public Full Access (Option for setting the campaign Object only)

Actions:

Change Ownership of record

Search Records

Report on records

Add related records

Edit details of record

Delete record

Access levels for the campaign OWD’s can be set to private, Public Read only, Public Read/ Write , or public Full Access. When campaigns are set to public Full access, all users can view, edit, transfer, delete, and report on all campaign records.

Example Anil Reddy is the owner of a campaign all other users in the application can view, edit, transfer, or delete that campaign

  1. Access Level: Read/ Write/ Transfer:

(Option for setting the lead and case objects only)

An user have following privileges for above access level:

Change ownership of record.

Search records

Report on records

Add related records

Edit details of record

  1. Access Level: Read/ Write

An user have following privileges for this access level

* Search records

* Report on records

*Add related records

* Edit details of record

Note1:

Access Level: public read/write/ Transfer

Access levels for case or lead OWD’s can be set to private, public Read only, public Read/ Write, or Public Read /Write/ Transfer. We case or leads are set to public Read/Write/ Transfer, all users can view, edit, transfer, and report on all case or load records.

Example: If Andy is the owner of case number XXX, all other users can view, edit , transfer ownership and report on that case But only Andy can delete or change the sharing on  case XXX.

The above option is available on cases or leads only.

Note: 2

Access Level: public Read/ Write

(All users can view, edit, and report on all records)

Example: If Sourabh is the owner of account record “Osmania Uni.”, all other users can view, edit and report on “Osmania Uni” account.

However only Sourabh has the ability to delete the “Osmania Uni” account record or alter the sharing settings.

4         Access Level: Public Read only

The following privileges, the user will get with Public Read only access level:

  • Search records
  • Report on records
  • Add related records
  • All users can view and report on every record but they cannot edit them. Here, only the record owner and user’s above that users role in the role hierarchy can edit the records.

Example: Mike is the owner of the Account record “GE TRP” and Mike is in the role international sales, reporting to Julia; who is in the role VP of international sales, in this case, both Mike and Julia have full Read/ Write access to “GE TRP” account.

1)      Access Level: private

Only the record owner, and users above that role in the hierarchy, can view, edit and report on those records.

Example: If Mike is the owner of an account record, and he is assigned to the role of international sales, reporting to Julia who is in the VP of international sales role, then Julia can also view, edit , and report on Mike’s accounts.

2)      Access Level: No Access, view only , or Use:

This option is available only for price Books.

Access levels for the price books OWDs can be set to either No Access, view only or use.

  • Use is the default access level and allows all users to access the Price Book information as well as using the price Book configuration for opportunities with products.
  • View only allows users to access the price Book information but not to use that price Book details in opportunities with products.
  • No access restricts users from accessing information for price Books and Prices.

Grant Access using Hierarchies:

By default, slaesforce uses role hierarchy, to automatically grant record access to users above the record owner in the hierarchy.

This automatic granting of access to users data to other users higher up in the hierarchy can be disabled for custom objects using the “Grant Access using Hierarchies” Check box.

When this check box is not selected, only the record owner and users granted access by the organization wide defaults will get the access to the records.

Note: The option “Grant Access Using Hierarchies” is automatically checked for standard objects. We cannot change this option.

We can able select and deselect this option for custom objects.

Controlled by parent:

When controlled by parent is set on any object a user can perform an action ( such as view, edit, or delete)  on the record based on whether they can perform that same action on the parent record associated it.

Example: if a contact record is associated with the XYZ account using Controlled by Parent, then a user can only edit that contact if they can also edit the XYZ account record.

  • When a custom object is on the detail side of a master detail relationship with a standard object, it’s OWD’s is automatically set to “Controlled by parent” and it is not editable.

i.e., Child records in master- detail relationships inherit their organization wide defaults from their parents.

Note: Child records in lookup relationships have independent organization wide defaults from their parents.

  • Changing organization wide defaults can potentially delete manual sharing if that sharing is no longer needed.

Example: Changing from private to public Read/ Write

Imp Note:

Although “Grant Access Using Hierarchies” can be deselected to prevent users that are higher in the role hierarchy having automatic access, users with the view all and modify all object permissions and the view all and modify all Data profile permissions can still access records they do not own.

i.e., organization wide Defaults does not work if the profile have View All and Modify All permissions for an object.

 

Limitations:

 

  • The organization – wide defaults (OWD) for the solution object in sales force is public Read/ Write which cannot be changed.
  • When a custom object on the detail side of a M-D relationship with a standard object, its OWD’s is set to Controlled by parent and it is not editable.

Introduction to Role Hierarchy:

Once the organization – wide defaults have been established, we can use a role hierarchy to ensure that managers can view and edit the same records as their line reports (sub ordinates). Users at any level are always able to view, edit, and report on all data owned by or shared with users below them in the hierarchy, unless the OWD settings specify ignoring the hierarchies.

Role and Role Hierarchy:

Role:

A Role controls the level of visibility that users have to an organizations data.

  • A user may be associated to one role.

Role Hierarchy:

  • Controls the data Visibility
  • Controls record roll up for reporting
  • Users inherit the special privileges of data owned by or shared with users below them in the hierarchy.
  • With Standard objects, access to records roll up through the role hierarchy.
  • With Custom objects, developers choose whether or not access should roll up through the role hierarchy i.e. determined by the “Grant Access using Hierarchies” setting on Organization wide defaults.

Creating Role Hierarchy:

To view and manage Organization roles,

Click Your Name: Setup: Administration Set up: Manage Users: click on “Roles”.

Choose one of the following list view options.

Show in tree view:

We can see a visual representation of the parent- child relationships between roles. Click “Expand All” to see all roles or “Collapse All” to see only top – level roles. To expand or collapse click the plus (+ ) or minus (-) icon.

Show in sorted list view:

(we can see a list that we can sort aplphabetically by role name parent role (Reports To) , or report display name.)

Show in List View:

We can see a list of roles and their children , the grouped alphabetically by the name of the top- level role. The columns are not sort able. This view is not available for hierarchies with more than 1000 roles.

  • To create a role, click “New Role” or “Add Role”, depending whether we are viewing the list view or tree view of roles.
  • To edit a role, click Edit next to a role name, then update the role as needed.
  • To delete a role, click “Delete” next to the role name.

Assigning Users to Role:

  1. To assign users to a particular role.

Click you’re Name: setup: Manage users: 1. Click on “Roles”.

  1. Click “Assign” next to the name of the desired role
  2. Make a selection from the drop- down list to show the available users.
  3. Select a user on the left, and click “Add” button to assign the user to this role.

Notes:

  1. We can create up to 500 roles for organization.
  2. Every user must be assigned to a role.
  3. All users that require visibility to the entire organization should belong to the highest level 0 in the hierarchy.
  4. When we change a user’s role, any relevant sharing rules are evaluated to add or remove access as necessary.

Sharing Rules:

With sharing rules, we can make automatically exceptions to Organization- wide default settings for defined sets of users.

For Example:

Use sharing rules to extend sharing access to users in public Groups, roles.

  • Sharing rules can never be stricter than Organization- wide default settings. They simply allow greater access for particular users.

Comparison of profiles & the sharing model:

ProfilesSharing Model
  • Controls access to objects

(Example: Accounts, Contacts… Custom objects.. )

  • Controls access to records (Example: one account record (Osmania University), one contact record (Anil Reddy) and custom object records.

 

  • So a users profile might specify that a user can see Accounts, but the sharing model determines which accounts records that user can see.
  • The sharing model might determine that a user can see Anil Reddy record, but profile specifies which fields that user can view and edit.

To access the sharing Rules related list,

Click Your Name: Setup: Administration Setup: Security Controls: Sharing settings then scroll to the sharing Rules related list, From we can

  • Create and edit Lead Sharing Rules.
  • Create and edit Account Sharing rules
  • Create and edit contact sharing rules.
  • Create and edit Opportunity sharing rules
  • Create and edit case sharing rules
  • Create and edit Campaign sharing rules
  • Create and edit Custom object sharing rules.

 

Creating Sharing Rules:

To create sharing Rules for any type of records.

Click Your Name: Set up: Security Controls: Sharing Settings:

  1. Go to any object sharing rules related list and Click on “New” button.
  2. Enter the label and Rule Name
  3. Select the following rule type

Based on record owner: in the owned by line, specify the users whose records will be shared. Select a category from the first drop down list and set of users from the second drop- down list.

Based on Criteria: specify the field, operator and value criteria that records must match to be included in the sharing rule. The fields available depend on the object selected, and  the value is always a literal number or string.

Click “Add Filter Logic” – to change the default AND relationship between each filter.

  1. In the share with line, specify the users who should have access to the data. Select a category from the first drop down list and a set of users from the second drop down list.
  2. Select the level of access for the users

Read only – Users can view, but not update records

Read / Write – users can view and update records.

  1. Click on “Save” button

Important points about sharing Rules:

  • Sharing Rules apply to all new and existing records owned by the specified role or group members.
  • Sharing rules apply to both active and in active users.
  • When we change the access levels for a sharing rule, all existing records are automatically updated to reflect the new access levels.
  • When we delete a sharing rule, the sharing access created by that rule is automatically removed.
  • When we modify which users in a group or role, the sharing rules are re-evaluated to add or remove access as necessary.
  • Managers in the role hierarchy are automatically granted the same access that users below them in the hierarchy have from a sharing rule.
  • We can edit the access levels for any sharing rule we can not change the specified groups or roles for the rule.

Manual Sharing:

  • It is used to open up access to records on a one off basis when it is too difficult to come up with a consistent set of users who need access.
  • Granted by owners, anyone above owners in the role hierarchy and system administrators.
  • Users grant access simply by clicking on the “Sharing” button found on the Record Detail Page.

Note:  The sharing button does not appear if the objects organization- wide sharing defaults are set to public Read/ Write.

Note: What are the ways to obtain Access to a record?

Full AccessRead/Write or Read Only Access
  • Owner field

User

Queue member

  • Organization wide Defaults
  • Above user (who has ownership in role hierarchy)
  • Above user (Who has read/ write or read only access) in role hierarchy
  • Manual sharing
  • Sharing rules
  • Apex Sharing
  • Profile permission: “Modify All Data”
  • Profile permission: “View All Data”
  • Object permission: “Modify All”
  • Object permission: “View All”

 

Customizing Search Layouts:

Search Layouts determines determine Customize which fields display for users in search results, search filter fields; look up dialogs, the recent lists on tab home pages, and in look up phone dialogs.

  • We can specify a different set of fields to show in each search layout. The settings apply to all users in organization.
  • Additionally we can customize which buttons display in custom list views and search results. We can hide standard list view button or display a custom button.
  • Go to the following path to access the search layouts click your Name: Set up: Customize : select the appropriate object:
  1. Choose the “Search Layouts” link.
  2. Click “Edit” next to the layout we want to customize.

We can specify a different set of fields to display for search results, look up dialogs, recent records lists on tab home pages, lookup phone dialogs, list views and search filter fields.

  1. Use the arrows to add or remove items from the layout, and to define the order in which the fields should display.
  2. Click on “Save” button.

Notes on Search Layouts:

  • The search Layout does not determine which fields are searched for keywords matches.
  • We can add up to 10 fields to each search layout.
  • We cannot remove unique identifying fields, such as Account Name, Opportunity Name or Case Number from the search layouts.
  • These fields must be listed first in the order of fields in the search layout.
  • We cannot add long text fields such as Description, solution details, or custom long text area fields to search layouts.
  • If a field is included in the search layout but hidden for some users via filed- level security, those users do not see that field in their search results.
  • Formula fields are not available in search layouts.

Validation Rules:

Validation Rules help improve data quality by preventing users from saving incorrect data. We can define one or more validation rules that consist of an error condition and corresponding error messages.

  • Validation rules are executed at record save time.
  • A Validation rule can contain a formulae or expression that evaluates the data in one or more fields and returns a value of True or False.
  • Validation Rules also include an error message to display to the user when the rule returns a value of “True” in formulae due to invalid value.

 

 

  • Error message can be displayed directly below field or at top of the page.
  • Multiple error messages may be displayed at one time.
  • When the validation rules are defined for a field or set of fields, the following actions are fired when the user creates a new record or edits an existing record and then clicks the “Save” button.
  1. Sales force executes the validation rules and only if all data is valid, then record will save.
  2. For any invalid data, sales force displays the associate error message without saving the record.
  • Even if the fields referenced in the validation rule are not visible on the page layout, the validation rules still apply and will result in an error message if the rule fails.

Example of validate Data:

  1. Make fields conditionally required, depending on the value of another field.
  2. Ensure that numbers are within a specific range, such as discount is less than 30%.
  3. Start Date is before end Date.

Creating Validation Rules:

For standard objects

  1. Click Your Name: Set up: customize select the appropriate object: click validation Rules.
  2. Click New in the validation Rules Section.
  3. Enter the rule name ( unique identifier of up to 80 characters with no spaces or special characters such as extended characters)
  4. Select the “Active” Check box (It determines that the rule is enabled)
  5. Enter the “Description”: A 255 character or less description that distinguishes the validation rule from others.
  6. Give the “Error Condition Formula”: The expression is used to validate the field.
  7. Enter the “Error Message”

The message that displays to the user when a field fails the validation rule.

(Or)

The error Message field is the text to be displayed to the user when a record update fails the validation rule.

  1. Select the “Error Location”.

The “Error Location” is used to determine where on the page the error  is displayed to the user  Locations are

  • Top of Page
  • Field
  • The top page option sets the error message to be displayed at the top of the page.
  • To display the error next to a field, choose the “field” option and then select the appropriate field.

Note: If the error location is set to a field, that is later deleted or a field that is read only or not visible on the page layout, sales force automatically changes the error location to “Top of Page”.

  • Click on “Save” button to finish the validation rule.
  • Click on “Save & New” button to create additional validation rules.

Example: The following examples shows the opportunity validation rule to ensure that users cannot enter a date in the past into the “close Date” field.

Formula: CloseDate < TODAY()

Note: An error message will be displayed to the user if the formula evaluates to TRUE.

  • An above example error message for this validation rule is “Close Date Must Be a Future Date”.

Important functions in Validation Rules:

These functions we will use in both validation Rules, and Workflows.

  1. ISNEW():  Checks if the formula is running during the creation of a new record and return TRUE if the existing record is being updated, this function returns “FALSE”.

Example: Use the following validation rule to prevent users from creating a record with a close date in the past and checks if the user is creating a new opportunity and if so, ensure that the close date is today or after today.

Formula: AND(ISNEW(), close Date< TODAY())

 

AND: Returns a “TRUE” response if all values are true; returns a “FALSE” response if one or more values are false.

Example: AND (Condition1, Condition2, …….)

This formula is true, when condition1, condition2 are true at a time.

 

OR: Determines if expressions are true or false. Returns “TRUE” if any expression is true. Returns “FALSE” if all expression are false.

 

Example:  OR (Condition1, Condition2, … )

This formula is true, when any condition is true and it is false, if all the conditions are false.

 

IF:  Determine if expression are true or false. Returns a given value if true and another value if false.

Ex:

If (payment_Due_Date__c  < TODAY(), “PAYMENT OVERDUE” )

Logic_test                                         null ( Value if flase)         Value if true

 

Note: This example uses a custom field called payment due date. And above formula determines if the payment due date is past. If so, returns the text “Payment over Due” and if not, leaves the field blank.

ISPICKVAL:

Determines if the value of a pick list field is equal to a text literal we specify.

Example:

ISPICKVAL (Country__c, “india”)

Pick list field                          Text literal

This example uses the custom field “Country—c” and above formula is true when the country is equal to India.

Scenario:

The following validation rule prevent users from creating a Account with a Record status is  “Un validated”.

Formula: ISPICKVAL (Record_Status__C, “Un validated”)

This above scenario uses the custom field called Record Status (Data type = pick list) with values

  1. Un validated
  2. Validated
  3. Rejected

ISCHANGED:

Compares the value of a field to the previous value and returns TRUE if the values are different. If the values are the same, this function returns FALSE.

Example: ISCHANGED (Name)

Field (Account Name)

The above formula prevents users from changing the Account Name. i.e., create an account record with Account name “Test” and now changing the Account name to “Test2”. This validation rule will fire and gives the error message.

PRIORVALUE: Returns the previous value of a field.

Syntax: PRIOR VALUE (field)

Scenario:

The following validation rule will fire when the record status changing from “Un validated” to “Validated”.

Formula: ISPICKVAL (PRIOR VALUE (Record_Status__C), “un validated”) && ISPICKVAL (Record_ Status __C, Validated”)

IS BLANK:

Determines if an expression does not have a value and returns TRUE. If it contains a value, this function returns FALSE.

Example: ISBLANK (Expression)

Here we can replace a field

Example1: ISBLANK (Active –c)

If it is pick list field, then we have to give ISBLANK (TEXT (Active__C))

  • If we want to make the field required, then we have to use ISBLANK() function.

ISBLANK (expression)

This expression allows both number and text fields.

IS NULL:

Determines if an expression is null (blank) and returns TRUE if it is. If it contains a value, this function returns FALSE.

Syntax: ISNULL (expression)

(Only number fields, but here text fields will not be allowed.

Example: ISNULL (Amount__C) this will make the Amount only Number field.

Field required.

  • What is difference between ISBLANK () and ISNULL() ?

Ans: Both determines if an expression has a value and returns TRUE if it does not. If it contains a value, this function returns FALSE.

IS BLANK (expression): The expression allows both number and text fields.

(Both number and text fields)

ISNULL (Expression): (Only number fields)

Here the expression allows only number fields.

TODAY: Returns the current date as a date data type.

Syntax: TODAY ()

Example: Sample Date < TODAY ()

This example ensures that users can not change the sample Date to any date in the past.

YEAR: Returns the four- digit year in number format of a given date.

Syntax: YEAR (date)

Ex: YEAR (TODAY ()): 2012

 

 

REGEX:

Compares a text field to a regular expression and returns TRUE if there is a match. Otherwise, it returns FALSE.

Syntax: REGEX (text, regex- text)

Text field, Regular expression is a String used to describe a format of a string according to certain syntax rules.

Example:

The following example ensures that a custom field called SSN matches a regular expression representing a valid social security number format of the form 999-99-9999

Ex: REGEX (SSN—C, [0-9] {3} – [0-9] {2} – [0-9] {4}”)

Field                          Regular expression

Email Templates:

We can create four different types of email templates

  1. Text
  2. HTML (Using Letter Head)
  3. Custom (Without using Letter head)
  4. Visual force

Text:

All users can create or change text email template.

HTML with Letter Head:

Administrators and users with the “Edit HTML Templates” permission can create HTML email templates based on a Letter Head.

Custom HTML:

Administrators and users with the “Edit HTML Templates” permission can create custom HTML email templates without using a letter head.

Visual Force:

Administrators and developers can create using visual force. Visual force email templates allow for advanced merging with a recipients data, where the content of a template can contain information from multiple records.

  • All of these email templates can include text, merge fields and attached files.
  • We can also include images on HTML and visual force templates.
  • Text and HTML templates can also be used when we send mass email.
  • We can’t send a mass email using a visual force email templates.

Creating Text Email Templates:

For creating Email Templates with the type “Text”

Click Your Name:

Setup: Administration Set up: Communication Templates: Click on “Email Templates”

  1. Click on “New Template” button
  2. Choose the “Text” template type, and click “Next”
  3. Choose the folder in which to store the template.
  4. Select the “Available For use” Check box if we would like this template offered to users when sending an email.
  5. Enter the Email Template Name and Template Unique Name.
  6. Select a default encoding setting to determine the character set for the template.
  7. Enter a description for the template. Both template name and description are for internal use only.
  8. Enter the “Subject” for the message that appears as subject for email.
  9. Enter the text to appear in the message.
  10. Optionally, enter merge fields in the template subject and text body. These fields will be replaced with information from records when we send an email.

Note: Merge Fields Overview:

Merge fields serve as placeholders for data that will be replaced with information from records, user information, or company information.

  • When we insert the Account Number merge field in an email template, the syntax is

{! Account. Account Number}

Object                     Field Name

  1. Click on “Save” button

Creating Custom HTML Email Templates:

For creating custom HTML Email templates, go to the following path.

Your Name: Set up: Administration Set up: communication Templates: Click on “Email Templates”

  1. Click on “New Template” button
  2. Choose Custom (Without using Letter head) and click Next.
  3. Choose a folder in which to store the template.
  4. Select the “Available for Use” check box if we would like this template offered to users when sending an email.
  5. Enter the “Email Template Name” and Template unique Name.
  6. Select a default encoding setting to determine the character set for the template.
  7. Enter a description of the template.

Select the Letter head and Email Layout.

  1. Click on “Next” button
  2. Enter the “Subject” to appear in the email we send.
  3. Enter the HTML Source text to appear in the message we send. This should include all the HTML tags.

 

Note:

If we are including an image, we recommend uploading it to the Documents tab so that we can reference the copy of the image that is on server.

  1. Optionally, enter merge fields in the template subject and body.
  2. Click “Next” button.
  3. Optionally , enter the text only version of email or click copy text from HTML version” to automatically paste the text from HTML Version without the HTML tags. The text- only version is available to recipients who are unable to view HTML emails.
  4. Click on “Save” button.

Note: Click “send Test and verify Merge fields” to view a sample of the template populated with data from records we choose and send a test mail.

Work flow Rules:

  • The workflow rules allow us to automate the business processes for organization.
  • Work flow rules provide benefits such as improving the quality and consistency of data, increasing data integrity, improving efficiency and productivity, lowering costs and reducing risks.
  • Work flows allows us to automate the following types of actions:
  1. Email Alerts
  2. Tasks
  3. Field Updates and
  4. Outbound Messages.

Email Alert:

An email alert is an action that is sent to specified recipients using the email templates. The recipients may be sales force users or others.

TASKS:

Tasks can be assigned to users or record owners automatically when the rule criteria meet. Work flow tasks provide the subject, status, priority and due date for the tasks a rule assigns.

  • Tasks appear on the user’s calendar which can be accessed by the “My Tasks” section of the Home tab.

Field Update:

Field update is an action that will update the value of a field automatically. Work flow field updates specify the field we want to update and the new value for it.

Depending on the type of field, we can choose to apply a specify value, make the value blank, or calculate a value based on a formula we create.

Outbound Message:

Outbound Message is an action that sends a secure, configurable API message (in XML format) to an external system.

Note: The work flow rules are trigged up on the Clicking of “Save” button.

Types of Work flows:

There are two types of work flows

  1. Immediate Work flows
  2. Time- Dependent Work flows.

 

 

Immediate workflows:

In this kind of work flows the work flow actions will execute immediately whenever a record meets the conditions specified in the work flow rule.

  • Immediate actions trigger as soon as the evaluation criteria are met.

Time- Dependent Work flows:

In this kind of work flows the action that queue when a record matches the criteria, and execute according to time triggers.

Example: Salesforce.com can automatically send an email reminder to the account team if a high- value opportunity is still open ten days before the close date.

  • Example of immediate work flow is, salesforce.com can automatically send an email that notifies the users when a new account is created with status “Un validated immediately”.

Creating Workflow Rules:

The following steps are required to create a work flow rule.

  1. Select the object
  2. Select the Evaluation Criteria and Rule Criteria.
  3. Specify the work flow actions
  4. Activate the workflow rule

To create a work flow rule, follow the path

Your Name: Set up: App Setup: Create: Work flow & Approvals: Work flow Rules: The Workflow Rules detail page shows a list  of the current workflow rules along with various properties such as the associated object and whether the rule is active.

  • From the work flow rules list page, click on “New Rule” button.

Step1: Select object (Select any one object from drop- down values)

  • Now Click on “Next” button

Step2: Configure work flow rule.

(This page will use to select the evaluation Criteria and rule Criteria.)

  • In the edit Rule section we must enter a rule name and optionally, we can enter a description for the rule.
  • Evaluation Criteria:

In the Evaluation Criteria section, we can choose the appropriate Criteria that cause the application to trigger the work flow rule.

The criteria can be selected from the following three options.

  1. When a record is created, or when a record is edited and did not previously meet the rule criteria.

The rule is not re- triggered on record updates that do not affect the specified rule Criteria.

For example, we have created the workflow rule by selecting this option and record status =” Un validated” in the Rule Criteria.

This workflow will fire when the account is created with record status = Un validated”

Or

This Work flow rule will get fire, when the existing record is updated with the record status = “un validated” previously the value is other than “un validated”)

  1. Only when a record is created.

Choose this option to ignore any subsequent updates to existing records as the rule will only ever run once when the record is created.

  1. Every time a record is created or edited.

Choose this option to include new records inserts and updates to existing records. This action cause repeated triggering of the rule, as long as the record meets the criteria.

***Note:

We cannot add time- dependent actions to a rule if we choose the “Every time a record is created or edited” Option.

 

Rule Criteria:

In the Rule Criteria section, there are two ways of formulating the logic that is used to trigger the work flow rule.

  1. Run this rule when Rule Criteria = “Criteria are met”
  2. Run this rule when Rule Criteria = “ formula evaluates to true”

 

 

Run this Rule When Rule Criteria = “Criteria are met”

This option is displayed by default and allows us to select the Field from the drop down values and select the operations from the list of values and give the value.

Example:

        Field                                 Operator          Value
  1. Close Date                  equals                         TODAY()
  2. Closed                          not equal to    True

The “Add Row” link allows us to add more criteria options where up to a maximum of 25 can be added.

  • Give the filter logic, this allows us to use Boolean expressions to set the Criteria

Example:

1 OR 2

In this case, the criteria are met will be true when any one of Criteria is true.

1 AND 2

 

In this case, the criteria are met will be true when both criteria is true.

 

Run this Rule when Rule Criteria= “formula evaluates to true”

This option allows us to enter a formula that returns a value of “True” or “False”. The application triggers the rule if the formula returns “True”.

  • Check Syntax:
  • Click on the “Check Syntax” button to validate that the formula contains no error before progressing beyond this page.
  • Click on “Save & NEX” button.

Step 3:  Specify work flow Actions.

This page which allows us to configure the work flow actions.

Adding Immediate Work flow Actions:

To add an immediate work flow action, click on “Add Work flow Action” drop down selection in the immediate work flow actions selection and choose either.

New Task: To create a task to associate with rule.

New Email Alert: To create an e-mail alert

Ne Field Update: To define a field update

New Outbound Message or “Select Existing Action” to select an existing action to associate with the rule.

To define an out bound message to associate with the rule.

 

Configuring tasks for Work flow Rules:

To configure tasks for work flows,

Click Your Name: Setup: App Setup: Create: Work flow & Approvals: Workflow Rules.

Click on particular Rule Name: Click on “Edit” button on Work flow Actions Section.

  1. Click on “Add Work flow Action” button and select “New Task” option from the drop down list.
  2. Select an assignee, an assignee can be in the form a of a user, role and record owner.
  3. Enter a subject for the task and unique name for the task.
  4. Choose a due date, status, and priority where due dates appear in the time zone of the assignee.
  5. Set the “Notify Assignee” Check box to send an e- mail notification when the task is assigned.
  6. The “protected component” check box is used to mark the alert as protected.
  7. Optionally, enter any comments for the description information that is included with the task and then click on “Save”.
  • Go to “Assignee User” login and check this task in “My Tasks” section by clicking on “Home” tab.

Configuring e-mail alerts for Work flow Rules:

To configure e- mail alerts for work flow rules, follow the steps below.

Click Your Name: Setup: App Set up: Create: Work flows & Approvals: work flow Rules: Click on Particular work flow Rule Name: Click on “Edit” button on “Work flow Actions” section:

  1. Click on “Add Work flow Action” button and select “New Email Alert” option form the drop down list.
  2. Enter a description for the email alert.
  3. Enter a unique name for the e- mail alert

(The unique name for the e-mail alerts is required and used by the API and managed packages. The name is auto- populated when we enter the preceding field called description.)

  1. Choose an e- mail template (Creation of e- mail template will be discuss in upcoming pages)
  2. The “protected component” check box is used to mark the alert as protected.
  3. Now select who should receive this e- mail alert from the available options.

Recipients: select “Account Owner” from the drop down list.

  • If the account owner is selected then the e- mail alert is sent to the user who is set as owner of the account record.
  • Recipients: Account Team

If the “Account Team” selected, then we have to choose from the list of users that are assigned to a particular account team role.

(Note: E-mail alerts are only sent when the rule is associated with the account object)

 

  • Recipients: Creator

This is the user listed as the record creator and is the user who is set in the created by field.

  • Recipients: Email field

An e-mail address field on the selected object, such as the Email field on contact records or a custom e-mail field.

  • Recipients: Owner

The record owner

  • Recipients: Public Groups

Choose from the list of users in a particular public group.

  • Recipients: Role

Choose from the list of users assigned a particular role.

  • Recipients: Role and Subordinates

Choose from the list of users in a particular role, plus all users in roles below that role.

  • Recipients: user

Choose from the list of available users in Sales force CRM.

  1. Select the recipients who should receive this email alert in the “available Recipients” list and click on “Add”.
  2. Enter up to five additional recipients e- mail address

(Which may or may not be users in sales force)

  1. Set the “From Email Address” to either the Current user’s e-mail address or to the default workflow users email address.
  2. Click on “Save” button

Configuring field updates for Work flows:

To configure field updates for work flows

Click Your Name: setup: App Setup: Create: Work flow& Approvals: Workflow Rules: Click on Particular Work flow Rule Name: Click on “Edit” button on Work flow Actions Section

  1. Click on “Add Work flow Action” button and select “New Field Update” option from the drop down list.
  2. Enter a Name and a unique name for the field update.
  3. Now, optionally enter a description for the field update
  4. Upon choosing the field to update, a new section called “Specify New field value” appears where we can set the logic of the desired field update.

Here, the available options depend on the type of field we are updating following scenarios:

Check boxes:

For checkboxes, in specify new field value section, Choose “True” to select the checkbox and “False” to deselect.

 

Pick lists:

For pick lists fields, select “A Specific value” Check box from pick list options in specify New field value section and choose the pick list value from the drop down list.

Other data types:

For all other data types, we can set the following “Text Option” as shown.

Follow these steps to finish the field update configuration.

  • Choose a blank value (null) if we want to remove any existing value and leave the field blank.
  • Choose “Use a formula to set the new value” to calculate the value based on formula to set the new value” to calculate the value based on formula logic.
  • Click on “Save” to complete the configuration of the field update.

Adding Existing Action:

We can add existing action (i.e. either Task, or Email Alert, or Field Update) directly from “Select Existing Action” option following procedure gives the information about how to add Existing Action to the particular work flow.

Click Your Name: Setup: App Setup: Create: Work flow & Approvals: Work flows:

Click on particular work flow Rule Name: Click on “Edit” button on Work flow Actions section.

  1. Click on “Add work flow Action” button and choose “Select Existing Action” option from the drop down list.
  2. In the select Existing Actions page, choose action Type and add the actions into selected actions from the available actions by clicking on “Add” button.
  3. Click on “Save” button to associate selected actions to the work flow rule.

Adding Time- dependent work flow Actions:

  • To add a time- dependent work flow action, click on “Add Time Trigger” button in the Time Dependent work flow Actions Section.
  • Then specify a number of days or hours before or after a date relevant to the record, such as the date the record was created or modified.

*** We cannot add time trigger when the rule criteria is set to “Every time a record is created or edited”.

(The “add time Trigger” button will be disabled for these criteria)

  • And also the “Add Time Trigger” button is unavailable when the rule is already active. (here we must deactivate it in order to apply the action)
  • And also, the rule is deactivated, but has pending actions in the work flow queue.

Additional Immediate or time- dependent actions can be configured and then finally click on the “Done” button on the top- right of the screen.

Activating the work flow rule:

  • The sales force CRM Application will not trigger a work flow rule. Until we have manually activated it.
  • To activate a work flow rule, Go to the work flow rule detail page and click on “Activate” link on Action facet and click on “Deactivate” to stop a rule from triggering.

 

Monitoring the work flow queue:

We can use the time- based work flow queue to monitor any outstanding work flow rule that has time- dependent actions.

In the following path, we can view pending actions and cancel then if necessary.

Your Name: Setup: Administration Setup: Monitoring: Time based Work flow:

Give the Criteria: Click on “Search” button to view all pending actions for any active time-based work flow rules that match the criteria.

Understanding Cross – Object Field Updates:

For all custom objects and some standard objects, we can create work flow actions where a change to a detail record, that update a field on the related master record.

  • Cross – Object field updates works for

Cross- to – Custom master – detail relation ships

Custom – to – Standard master- detail relation ships

Standard – to – Standard master- detail relation ships

Example: Create a work flow rule that sets the Active check box to true on opportunity (The Master object) when a Designation (The detail Object) is created with the status equal to “Active”.

(The above example uses the creation of)

  1. Active (data type = Check box) on opportunity
  2. Designation (Custom Object)
  3. Status (data type = pick list) on Designation Object

Values: Active, inactive.

  • We can use cross – Object field updates for following cases
  1. For all custom objects that are children of Custom Objects in master – detail relationship.
  2. For all custom Objects that are children of certain standard objects in master – detail relationship.
  3. For Standard objects that are children of standard objects in M – D relationship.

Configuring Cross – Object field Updates:

To configure Cross- Object field updates,

Click Your Name: Setup: App Setup: Create: Work flow & Approvals: Click on Field Updates: Click on “New Field Update” button.

  1. Enter name and unique name of a field update
  2. Optionally enter a description of a field update.
  3. Select the detail Object (i.e. detail Object in the M – D relationship)

Example: Opportunity

  1. Once the detail Object is selected,” Field to update” will automatically populate with the master- Object (Account) fields and detail – Object (opportunity) fields.
  2. Select the field, and “Specify New field Value” and Click on “Save” button.

Import Wizard:

It is the one way to import/ export the data into/ from salesforce.com

  • This supports Accounts/ Contacts, Leads, Solutions & Custom Objects
  • Supports up to 50,000 records.
  • Duplicates will not be allowed.
  • Don’t have Batch size.

*** Sales force import wizard supports only CSV files: Comma Separated Values (or) Comma delimited values.

Report Types:

  • Report types allow us to build frame work in the report builder from which users can create and customize Reports.
  • A report type defines the set of records and fields available to a report based on the relationships between a primary object and its related objects.
  • Sales force provides a large range of pre- defined standard report types.
  1. Accounts & Contacts: Contains information about accounts and contacts.
  2. Opportunities
  3. Customer Support (Report types regarding Cases & Solutions)
  4. Leads
  5. Campaigns
  6. Activities
  7. Administrative Report types
  8. Price books, Products and Assets report types.

Creating Custom Report Types:

In addition to the standard report types, we can also create custom report types. Custom report types extend the types of reports from which all users in organization can create or update custom reports.

Custom report types are created using the following steps follow the path

Your Name: Setup: App Setup: Create: Report types: Click on “New Custom Report Types” button

Step1:

Defining the custom Report Type

  • From the Primary Object drop-down list, select the primary Object from which we want to build custom Report type.
  • Enter the Report type Label and the Report type Name.

The label can up to 255 Characters long.

  • Enter a description for the Custom Report type, this will be visible to users who create Reports and is used to help the purpose for the custom Report type.
  • Select the Category to store the Custom report type.
  • Select the Deployment status.

If we select “In development”, this will hide the custom Report type and prevent users from creating and running reports from the report type.

  • Choose “Deployed, if we want to let users create and run reports using that Custom report type.
  • Now click on “Next” button, and then choose the object relationships that a report can display when run from a custom report type.

Step2: Define Report Records set:

To add child Objects to the report type, so that users can access both fields in the report builder.

  • Click on the box under the primary object.
  • Select a child object, only related objects are shown.
  • For each child object, select one of the following criteria.

Each “A” record must have at least one related “B” record:

Only parent records with child records are shown in the report.

Reports may or may not have related “B” records.

Parent records are shown, whether or not they have child records

  • Click “Save” button.

Edit Layout:

After clicking on “Save”, the layout can be edited to specify which standard and custom fields a report can display when created or run from the custom report type by click on “Edit Layout” button.

  • To start configuring the layout, select fields from the right- hand box and drag then to a section on the left.
  • We can view specific objects fields by selecting an object from the “View” drop- down list and arrange fields with in sections as they should appear to users.

Note: we can add up to 1000 fields to each custom report type.

  • To rename the sections, click on Edit next to an existing section, or create a new section by clicking on “Create New Section”. Now click on “Save”.

 

Note:

  • When a Custom report type is deleted, any reports that have been created from it are also deleted.
  • Furthermore, any dashboard components that have been created from a report that was created from a deleted Custom Report type will show an error message whenever viewed.

Reports:

A report returns a set of records that meets certain criteria and displays it in organized rows and columns. Report data can be filtered, grouped, and displayed graphically as a chart.

  • Reports are stored in Folders, which control who has access.
  • We must have “Read” permission on the records included in reports, otherwise when we run them; they may be missing data or appear blank.

Report Folders:

The Report folders section allows us to choose the reports that are stored in specific folder.

  • In sales force CRM , we cannot save reports to the standard report folders, we can only save reports to the My personal custom Reports folder, Unfired Public Reports folder, or any custom Report Folder where we have appropriate read/write access.
  • Using the link, “Create New Folder” allow us to create new report folders for custom reports.

Creating Report Folder:

For creating Report Folder, follow the steps below.

  • Click on “Reports” tab.
  • Click on “New Report Folder” option in the left side of page.
  • Enter Report Folder Label and Folder Unique Name.
  • Give the Public Folder Access.

Read Only: This access allow users to view the reports under this folder.

Read/ Write: This access allows users to view, edit the reports under this folder.

  • We can move reports from Unfiled Public Reports folder.
  • We must specify the accessibility to users where we can select from either

Accessible by all users: All users can able to run the reports under this folder.

Hidden from all users: No user can view any report under this folder.

Accessible by following users: Add the public Groups

Roles

Roles & Subordinates

Only users belongs this categories can able run the reports under this folder.

  • Click on “Save” button.

*** Note:

  1. Deleted Reports and Dashboards can be retrieved from the recycle bin.
  2. We cannot use the Reports search functionality to search for standard Reports.

 

 

 

Standard Vs Custom Reports:

Standard ReportsCustom Reports
  • Are built in
  • Can be built from scratch
  • These reports are stored in standard folders
  • Must be saved in a Custom personal or unfiled public Reported folder.
  • Cannot be edited or deleted
  • Can be edited or deleted
  • Cannot be searched
  • Can be searched.

 

Types of Reports:

Sales force supports four report formats, each with varying degrees of functionality and complexity.

  1. Tabular Report:
  • Tabular Reports provides a simple listing of data without sub totals.
  • Tabular Reports are most suited for creating lists of records or a list with a single grand total as they cannot be used to group data.
  1. Summary Reports:
  • Summary Report format provides a listing of data like a tabular report, plus sorting (grouping) and subtotalling of data.
  • Summary reports can be used to get subtotals based on the value of a particular field.
  1. Matrix Reports:
  • Matrix Report format provides totals for both rows and columns.
  • Matrix reports allow us to group records both by row and column.

Note:

  • Tabular reports cannot be used source report for dashboard components.
  • Summary reports, Matrix reports can be used as the source report for dashboard components.

Creating Reports:

The basic steps for creating new reports are:

  1. Click on “Reports” tab, and click on “New Report” button.
  2. Select the report type for the report, and click on “Create” button.
  3. Customize the report, then save and run it.
  • Give report Name and Report Unique Name.
  • Once we Click on “Save” button, use the Description field to describe exactly what the report is intended for (There is maximum of 255 Characters)
  • Select “My Personal Custom Reports” or “Unfiled Public Reports” report folder to store the custom report.
  • Selecting the appropriate report type is one of the most important steps in creating a report. Report types allow pre- defined sets of records and fields to be available within a report based on the relationship between a primary object and any related objects.

Customizing Reports using Report Builder:

Go to any report and click on “Customize” button. Report Builder will open. It is a visual editor for reports. The Report builder interface consists of three panes.

Fields Pane:

The field’s pane lists all accessible fields in the selected report type, organized by folder. Find the fields we want using the Quick Find search box and field type filters, then drag them into the preview pane to add them to the report

  • We can create view and delete our custom summary formulas in the field’s pane as well.

Filters Pane:

Set the view, time frame and custom filters to limit the data shown in the report.

Preview Pane:

In this preview pane, we can add, recorder and remove columns, summary fields, formulas and groupings. Change the report format and display options, or add a chart.

The preview shows only a limited number of records, run the report to see all results.

Creating Charts:

To add or edit a chart.

  1. Click on “Add Chart” in report builder. Our report must have at least one grouping before we can add a chart. For existing charts, click “Edit Chart”.
  2. Select a chart type.
  3. Enter the appropriate settings on the chart Data tab for the chart type we selected.
  4. Enter the appropriate settings on the formatting tab.
  5. Click “OK”.

Types of Charts:

  1. Horizontal Bar Chart
  2. Vertical Bar Chart
  3. Line Chart
  4. Pie Chart
  5. Donut Chart
  6. Funnel Chart
  7. Scatter Chart

 

 

Scheduling and Emailing Reports:

To Schedule Report:

  • Click on “Report” tab and click an existing report name
  • Click “Run Report” and choose schedule Future Runs… from the drop down.
  • Select notification settings to email the report at the scheduled time.
  • Select “To me” to send the report to the email address specified on sales force user record.
  • Select “To me and / or others… “To email the report to additional users.
  • Schedule the report.

In the Frequency field, select how frequently to run the report. Select daily, weekly or monthly and then refine the frequency Criteria.

In the start and End fields, Specify the dates during which we want to schedule the report.

We must select a start time for running the report. Next to preferred start Time, click Find Available options… To start time.

  • Click “Save Report Schedule” to schedule the report.

Exporting Reports:

To export a report, users can perform the following steps:

  • Click on any existing report name
  • Click on “Export Details” button
  • Set the default option in the Export File Encoding
  • Set the Export File format to either Excel or CSV (comma delimited)
  • Click on “Export” button.
  • In the browsers file download dialog, they can choose where to save the file to on their local disk.

Note: Up to 256 columns and 65, 536 rows of data can be exported from a report.

Dashboards:

A dashboard shows the data from source reports (Summary reports, Matrix reports) as visual Components, which can be charts, gauges, tables, metrics or visual force pages.

  • Each dashboard can have up to 20 Components.
  • Administrators control access to dashboards by storing then in folders with certain visibility settings.
  • Dashboards folders can be public, hidden or restricted to groups, roles. If we have access to a folder, we can view its dashboards.

Components:

  1. Horizontal Bar Chart
  2. Vertical Bar Chart    ( Bar charts Compare two or more groupings)
  3. Line Chart (Connect a service of points that represent individual data measurements.
  4. Pie Chart
  •  Compare the parts that make up a whole
  • Good for seeing how much each part Contributes to an overall total.
  1. Donut Chart (Show proportion of individual groupings to each other, and to the total.
  2. Funnel Chart ( Good for identifying bottle necks (large Components)
  3. Gauge

Gauge component type may be used to show a single value that is to be shown as a part of a range of custom set values.

  1. Metric

Metric Component types used to show a single value to display (i.e. Total Value)

  1. Table

Table Component types are used to show a set of report data in column form.

  1. Visual force Page

Visual force page component types may be used to create a Custom Component type and present information in a way not available in the standard dashboard component types.

Data Sources:

  • Reports and visual force pages are the sources to create a dashboard.
  • Only Custom Reports are the sources for the Dashboards.

Note:

Dashboards are generally graphical representation of summary, Matrix reports.

  • We cannot create dashboard for the tabular report when we drag the tabular report into the dashboard component. Then we will get the error. The data will not be displayed.

Creating Dashboards:

Before creating dashboards, create the custom reports containing the data we want to display. Make sure that these reports in folders have the access to users.

  1. Click the Dashboards tab.
  2. Click Go To Dashboard List
  3. Click “New Dashboard…” button to create a new Dashboard.

To modify an existing dashboard, click its name from the list.

  1. Customize dashboard and click Save.

Customizing Dashboards:

Dashboards builder is a drag – drop interface for creating and modifying dashboards.

To customize a dashboard, view it and click “Edit”. Dashboard builder contains following controls.

Dashboard – level Controls:

Click “Dashboard Properties” to change the title, unique- name, folder and component settings.

  • Click “Save” button and give the little, Dash board unique Name and folder to save.
  • View or set the running user for the dashboard.
  • Click the text field at the top of the dashboard to add a description.

Column- Level Controls:

  • Click ‘+’ to add a new column. Dashboards can have up to three columns.
  • Click ‘X’ for column to delete. Dashboards must have at least two columns.
  • Select Narrow, medium, or wide in the drop – down to set a column’s width.
  • Drag the Dashboards components from left side to the right columns and drag sources

I.e. reports into the dashboard components.

 

Selecting a Dashboard Running User:

Each dashboard has a running user, whose security settings determine which data to display in a dashboard.

To select the running user for a dashboard:

  1. Edit a dashboard.
  2. In the view dashboard as field, enter a running user. Enter ‘*’ to see all available users.
  3. Save the dashboard.

The running user options are:

  1. Edit a dashboard
  2. Click the drop down button next to “View dashboard as” field.
  3. Choose the dashboard type.

Run as specified user: The dashboard runs using the security settings of that single specific user. All users with access to the dashboard see the same data, regardless of their own security settings.

Run as logged- in – user: A dynamic dashboards run using the security settings of the user viewing the dashboard. Each user sees the dashboard according to his or her own access level.

  • Optionally select “Let authorized users change running user”.
  1. Click “OK”.
  2. Save the dashboard.

It enables permission to change the running user on the dashboard view page.

Groups:

Groups are set of users. They contain individual users other groups, the users in a particular role, the users in a particular role plus all of the users below that role in the hierarchy.

There are two types of groups:

  1. Public Groups:

Only administrators can create public groups. They can be used by everyone in the organization.

  1. Personal Groups:

Each user can create groups for their personal use.

Public Groups:

Public Groups are set of users and they are used in a

  • Sharing rule
  • Give access to folders
  • Email alerts

Public Groups can be made up of any combination of

  • Users
  • Roles
  • Roles and Subordinates
  • Public Groups

When the public Groups are made up of roles or roles and Sub ordinates, when a user is added or removed from the role, the public group membership is updated.

Creating Public Groups:

Go to the following path

Your Name: Setup: Administration Set up: Manage Users: Click on “Public Groups”

  1. Click on “New” button
  2. Give the Label and Group Name of public group.
  3. For public groups only, select “Grant Access Using Hierarchies” to allow automatic access to records using role hierarchies. When selected, any records shared with users in this group are also shared with users higher in the hierarchy.

If “Grant Access Using Hierarchies” is deselected, users that are higher in the role hierarchy don’t receive automatic access.

  1. From the “Search” drop – down list, select the type of member to add. If we don’t see the member we want to add, enter keywords in the search box and Click “Find”.
  2. Select members from the available member’s box and click “Add” to add them to the group.
  3. Click “Save” button.

 

Queues:

  • Queues allow groups of users to manage a shared work load more effectively.
  • A Queue is a location where records can be routed to await processing by a group member.
  • The records remain in the queue until a user accepts them for processing or they are transferred to another queue.
  • We can specify the set of objects that are supported by each queue.
  • We can also specify the set of users that are allowed to retrieve records from the queue.

Note:

  1. We can create Queues for Cases, Leads and custom Objects.
  2. Whenever we create a case queue, lead queue sales force automatically generates a case list view, lead list view to enable use to access the records in the queue.
  3. Case records can be assigned to queue manually or automatically using Assignment rules. Case Queues and Assignment rules are very similar to the queues and assignment rules available for leads.

Creating Queues:

Go to the following path

Your Name: Set up: Administration Set up: Manage Users: Click on “Queues”.

  1. Click on “New” button
  2. Enter the Label and Queue Name.
  3. To notify one email address when new records are placed in the queue, add on email address to “Queue Email”.
  • To notify all queue members and the Queue Email individually when the new records are placed in the queue, add an email address to “Queue Email” and Check “Send Email to Members” Check box.
  • Select the objects we want to assign to Queue from available objects (Case, Lead, and Custom Objects) to the selected objects.
  • Add the members to this queue,
  • Click on “Save” button.

Sales force Editions:

The editions can be divided into

Sales Cloud: Contact manager, group, professional, Enterprise unlimited.

Service Cloud: Professional, Enterprise, Unlimited.

Data.com: Data.com Clean, Data.com corporate, Data.com Lists.

Chatter: Chatter and Chatter plus

Force.com: Force.com one App, Force.com Enterprise, unlimited

Social Enterprise: heroku, radian6…

 

 

 

 

Editions in Sales Cloud: (Comparison)

  1. Contact Manager EDITION:

Users: Up to 5 users can be added

Cost: $/ month/ user.

Facilities: Accounts and Contacts, App Exchange app integration, chatter Collaboration, document attachments, integration with (Gmail, Outlook) Google apps integration, Mobile access, Reports, Task and activity tracking.

  1. Group Edition:

It’s a sales and marketing for up to fire users, with this; we get basic CRM to help your team sussed, including web Lead capture, to generate leads and reports.

Campaign management.

Dashboards to be managed through the sales cycle. You can also get 1 App from App Exchange for free.

Cost: $25/ month/ user

  1. Professional Edition:

Complete Sales app for any size team, choose professional edition if you want no user limits and a bunch of addition features like…

  • Campaign management                                                * Mass Email
  • Email Marketing                                               * Analytics Snapshots.
  • Product Lists                                                      * Role permissions
  • Sales For Casting                                              * Ideas Community
  • Customizable Dashboards                            * Case Tracking
  • Privacy Controls
  • You can create more custom Objects and use up to 5 App Exchange apps.

Cost: $65 / Month / user.

  1. Enterprise Edition:

This is the most popular Edition used.

Cost: $125/ user / month.

Features: Complete and Customize and integrate sales app for your entire business.

And this include all the features of professional edition and additional features are

  • Work flows and Approvals automation
  • Sales teams
  • Territory Management
  • Offline Access.
  • Visual Work flow
  • Profile and page Layouts.
  • Custom apps and Websites.
  • Developer Sandbox
  • Call Scripting
  • Integration via Web Services API.
  • Enterprise Analytics.

 

  1. Unlimited Edition:

The name says it all, unlimited edition, you will receive the permit success plan with success resources, 24 X 7 supports, UN limited online training, and administration services to help customize the sales cloud for your organization.

Cost: $250 / Month / User.

Features:

  • Unlimited Customizations
  • Unlimited Custom apps
  • Unlimited access to 100+ administration Services
  • Assigned Success resource.
  • Increased storage limits
  • Multiple Sand boxes
  • 24 X 7 toll free support.

Service Cloud:

Supports the following Editions:

Professional Edition: $ 65 / user / Month

Enterprise Edition

UN limited Edition

 

 

 

SalesForce Developer Notes:

Apex is a strongly typed object-oriented programming language.

•    It allows the developers to execute flows and transaction control statements.

•    Apex enables developers to add business logic to most system events like button related record updates and visual force pages.

•    Apex language

  • Integrated: it provides built-in support for DML calls
  • Inline salesforce object query language
  • Easy to use
  • easy to test
  • version
  • Multitenant aware

When should I use apex:-

•    To create email service

•    Create web services

•    Perform complex validation over multiple objects

•    To create complex business process that are not supported by workflow

•    Create custom transaction logic

•    Attach custom logic to another operation

How does Apex world:-

All apex programs run entirely ON-demand on force.com platform.

 

 

 

When the developers write and save apex code to the plat form

•    First the platform application server compiles the code into an abstract set of instructions that can be understood by apex runtime interpreter.

•    The compiled code is stored to metadata.

•    When the end user triggers the execution of apex by clicking button or visual force page the application servers retrieve the compiled instructions from the metadata and send them to runtime interpreters before returning the result

Object oriented programming(oops):-

OOP(object oriented programming) is a methodology that provides a way of modularizing a program by creation partitioned memory area for both data and methods that can be used as template for creating copies  of such modules (objects) on demand.

Unlike procedural programming, hence in the loop programming model, programs are organized around objects and data rathers than action and logic

The main oops principles are

  • Encapsulation
  • Inheritance
  • Polymorphism.

Encapsulation: – the wrapping up of data and methods together is called encapsulation. For example, if we take a close, we write the variables and methods inside the class. Thus, class is  binding than together. So the class is an example for encapsulation.

Inheritance: – it creates new classes from existing classes so that the new class  will acquire all the features of the existing classes is called inheritance.

 

A good example for inheritance in nature is parents producing the

Children inheriting the qualities of the parents.

Polymorphism : – polymorphism represents one form in multiple forms . in programming, we can use a single variables to refers to objects of different types and thus , using that variable we call the methods of different objects.thus, a method call can perform different tasks depending on the type of the object.

Apex fundamentals:-

Data type:-

•    Data type in the apex tells about what type of data can be stored.

•    What is the range of the data that can be stored

•    Primitive data type as

•    Collections

•    Enums

Primitive data types:-

These are the data types which are predefined by the apex

•    A primitive data types such s an integral, Double, long date, date-time, string, ID or Boolean.

•    All primitive date type passed by values, not by reference

•    All apex variables, whether hey are class member variables, are initialized no null. Make sure that we initialize variables to appropriate values before using them.

Apex primitive datatypes include:-

Boolean: a value that can only be assigned true,false or null

Ex:- Boolean inactive = false;

Date: – a value that indicates a particular day date values contain no information about time.a date value must always be created with a system static method.

Ex:- date mydate =  date.newing tance(2013,05.15);

Output is 2013-05-15 00:00:00

Time and date time: – these are date types associated with dates and times along with date data type. The data types stores times (hours, minutes, seconds and, milliseconds). The date data type stores dates (year month and day). The date time data type stores both dates and times

Each of these classes has a new instance method with which we can construct particular date and time values.

Ex:- Time t1= new instance(19,20,1,20);

o/p is  19:20:01

•    We can also create dates and times from the current clock

date my= datetime.now();

date t= date.today();

•    The date and time classes also have instance methods for converting from one format to another

Eg:- time t2 = datetime.now().time();

•    We can also manipulate the values by using a range of instance methods

Ex:- date t3 = date.oday(0);

Date next = t3.adddays (30);

We will get something like this the output

2013-05-15  00:00:00

2013-06-16   00:00:00

 

Integer, long, double and decimal: – to store numeric values in variables, declare variables with one of the numeric data type’s integers, long, double and decimal.

Integer: – a 32-bit number that doesn’t include decimal point integers have a minimum value of -2,147,483,648 and a maximum value of 2/147/483,647

Ex:- integer I =1;

Class:-

Class is a collection of data members and methods

Eg: – class student

{

Integer no;

String name;          these are data members f the class

Public void get details()

{

System.debug(‘roll’ + no);

System.debug(‘name’+name);        this is the method of the class

}

}

EX 2: –    class employee

{

Integer ex;            variables/data members of the class.

String department;

Void show()

{

//write the logic        method of the class

}

}

 

•    To define an apex class specify the following

Access modifiers:-

  • You must use one of the access modifiers for top level class ( public or global)
  • You do not have to use access modifiers in the declaration of inner classes.

•    Optical definition modifiers such as vertical, abstract

•    Required: the keyword class followed by the class name

  • Optical extensions: – AND/OR implementation
  • Syntax:-

Private|public|blobal [ virtual|abstract| with sharing|(none)]

Class class name[implements interfacenamelit|(none)][extends class name|(none)]

{

// the body of the class.

}

Access Modifiers:-

  • Private: – if you declare a class a private it is only known to the block in which it is declared.

o    By default, all the inner classes are private

  • Public: – if you declare a class as a public, this class is visible throughout your application and you can access the application anywhere.

•    Global: – if you declare a class a global this apex class is visible to all the apex applications the application or outside the application

Note :-

If a method or a class (inner) is declared as global then the top level also must be declared as global.

•    With sharing:- if you declare a class as a with sharing, sharing rules given to the current users will be taken into the consideration and the users can access & perform the operations based on the permissions given to him on objects & fields.( fields level security, sharing rules)

•    Without sharing :- if you declare a class as a without sharing then this apex class runs in system mode which means apex code has access to all the objects and fields irrespective of current users sharing rules, fields level security, objects permissions.

Note :-

•    If the class is not declared as with sharing or without sharing then the class is by default taken as

•    Both inner classes and locates classes can be declared as with sharing

•    If inner class is declared as with sharing and top level class is declared as without sharing ,then by default entire context will run in with sharing context\

•    If a class is not declared as with/without sharing and if this class is called by another class which sharing is enforced then both the classes runs with sharing

•    Outer class s declared as with sharing and inner class is declared as without sharing then dinners class runs in without sharing context only(inner classes don’t take the sharing properties) from routers class).

  • Virtual:- if a class is declared with keyboard virtual then this class can be entered( inherited) or this class methods can be overridden by using a class called overredden.
  • Abstract : – this class contains abstract methods

Ex :-

Public class outer class

{

//code

Class inner class

{

//innerclass code

}

}

Ex 2:-

Public with sharing class sharing class

{

//code

}

Ex 3:-

Public without sharing class sharing

{

//code

}

Ex 4:

Public with sharing class outer

{

//outer class code

Without sharing class inner

{

//inner class code

}

}

In the above code outers class runs with current users sharing rules. But inners class runs with systems context.

Ex 5:-

Public without sharing class outers

{

//outers class code

With sharing class inner

{

//inner class code

}

}

In this, both inners and outers classes run with current users permissions.

Class variables:-

The variables in the class should specify the following properties when they are defined

•    Optional: modifiers such as public or final as well as static

•    Required: the date type of the variable, such as string or Boolean.

  • Optional:- the value of the variables

•    Optional: – the name of the variables

Syntax:-

[ public | private |protected| global|final ][static]

Data_type variable_name

Eg:-

Private static final integer My_INT;

Private final integer i=1;

Class methods:-

To define a method, specify the following.

•    Optional: modifiers, such as public or protected

•    Required: the data type of the value returned by the method such as string or integer. Use void if the method does not return values.

•    Required: a list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in paranthese(). If there are no parameters, use a set of empty parenthese a method can only 32 input parameters.

•    Required: the body of the method enclosed in braes{}.  All the code for the method, including any local variable declaration is contained here.

Syntax:-

(public | private | protected global) [ override][static]

Dta_type method_name (input parameters)

{

//the body of the method.

}

Ex:-

Public static integer getting()

{

Returns My_int;

}

Ex 2: – Public class example

{

Public integer show (integer age)

{

System.debug (‘my age is ‘ age);

}

}

Object :-

Object is an instance of the class. This has both state and behavior

•    Memory for the data members is allocated only when you create an object.

Syntax:-

Classname      objectname   =     new     classname();

This the name           it’s an               it is a            constructor

Of class for which     reference      keyword

We are creating         variable        which we are

An object                  allocating

The memory

Ex:-

Class example

{

\\code

}

Examole e = new example ();

Constructor:-

The constructor is a special method which have the following properties.

•    The method name will be same the as the class.

•    Access specifies will be public

•    This method will invoke only one that is at the time of creating objects

•    This is used to instantiate the data members of the class

Ex:-

Public class test object

{

//the no argument constructor

Public testobjects()

{

//code

}

}

There are 3 types of constructors.

•    Default constructor

•    Non-parameterized constructor

•    Parameterized constructor

Default constructor:

If an apex class doesn’t contain any constructor then apex compiler by default creates a dummy constructor on the name the of the class  when we create an object for the class.

Ex:-

Public class example

{

}

Example e = new example ();

In the above example, the apex class doesn’t,t contain any constructor. so when we create objects for example class the apex compiler  creates a default constructor

Ex:

Public example()

{

}

Non- Parameterized constructor & parameterized constructor:-

it is a constructor that doesn’t have any parameters or constructors.

Ex: – public class example

{

Integer no;

String name;

Public example (integer X, string my name)

{

Rno = x;                    parameterized constructor

Name = myname;

}

Public example()

{

//code r.no=10;            this is non-parameterized

Name = sam;                constructors

}

}

 

Write an apex program to demonstrate the usage the of the constructor.

•    Open developers console by clicking the name on the salesforce page.

•    Click file & select apex class

•    Enter the class name

•    Write the apex class.

 

Ex:-

Public class employee

{

String employee name;

Integers employee No:

Public employee()

{

Employee name = hari;

EmployeeNo   = 10;

}

Public void show()

{

System.debug(‘employeename is ‘+employeename);

System.debug (‘employeeno is ‘ +employeeno);

}

}

•    Open the anonymous block

Employee e1 = new employee ();

Employee e2 = new employee ();

E1.show ();

E2.show();

This will give output of employee name is hari    and

Employee no is 10

getter name is hari

Employee no is 10.

Usage of apex program with within visual force page:-

•    When you want to call apex class in visyualforce page we have to declare in the following formed

< Apex: page controller = “class name”>

Whenever we call a visualforce page in which controller attribute is defined first created an object for the apex class which is defined in controller.

•    When the object is created for the apex class first it invokes the constructor.

Referring to the apex class members in visual force:-

When you want to fewer apex class variables in the visual force page we need to use getter & settar methods.

Public class example

{

String name;

}

Get method:

When visualforce page want to get the value of a variable defined in thw apex it will invoke get method of that variable.

 

Ex:-

< apex: output label> { ! myname} </apex : outputlable>

 

This is variable defined in apex class.

In the above statement, visual force page is trying to use my name variable which is declared in apex class . so it is invoke automatically get my name() method in the apex class and this method will return the value of that

Public class example

{

String name;

Public void set(string name)

{                    setter method .ths will take the

This .name =  name;        value from the visualforce page and

}                    stores to the apex variable name

 

Public string gets name()

{

Return name;            getter method.this method will

}                with return a value to a visualfirce page

}                whenever a name variable is called

Ex:- Public class example1

{

Integer no:

Public void set(stringno integer no)

{

This .no=no;

}

Public integer gets no()

{

Return no;

}

}

•    Write an example for getter method using visualforce and apex class:-

Example class:-

Public class example

{

String name;

Public string gets name()

{

Return  ‘sam’

}

}

Example page :-

<apex:page controller= “example”>

< apex : outputlable.{!name }</apex: outputlable>

</apex: page>

•    In the above program when the page is loaded first it creates an object for the example class.

•    When output label calls { !name} in the VF page it invoke get name() method in the controller class which will return “sam”

Output :-

•    Apex class example:-

Public class example            When visualforce page is loaded it creates an

{                    Object for the example class

String name;

Public example ()        2. at the time of creating the object if first calls

{                first calls the construct and assign name=’hari’.

Name = ‘hari’,

}

Public string gets name()

{

Return name;                3. when visualforce page called {name}

}                    it invokes getname() in the apex class

}

 

Example page :-

<apex: page controller = “ Example”>

<apex:outputlabel> yourname is {!name}</apex:outputlable>

</apex:page>

Hari

Output:-

 

Writing the values into apex variable from visualforce page :-

This is called read/write operation on the variable

Ex:

{!age}

Public void setage(interger age)

{

This.age=age;

}

Ex:- {!name}

Public void setname(string name)

{

This.name=name;

}

Write an apex class to return the value to visualforce page:

Apex class :-

Public class Example1

{

Public integer age;

Public example1()

{

Age = 10;

}

Public integer getage()

{

Return age;

}

Public string getname()

{

Return ‘sam kumar’;

}

}

Vf page :-

< apex: page controller =” example”>

<apex:form>

<apex:ouputtale> enter name </apex:outputlable>

< apex:inputltext value = “{!name}”/>

<apex: commandbutton value= “click” rererdes=”one”/>

<apex: outputlable id= “one”>your name is { 1name}</apex: outputlable>

</apex: form>

</apex:page>

•    We ca also define setter and getter methods in a single line.

Public integer{ set;get;}

How to call apex methods in an visual force page:-

Public class demp

{

Public page reference show()

{

Return null;  // when we give return null it will come

}                 back to the same page.

}

<apex: commandbutton value =”click” action = “ { ! show}”/>

•    When we click on the “ click “ button it will invoke pagereference show() method.

•    Pagereference is the return type of avery method that we have called from visualforce page.

Public class example1

{

Public string name;

Public string getname ()

{

Return name;

}

Public void set name(string name)

{

This.name=name;

}

Public pagereference show()

{

Name = ‘this is my name’ +name;

Return null;

}

}

<apex: page controller= “example1”>

<apex: form>

<apex: outputlable>enter name</apex;outputlable>

<apex: inputtext value= “{!name}”/>

<apex: commandbutton value=: click”rerendes= “one” action= “{!show}”/>

<apex: outputlable id=”one”> {!name}</apex:outputlable>

</apex: form>

</apex: page>

Eg:-

Simple apex class to perform addition and subtraction based on the button you have clicked.

Public class example1

{

Publc intger bvalue {get; set;}

Publc intger avalue {get; set;}

Publc intger result {get; set;}

Public string operation{get;set;}

Public preference  sub()

{

Result = avalue – bvalue;

Operation = ‘subtraction’;

Return null;

}

Public pagererence subb()

{

Result= avalue+bvalue;

Operation  = ‘ADDITION’;

Return null;

}

}

<apex: page controller= “example1”>

<apex:form>

< apex: pageblock title = “calculator”>

<apex=pageblocksection column=”/    ” title=” simple operations” collapsible = “false”>

<apex : pageblocksection item>

<apex: output label>enter avalue</apex: outputlable>

< apex: input text value=”{!avalue}”/>

<apex:pageblocksectionitem>

<apex: outputlable>enter B value</apex:outputlable>

<apex:inputtext value =:{!bvalue}”/>

</apex: pageblocksectioniem>

<apex:page blocksectionitem>

<apex:outputlable>you have performed{!operation} of {!avaue} and {!bvalue} and  the results  {!result}</apex: outputlable>

</apex: pageblocksectionitem>

</apex:pageblcksection>

</apex:pageblock>

<apex: form>

</apex:apge>

Array:-

Array is a collection of similar elements,where the memory is allocated sequenly.

Datatype[] arrayname= new datatype[size]; //this is called dynamic declaration.

Dataype{} array name = new datatype[] { value1,value2}; //static declarartion

Integer[]  marks= new integer[]{10,20,30};

Account a1= new account(name=’sam’);

Account a2 =     new account( name=’ram’);

Account{} acc= new account{} {a1,a2}

String[] s1=new string[]{‘ram’,’sam’,’ram’};

String{} s1= new string[4];

S1[0]=’kumar’;

S1[1]=’ravi’;

Q :- write a program to display array of strings in pageblock table

Ans  :- public class array example{

Public string[] myval{set;get;}

Public string name{get;set;}

Public arrayexample()

{

Name=’prepaid’;

Myval= new string[]{‘sam’,’ram’,’kiran’};

}

}

<apex:page controller=”arrayexample”>

<Apex:form>

<apex: pageblock>

<apex:pageblocktable value=”{!myval}” var=”a”>

<apex: column value=”{1a}”/>

</apex: pageblocktable>

<apex: outputlable.{!name}</apex:outputlable>

</apex: pageblock>

<Apex: form>

</apex: page>

Q :- Write a program to display array of account records

Ans:-

Public class arrayexample {

Public account [] myval{set;get;}

Public arrayexample ()

{

Account a1=new account(name= ‘sashi’, industry=’banking’);

Account a2 = new account(name=’ravi’,industry=’banking’);

Account a3 = new account(name=’ravi’,industry=’banking’);

Myval= new account[]{ a1,a2,a3};

}

}

<apex:page controller= “arrayxample”>

<Apex: form>

<Apex: pageblock>

<apex: pageblocktable value =”{!myval}” var=”a”>

<apex: column value =”{!a.name}”/>

<apex: colmn value=”{!a.industry”/>

</apex: pageblocktable>

<apex: outputlable> {! name} </apex: outputlable>

</apex: pageblock>

</apex: form>

</apex: page>

Picklist using selectoption from apex:-

1.    <apex: selectlist size=”1”>

<apex: selectoption itemlable=”java” itemvalue=”SCJP”/>

<apex:selectoption itemlable=”sf” itemvalue=”SDFC”/>

</apex:selectlist>

In the apex program we can create same selectoption using a object selectoption.

Selectoption op1= new selectoption (itemvalue,itemlable)

Public class selectexample{

Public selectoption[] myoptions{set; get;}

Public selectexample()

{

Selectoption op3= new selectoption (‘null’,’-none’);

Selectoption op1=new selectoption (‘one’,’jan’);

Selectoption op2= new selectoption (‘two’,’feb’);

myoptions =new selectoption[]{op3,op1,op2};

}

}

<apex:page controller= “selectexample”>

<apex:form>

<apex:selectlist size=”1”>

<apex:selectoptions value=:{!myoptions}”>

</apex:selectionoptions>

</apex: selectlist>

<apex: selectlist size=”1’”>

<apex: selecyoption itemtable=”java” itemvalue=”java”>

</apex: selectoption>

<apex; selectoption itemlable=”SFDC” itemvalue=”SF”>

</apex:selectoption>

</apex ; selectlist>

</apex:form>

</apex:page>

Collections:-

Difference between array and collections

Array                                                                     collections

•    Array is a collection of                                              it is a collection of homogenous &

homeogeneous(similar) elements                                    hetrogeneou element

•    Arrays can not grow and shrink                            it can grow and shrink dynamically Dynamically.

•    Arrays can be accessed faster and                      collections are slow compared to array

Less emory                                                                          consume more memory.

 

List :-

•    List is an interface

•    A list is an ordered collection of elements that are distinguished by their indices.

•    List elements can be of any data type- primitive types collections, subjects,user-defined types and builtin apex types.

Index 0         index 1    index 2        index 3        index 4

green    Blue

Yellow

Red

block

•    Insertion order is preserved

•    Can grow dynamically at run time

•    Duplicate values are allowed

•    Null values are accepted.

Method in list class:-

Add(object) :- adds an element to the end of the list

Add(integer ,object) :- insert an element int the list at the  specified index position

Add all(list): – adds all of these elements in the specified list to the list that calls the method, both lists must be of the same type.

Add all(set): – add all of the elements in specified set to the list that calls the method .the set and the list must be of the same type.

Clear() :- removes all elements from a list, consequently setting the lists length to zero

clone (): – makes a duplicate copy of a list

deepclone (Boolean ,Boolean ,Boolean):- makes a duplicate copy of a list of object records, including the  subject records themselves.

Equals(list): – compare this list with the specified list and returns true if both lists are equal. Otherwise returns false.

Get(integer) :- returns the list element stored at the specified index.

Getsobjects type():- returns the token of the subject type that makes up a list of subjects.

Hash code()-  returns the hash code corresponding to this liast and its contents

Isempty():-returns true if the list has zero elements.

Iterator() :- returns an istance of an iterator for this list

Remove (integer):- removes the list element stored at the specified index,r eturning the element that was removed.

Set(integer , object)-  sets the specified values for the element at the given index.

Size() : – returns the numbers of elements in the list

Sort(): – sorts the items in the list in an ascending order.

 

Eg:-List<string> str = New List<string>();

String S1 =’sam’;

String S2 = ‘Ram’;

String S3 =’Ravi’;

Str.add(S1);

Str.add(S2);

Str.add(S3);

List<String> finalist = new List<String> ();

Finals. Add All (Str);

String X = Str.get (1);//Ravi

 

*Write a program to demonstrate the list.

Public class List Example {

Public List<String> result {Set;get;}

Public List Example ()

{

Result = new List<String> ();

result.add (‘sam’);

result.add (‘ram’);

result.add (1,’kumar’);

}

}

<apex:page controller = “ListExample”>

<apex:pageBock>

<apex:pageBlock Table value = “{!result}”//ar = “a”>

<apex:column value = “{!a}”/>

<apex: pageblock table>

</apex: pageblock >

</apex: page>

List of Objects Demo:-

Public class List Example {

Public List <account> result {Set ; get;}

Public List Example ()

{

Account a1 = new Account (name = ‘sam’ Industry = ‘Banking’);

Account a2 = new Account (Name = ‘ram’ Industry = ‘Energy’);

Result = new List <Account> ();

Result.add(a1);

Result.add(a2);

}

}

<apex;page controller = “ListExamlpe”>

<apex:pageblock>

<apex:pageblocktable value = “{result}” “var = “a”>

<apex:column value = “{!a.name}”/>

</apex:page block table>

</apex:pageblock>

</apex:page>

Create a List of Apex class Objects:-

1. Student Apex:-

Global class student

{

Public String name {get; set;}

Public Integer age {get; set;}

Public Student (String name, Integer age)

{

this. Name = name;

this. Age = age;

}

}

2.List Example Apex:-

Public Class List Example

{

Public List <student> result {set ;get;}

Public List Example ()

{

Result = new List <Student> ();

Student S1 = new Student (‘Sam’, 20);

Student S2 = new student (‘Ram’, 40);

Student S3 = new Student (‘Praveen’,40 );

result.add (S1);

result.add (S2);

result.add (S3);

}

}

Listing Example Visual force:-

<apex: page controller = “List Example”>

<apex: Pageblock >

<apex: pageblock table value = “{!result}” var = “a”>

<apex:column value = “{!a.name}”/>

<apex:column value = “!a.age}”/>

</apex:page block table>

</apex:pageblock>

</apex:page>

Write an apex program to generate list of select options:-

Public class List select

{

Public String my value {get;set;}

Public List<Select Option> My Options;

Public List<SelectOption> getmyoptions()

{

Return my options;

}

Public List select ()

{

Myoptions = new List <Selectoption>();

Selectoption S = new selectoption(‘null’,’None’);

Selectoption S1 = new Selectoption (‘One’, ‘Jan’);

Myoptions.add(S);

Myoptions.add(S1);

myoptions.add(new selection(‘Two’,’Feb’);

myoptions.add(new selection(‘three’,’Mar’);

}

}

<apex:form>

<apex:selectList size = “1” value = “{!myval}”/>

<apex:selectoptions value = “myoptions}”/>

<apex:action support event = “Onchang” rependeu = “One”/>

</apex:select List>

<apex:Outputlabel id = “One”> you have selected {!myval}

</apex:octputlabel>

</apex:form>

</apex:page>

 

SET:-

It is a unordered collection of element where elements can be of any data type. Primitive types, collections, S Objects, user- defined types, and duplicate values.

1.Set don’t allow the duplicate values.

2. Insertion Order is not preserved in the set.

3. It grows dynamically at run time.

Eg:-

Set<String>names = new set <string>();

Set<Account>acc = new set <Account>();

Set<Customer —C> my customer = new Set<Cuetomer—c>();

Public void add(object)// This method will add an element to the set.

Set<String> names = new Set<String>();

Names.add(‘One’);

Names.add(‘two’);

Names.add(‘One’);

Note: – Set will not allow duplicates, but if we insist it will not raise any error it will not take value.

Public voice adds All(List)// this method will add elements to the set.

 

List<String>mulist = new List <string>();

mylist.add(‘One’);

mylist.add(‘Two’);

Set<Stirng> myname = newest<String>();

Mynames.add(‘sam’);

Myname.add All(myList);

Public integer size ()// this method will return no. of

Elements in the set s.

Set<String> name = new set <string>();

Names.add(‘One’);

Names.add(‘two’);

Names.add(‘One’);

Integar mysize = names.size(); // this will return 3 and Stored to my size variable.

Public void remove(Integer index) // This method will remove the elements at the specified index.

Names.remove(1);

Example: – Write an apex class to demonstrate set.

Public class Set Example

{

Public Set<string> names {get; set;}

{

Name = new Set<String>();

Names add(‘One’);

Names.add(‘two’);

Names.add(‘sam’);

Names.add(‘One’);

Names.add(‘one’);

}

}

Vf page:-

<apex:page controllas = “Set Example”>

<apex: Pageblock>

<apex: Pageblock tabl valu =”{!names}” var= ” a”>

</apex: pageblock table>

</apex:pageblock>

</apex: page>

 

*Write an apex class to add list elements to set

Public class Set Example

{

Public set <String> name {get ; set:}

Public set Example ()

{

List<String> mylist = new List<String>();

Mylist.add(‘sashi’);

Mylist.add(‘Sashi’);

My list. Add(‘rakesh’);

My list. Add(‘rakesh’);

Names = new set<string>();

Names.add(‘One’);

Names.add(‘two’);

Names.add(‘One’);

Names.add(‘one’);

Names.add(mylist);

}

}

Public void Retain All(List)// this will keep only the values

That are existing in list and set

Remove rest of the values.

Public class set Example

{

Public set <string> name {get; set ;}

Public Boolean test {get; set ;}

Public set Example()

{

List<string> mylist = new list<string>();

My list. add(‘sashi’);

My list. Add(‘rakesh’);

Names = new set<string>();

Names.add(‘sashi’);

Names. add(‘ram’);

Name. add(Kumar’);

Test = names.retainAll(mylist);

}

}

 

VISUAL FORCE PAGE:-

<apex: page controllas = “SetExample”>

<apex: page block>

<apex: Outputlab> {!test} </apex: outputlab>

<apex: datalise value = “{!name}” var = “a”>{!a}

</apex:datalist>

</apex:pageblock>

</apex: page>

 

MAP:-

AMAP is a collection of key-values pairs where each unique key maps to a single value. Keys and values can be any

Data type – primitive types, collections, Objects, uses-defined types, and built-in Apex types.

For Eg, the following table represents a map of countries and currencies.

 

 

 

 

 

Clear (): – Remove all the key-value mappings from the map.

Clone (): -Make a duplicate copy of the map.

Contains key (Object): -Return true if the map contains a mapping for the specified key.

Deep c lone(): – Makes a duplicate copy of a map, including Sobjsct record if this is a map with the Sobject

Record values.

Equals (Map) :- Compares this map with the specified map & returns if the both maps are equal. otherwise return false.

Get (Object): -return the value to which the specified key is mapping, or null if the map contains no values for this key.

Get the SObjetc type (): – Returns the taken of the Sobject type of the Sobject type that makes up the map values.

Hand code ()- returns the hash code corresponding to this map.

IsEmpty (): – Returns true if the map has zero key-value pairs.

Key Set (): – Returns a set that contains all of the keys in the map.

Put (Object, Object): – Associates the specified values with the specified key in the map.

PutAll (map): -Copies all of the mappings from the specified map to the original map.

PutAll (Sobjects[]): – Adds the list of Sobject records to a map declared as

Map<ID,Sobject> or Map<String, Sobject>

Remove (Key): – Removes the mapping for the specified key for the map, if present, and returns the corresponding value.

Size (): – Returns the no. of key-value pairs in the map.

Values (): – Returns a list that contains all of the values pairs in the map in arbitrary order.

Set of the key: – Key can’t be duplicate.

List of values: – It allows duplicates.

Map<Integur, string> my = new Map<Integur, string> ();

Set <Integur> keys = List<string> values

Void put (key, value)

m.put(1, ‘sam’);

m.put(2,’Ram’);

m.put (3,Kumar’);

{1-‘sam’, 2-‘Ram’, 3-‘Kumar’}

*Sobject get (key) when we give key it will return values.

String X = m.get (1) – sam

String Y = m.get (3) –kumar.

*Set <Sobject> keyset (): – If we use this method we will get a set of keys.

Set <Integer> S = m.keyset(); -{ 1,2,3}

*List <Sobject> values () :- It will return list of values in the map.

List<string> val = m.values() ;-{‘sam’,’ram’,’kumar’}

Public List<string< myresult {get; set;}

Map<String, String> my map;

Public Map Example()

{

Myresult = new list <String>();

Mymap = new map<String,String>();

Mymap.put (‘Hyd’,’Satish’);

Mymap.put (‘warngal’, reddy’).

Mymap. Put (‘Karimnagar’, ‘chaitu’);

}

Public page reference show () [

Myresult.clear();

Set<String>keys = Mymap.key set ();

Myresult.add All (keys);

Return null;

}

Public page reference display ()

{

Myresult = mymap.values ();

Return null.

}

}

Map<String, List<String >> my branches = new Map<String, List<String>> ();

List<String> hyd = new List <String> ();

Hyd.add(‘SR’);

Hyd.add(‘Ib’);

My branches.put(‘Hyd’, Hyd);

List <String>War = new List <String>();

Hyd.add (‘Kazi’);

Hyd.add (‘bhalampali’);

My branches.put(‘War’, War);

My branch.put (‘War’, War);

List<String> adi = new List<String>();

Adi.add(‘Manchiyarl’);

Adi.add (‘godaveri’);

Mybranches.ass(‘adi’, adi);

Set<String> keys = Mybranches. Keyset ();

For(string S .keys)

{

Selectoption OP = new SelectOption(S,S);

}

List <String> Val = mybranches.get(city);

Public Class DependExample {

Public pagerefeance show (){

List<String>bran = mybrances.get(mycity);

Branch.clear();

For (String X: bran)

{

Select option opl = new selectoption(X,X );

Branch .add (opl);

}

Return null;

}

Apex Class:-

Public sting mycity {get;set;}

Map<String, List<tring>>mybranches = new map <String, List<String>>();

Public List<Selectoption> city {set; get;}

Public List<Selectoption>branch{Set; get;}

Public DepenExample ()

{

List<String>hyd = new List<String> ();

Hyd.add(‘srnagar’);

Hyd.add(‘/bnagar’);

List<String> bang = new List<String> ();

Bang.add(‘Ecity’);

Bang.add(‘Marthali’);

Mybranches.put(‘hyd’,hyd);

Mybranch.put(‘Bang’,bang);

Set<string>keysset();

City = new List<Selectoption> ();

Branch = new List <selection> ();

City.add(new selectoption(‘null’,’none’));

List<String> my = new List<String> ();

My.add(‘None’);

For (String a: keys)

{

Selectoption opl = new selectoption(a,a);

City.add(opl);

}

}

}

VFpage :-

<apex:pagecontrollar = “Depend Example”>

<apex:form>

<apex:SelectList value = “{!mycity }” size = “1”>

<apex:selectoption value = “{!city”></apex:selectoption>

<apex:actionsupport event = “Oncharge” action = “{! Show}”

Rerendur = “One”/>

</apex:selectlist>

<apex: SelectList size = “1” id = “one”>

<apex:Selectoptions value = “{!branch}”>

</apex:selectoptions>

</apex:selectList>

</apex:form>

</apex:page>

Example  :-

Apex Class:-

Public class List maps controller s{

Public Map<String,String>inputfields{get; set}

Public List Maps controller (){

Inputfields = new map <String, String> {

‘first name’ – ‘Jonny”, “last name’ –‘Applessed’, ‘age’-

42};

}

Public page reference submit Field data (){

Do something Interesting with Input ();

Return null;

}

Public void do something Interesting with Input ()

{

Input fields .put (‘age’,(intrger . value of(Input fields.get (‘age’))

+10).format ());

}

}

<apex:page contollas = “Lists maps controller”>

<apex:Outputpanel id = “box” layout = “block”>

<apex:page message/>

<apex:form>

<apex:repeat value = “{inputfields}” var = “field key”>

<apex:outputtext value = “!fieldkey}”/>

<apex: inputtext value = “{!inputfields[fieldkey]}”/><br/>

</apex:repeat>

<apex:commamd button action = “{!submitfielddata}”

Value = “submit” id = “button” rependur = “box”/>

</apex:form>

</apex:output panel>

</apex:page>

 

SOQL QUERIES:-

Salesforce Object query language is used to query the record from thedatabase.com based on the

There are 2 types of SOQL statements.

1.    Static SOQL

2.    Dynamic SOQL

 

1.Static SOQL: – The Static SOQL statement is written in [](array brackets)

* This statement are similar to LINQ.

Eg: – String search for = ‘Jones’;

Contact [  ]contacts =  [ select testfield — C, First name,

Last name from contact where

Last name = :serch for];

2. Dynamic SOQL: -It is used to refer to the creation of an SOQL string at the run time with Apex code.

* Dynamic SOQL enables you to create a more flexible application.

*To creat dynamic SOQL query at the run time use data base. Query () method, in One of the following ways .

*Return a single Sobject when the query returns a single record.

Sobject S = database. Query (String_limit-1);

*Return a list of Sobject when the query returns more than a single record.

Examples:-

Eg 1:-

String my test string = ‘testname’;

List <Sobject> L = Database.Query(‘SELECT Id form

My customer _(WITERE Name =: my test string);

Eg 2:-

String resolved field 1 = my variable.fild_ _ c;

List <Sobject> L= Database.Query(‘SELECT ID From my customer object – -C

WHERE field 1__ C = rasloved field 1);

 

Syntax of SOQL query: –

SELECT field1, field2 ………

From Object Type

[WHERE condition]

Examples:-

SELECT ID, NAME

List<Account> acc = [Select Id, Name from Account];

List<Account>acc = [Select id, Name from Account where annual revenue <1000>];

 

 

Q) Write a query to fetch customer Name, Balance from customer Object where the balance is more than 100,000.

List<customer – -C> customer = [Select Id, Customer _Name _ _C, Balance _ _ from customer _ c

Where Balance_ _ C> 100,000]

Q) Write a query to fetch TID, Type _ _C from a transaction if made is ‘cash’.

List<Transaction _ _ C> tra = [Select Name, Type _ _ C from transaction _ _ C where Mode _ _ = ‘cash’];

 

Querying Multi select Pick list Values:-

When you want to write a query with a condition based on multi selection picklist in which multiple item value are selected then we can use the following operators to write the condition.

Note: – First Let us creat proof field with data type multi selection with the values

1. Pass Port

2. Aadhar card

3. Voter ID

4. Pan Card

Q) Write a query to fetch all the Customer names & account types who has submitted PAN Card as a proof.

List <Customer –c> Customer = [Select id, customer name – -C, Account –Type- -C from Customer – – C

Where proof – – C = ‘Pan Card’];

Q ) Write a query to fetch customer name, balance from customer object where the proof is Pan Card or Aadhar card.

Note: –

When you want to verify whether the value what we have selected is in the list or not by using INCLUDES.

List <customer _ _C> Customer = [Select customer _ Name _ C,

Balance _ _C from customer _ _ C Where proof _ _C INCLUDES

(‘Aadhar Card’, ‘ Pancard’)]

 

Q ) Write a query to fetch the list of Id’s & customer names from customer Object where proof is Aadhar

Card or Pass Port and Voter Id .

When you want to verify whether we have selected more than one value then use ‘; ‘

Proof _ _C =: ‘Passport; Voter id’

List <customer _ C>Customer = [Select customer – Name – c, Balance _ _ C from Customer _ _ C

Where Proof_ C INCLUDES (‘Aadharcard ‘, ‘Passport; Voter id’)];

 

LIKE :-

The expression is true if the value sp in the specified field name matches the characters of the text sting in the specified value.

*The LIKE operator in SOQL and SOSL is similar to the LIKE operator in SQL.

It provides a mechanism for matching partial text strings and includes support for Wild cards.

*The % and – Wildcards are supported for the LIKE operator.

*The % Wild card matches zero or more characters.

*The text string in the specified value must be enclosed in single quotes.

*The LIKE operator is supported for sting field only.

*The LIKE operator performs a case insensitive match, unlike case sensitive match in SQOL.

Eg: – SELECT Account Id, First name, Last Name

FROM Contact

WHERE Last Name Like ‘ appl_ %’

IN :-

If the value equals any one of the specified values in a

WHERE  Clauses.

Eg: -SELECT NAME FROM ACCOUNT

WHERE Billing state In. (‘California’, ‘Newyork’)

 

NOTING  :-

If the value does not equal any of the specified values in a WHERE Clause .

Eg: –    SELECT Name FROM Account

WHERE Billing state NOT IN (‘California’, ‘New york’)

SUBQUERY :-

The query within a query is called Sub query.

Eg 1: – Write a query to return a list of Accounts that do not have any open opportunities.

SELECT ID

FROM Account

WHERE Id NOTHIN

(

SELECT Account Id – Account Id is a lookup field in the opportunity.

FROM Opportunity

WHERE IS Closed = false

)

Eg 2: –    SELECT Id

FROM Opportunity

WHERE Account Id NOT IN

(

SELECT Account Id

FROM Contact

WHERE Lead source = ‘Web’

)

NOTE: -Whenever we create a master details or lookup field.

The id of the master record is stored in this field.

DATE FORMATS:-

When you want to use the date formats in the query , it should be any one of the below formats.

Format                                                   syntax                                                    Example

Date only                                              YYYY-MM-DD                                       1991-01-01

Date, time &                                      YYYY-MM-DD hh:mm:ss+hh    1991-01-01 723:01:01+01:00

Time zone offset                            YYYY-MM-DD hh:mm:ss+hh:mm

 

LIMIT  :-

Use LIMIT to specify the maximum number of rows to return.

Syntax:-

SELECT field List

From Object type

[WHERE Condition Expression]

LIMIT number _ of _ rows

Eg: -SELECT Name

FROM Account

WHERE Industry = ‘media’ LIMIT 125

NOTE: -you can’t use a LIMIT clause in a query that uses an aggregate function. But does not use a GROUP BY clause.

For example, the following query is invalid.

SELECT MAX (created Date)

FROM Account LIMIT 1

OFFSET  :-

Use OFFSET to specify the staring row offset into the result set returned by your query.

*Using OFFSET is helpful for paging into large result sets, in scenarios where you need to quickly jump to

A particular subset of the entire results .

SYNTAX:-

SELECT field List

FROM Object Type

[  WHERE Condition Expression ]

ORDE BY field order By List

LIMIT number _ of _ row _ to _ return

OFFSET number_of_rows_ to _skip

Eg :-

SELECT Name

FROM merchandise _c

WHERE piece _ C> 5.0

ORDER BY Name

LIMIT 100

OFFSET 10

GROUP BY:-

With API version 18.0 and later, you can use GROUP BY with aggregate functions, such as sum() or

MAX (), to summarize the data and enable you to rollup query results rather than having to process the individual records in your code .

Syntax :-

[GROUP BY field GROUP BY List]

Eg 1:-

SELECT Lead source FROM Lead.

Eg 2:-

SELECT Lead source, COUNT (Name)

FROM Lead

GROUP BY Lead source .

Eg 3:-

SELECT Lead source

FROM Lead

GROUP BY Lead source .

Note: -You must use a GOUP BY clause if your query uses a LIMIT Clause and an aggregated function.

Eg: – SELECT Name, Max (created Date)

FROM Account

GROUP BY Name

LIMIT 5

GROUP BY ROLLUP:- This allows the query to calculate subtotals so you don’t have to maintain that

The logic in year code .

 

Syntax:-

[GROUP BY ROLLUP ([Field Name1, Field Name 2, Field Name 3])]

 

Eg: – Rolls the results up by one field

SELECT Lead source, COUNT (Name) cnt

FROM Lead

GROUP BY ROLLUP (Lead source)

Eg 2: –   Rolls the results up by two fields

SELECT Status, Lead source, COUNT (NAME)CNT

FROM Lead

GROUP BY ROLLUP(status, Lead source)

GROUP BY CUBE: – this is particular useful if you need to compile cross- tabular reports of your database

GROUPBY CUBE with an aggregate functions, such as sum() and COUNT(field Name)

Syntax:-

[GROUP BY CUBE ([ Field Name 1,field Name 2 , Field Name 3])]

Eg: -Return subtotal of accounts for the combination of type & Billing city.

SELECT TYPE, Billing country,

GROUPING (TYPE) grp type, GROUPING(BILLINGCOUNTRY) grpety,

COUNT (Id) accts

FROM Account

GROUP BY CUBE (Type, Billing country)

ORDER BY GROUPING (Type), GROUPING (Billing country)

 

HAVING: – With API version 18.0 and later, you can use a HAVING Clause with a GROUP BY clause to

Filter the results returned by aggregate functions, such as sum ().

SYNTAX:-

[HAVING having condition Expression]

Eg 1: – Determine how many leads are associated with each lead source.

SELECT Lead source, COUNT (Name)

FROM Lead

GROUP BY Lead source

Eg 2:   Generate more than 100 Leads

SELECT Lead source, COUNT (Name)

FROM Lead .

GROUP BY Lead source

HAVING COUNT (Name)>100.

Eg3: -Returns Account with duplicate names.

SELECT Name, COUNT (id)

FROM Account

HAVING COUNT (ID)>1

 

RELATIONSHIP QUERIES:-

When you want to write a queries based on the parent-child relationship will be using relationship queries on standard & custom objects. T

*There are two types of relationship queries.

1. Child to parent relationship

2. Parent to Child relationship

 

  1. Child to Parent relationship:-

 

 

 

 

•    In the above diagram, Contact is a child of Account Object.

•    In the child to parent relationship name will be parent object which means the foreign key is in Account object.

Eg1:-

SELECT Contact.First Name, contact. Account.name from the contract

Eg 2: -Write a query to fetch List of contact  and Account names from contact Object where Account.

Industry = ‘ Media’ .

SELECT ID, NAME, Account , name FROM contact

WHERE Account .Industry =‘ Media ‘.

Child to parent on custom Objects:-

 

 

 

 

Note: – When we use relationship name for the customer objects in SOQL query we should append object Name  – -r to the relationship name.

Eg :-

List<child – – C> ch = [Select Id , Name , parent – r. Frist Name, Parent – -r. Last name –c from child_ _C

Where age _ _C<25];

 

 

 

 

Note: – When you are writing a query from child to parent relationship always relation name will be a master – detail field name (or) lookup field name.

Q: – Write a query to fetch the list of transactions along with Account type and customer name whose transaction type is the deposit.

Note: – Master –detail field in the transaction is customer details _ _ C

List <Transactions _ _C > tr = (Select id, Customer Details _ _ r.

CName _ _C, Customer Details_ _ r.Account type _ _ C, ma,e from

Transaction _ _ C];

Write an apex program to display first five contact details from contact object along with Account Name and industry.

Apex Class:-

Public class child-parent {

Public page reference show ()

{

Cont = [ Select id, Name , account .name, Account.industry from contact Limit 5 ];

Return null:

}

}

V f Page:-

<apex:pagecontroller = “child parent “>

<apex: form>

<apex:PageBLock rendered = “{!Not (Is NULL (cont ))}”>

<apex: Page Block table Value = “{! Cont} ” var = “a” >

<apex:column value = “{! a.name}”/>

<apex:Column Value = “{! a.Account .name}”/>

<apex:column value = “{!a.Account .Industry}”/>

</apex: Page Block Table >

< /apex:page block>

<apex: command button Value = “click” action = ” {! Show}”/>

</apex: from>

</apex: page >

 

 

Apex – 1

Long: – A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and a maximum value of 263-1

Eg: -Double d = 3.14159;

 

Decimal: – A number that includes a decimal point Decimal is an arbitrary precision number. the currency field is automatically assigned the type decimal.

Eg :- Decimal dec = 19.23;

Null variable: – If we declare a variable and don’t initialize it with a value, it will be null.Null means the absence of a value we can also assign a null to any variable declared with a primitive type.

Both of these Statements result in a variable set to null;

Boolean X = null;

Decimal d;

String: – Strings are set of character and are enclosed in single quotes. they store text values such as a name  or as the address.

Eg:- Date d1 = Date today ();

String S = String value of (d1);

The o/p of above example should be today’s date 2013-06-16.

 

SObject types:-

A Sobject, can be genetic Sobject or be a Specific Sobjects,

Such as an Account, contact, or My custom __ C.

•    Sobjects (short for “salesforce Objects “) are standard or custom objects that stores record data in the force. Comdatabase . These are also an Sobject data type in Apex that is the programmatic representation of these Sobject and their data in code.

•    Developers refer to Sobject and their fields by their API names.

Eg :- Account a = new Account ();

Mycustomobject_ _ C  co = new My custom object _ _ C));

*API name of the custom object.

* The following example creates an invoice statement with some initial value for the description

__ Canfield and assigns it to variables of a type also.

Eg: – Invoice –Statement _ _ C, Inv – new Invoice – Statement __C

(Description _ _C = ‘Test Invioce’,Status _  _C = ‘Pending’)

*Sobject variables are initialized to numb, but can be assigned a valid object reference with the new operator.

Q: – Write an apex program to display the transaction details along with customer name, Account type,

City using transaction object.

Apex Class:-

Public class child-parent

{

Public List <transaction – -C> tran {get ; set; }

Public page reference show()

{

Tran = [select type _ _r, Customer_Deatails _ _ r.

Account_Type _ _ C, Cuastome _ Details _ _ r. Customer _Name _ _C,

Customer _Details _ _ R. City _ _ C from Transaction _ _C];

Return null;

}

}

Vf page:-

<apex:page controller = “Child parent “>

<apex:form >

<apex:command Button value = “Click ” action = “{ ! sho }”/>

<apex:pageBlock>

<apex:pageBlock Table value = “{! a. customer_Deatails _r.

Customer _Name _ _ C}”/>

<apex:column value = “{!a customer _Details _r.Account _Type _ _ C}”/>

<apex:column value = ” {!a.customer _Deatails _ _r .City _ _ C}”/>

<apex:pageBlocktable>

</apex:pageblock>

</apex:form>

</apex:page>

 

Parent to child relationship on Standard objects:-

When you are trying to write a query to refer the child object records from the parent object then the

Child object name would be the relationship name.

*the child object name should be referred from with plural name

 

 

 

 

SELECT Account.Name (SELECT .contact.First Name,Contact .LastName FROM Account .contacts)

FROM Account .

Eg 1:-

SELECT Name,

(

SELECT Last Name

FROM Contacts

)

FROM Account

Eg 2: – SELECT Amount, Id, Name,

(

SELECT Quantity, List price,

Price book Entry.unit price, price book entry .name

FROM Opportunity Lin Items

)

FROM OPPORTUNITY

Eg 3: – SELECT Amount, Id, Name,(SELECT Quantity, List price,

Price Book Entry. Unit price, price book Entry.Name,

Price BookEntry.Product2. Family FROM opportunity Line Items)

FROM Opportunity

 

Q: – Write an apex program to display the list of accounts along with their corresponding contact details.

Apex class:-

Public class parent-child

{

Public List<Account > acc {get;set ;}

Public page reference show ()

{

Acc = [ select name, Industry, (select assistant Name , E mail from contracts) f

From Account ];

Return null;

}

}

Vf Page:-

<apex:Page controller = “Parent child”>

<apex: from >

<apex: command button value = “Clicl ” action + “{!show}”/>

<apex:dataList value = “{ ! acc}” var = “a” >

<apex:output Label> Account Name : {!a. name }: : :

Account.Indestry {!a.industry}</apex:output Label >

<apex:dataList Value = “{ ! a.contact }” var = “b”>

{!b.Email} – – – {!b.Assistant name}

</apex:dataList>

</apex:data List>

</apex:from>

</apex:page>

 

Q: – Parent to child relationship on custom Objects:-

When you are writing a query to refer custom child object field from the parent-child relationship then went have to append child object plural name – – r.

 

 

 

 

Eg :-

[SELECT Parent Name _ _ C , Age _ _ C , (Select child _Name _ _ C,

DOB _ _ C from child _ _r ) from Parent _ _ C

 

 

 

Q: – Write an Apex program to print customer details along with corresponding transaction details of the customer whose account type is saving.

Apex class

Public Class Parent-child

{

Public List <customer _ _ C > acc {get ; set;}

Public page reference show ()

{

Acc = [ select customer_ name_ _ c ,Account _Type_ _ C,

( select type _ _ C, Amount _C from Transactions _ _r)

From customer _ _ C )];

Return null;

}

}

 

<apex:page controller = “parent child ” >

<apex:from>

<apex: commandButton value = “Click” action = “{! Show}”/>

<apex:pageBlock>

<apex:PageBlock table value = “{!acc}” var = “a”>

<apex:column value = ” {!a. customar _ Name _ _ C } “/>

<apex:column value = “{!a.Account _ Type _ _ C }”/>

<apex:column>

<apex:page Block  Table Value = “{!a. Transactions _ _r }”

Var = “b”>

<apex:column> { ! b. Type __ C } <(apex : column >

<apex: column> {!b.Amount _ _ C} </apex:column>

</apex:pageblocktable>

</apex:column>

</apex:page blocktable >

</apex:pageblock>

</apex:form>

</apex:page>

 

SOSL Statements:-

SOSL Statement evaluates to a list of Sobject , where each list contains the search result for a particular Sobject type. The result list is always returned in the same order as they were specified in the SOSL

*If an SOSL Query does not return any record for a specified Sobject type, the search result include   the empty list for that Sobject.

* For example, you can return a list of account, contacts, opportunities and leads that begin with the

List <List <Sobject>> searchList = [FIND ‘map*’ INALL FIELDS RETURNING Account (Id,Name), Contact,opportunity, Lead];

 

NOTE  :-

The syntax of the FIND Clause in Apex differs from the syntax of the FIND clause in the SOAP API.

1. In Apex, the value of the found clause is demarcated with single quotes.For Eg.

FTND “map* INALL FIELDS RETURNING Account (I d, Name), contact, Opportunity, Lead.

•    In the force.com API, the value of the FIND clause is demarcated with braces.

For Eg:-

FIND {map*} IN ALL FIELD RETURNING ACCOUNT (ID, Name), contract opportunity, Lead.

From search List, you can create arrays for each object retuned

Account [] accounts = ((List <Account>) search List [0]);

Contact [] contacts = ((List <contact >) SearchList [1]);

Opportunity [] opportunities = ((List <opportunity>) search List [2]);

Lead [] leads = ((List <lead > ) search List [3]);

 

DYNAMIC SOSL:-

Dynamic SOSL refers to the creation of an SOSL string at runtime with Apex code.

*Dynamic SOSL enable you to create more flexible applications. For example, you can create a search based on input from end uses, or update records with varying field names.

 

To create a dynamic SOSL query at runtime, use the search query method. For example

List<List<SObject>> myQuery = Search.query (SOSL_ Search_String);

The following example exercises a simple SOSL query String.

String searchquery =’FIND\’Edge*\’ IN ALL FIELDS RETURNING Account (id,name), Contact lead;

List <List<Sobject>> SearchList = Search.query(searchquery);

Dynamic SOSL Statements evaluate to a list of list of sObjects, where each list contains the search results for a particular sObject type the result lists are always returned in the same order as they were specified in the dynamic SOSL query.

The Search query method can be used where every an inline SOSL query can be used, such as in regular assignment statements and for loops.

SOSL Example:

Public with sharing class DeferenceDemoController

{

Public List<opportunity> optyList {get; set;}

Public List<Lead> leadList{get; set;}

Public List<contact> conList(get;set;}

Public List<account> accList{get;set;}

Public DeferenceDemoController()

{

}

Public void sosDemo_method()

{

OptyList = New List<opportunity>();

leadList = new List<Lead>();

ConList = new List <Contact>();

accList =new List <account>();

List <List<Sobject>> SearchList = [FIND ‘test’ IN ALL FIELDS RETURNING Account (ID, Name,type), Contact (name,email),Opportunity (name,stageName), Lead(Company,name,states)];

accList=((List<Account>)SearchList[0]);

conList=((List<Contact>)SearchList[1]);

 

optyList=((List<Opportunity>)SearchList[2]);

leadList=((List<Lead>)SearchList[3]);

}

}

Vf Page:

<apex:page controller = “DeferenceDemoController”>

<apex:from>

<apex:CommandButton value =”Show records using SOSL”  action =”{!sos|Demo_method}”/>

<apex: pageBlock title =”Accounts”>

<apex:pageBlockTable value =”{!accList}” var =”acc”>

<apex: column value =”{! acc.name}”/>

<apex: column value =”{!acc.Type}”/>

</apex:pageBlockTable>

</apex: pageBlock>

<apex: pageBlock title =”contacts”>

<apex: pageBlockTable value=”{!conList}” var =”con”>

<apex:column value ={!con.name}”/>

<apex: column value =”{!con.email}”/>

</apex: pageBlockTable>

</apex:pageBlock>

 

<apex: pageBlock title =”Leads”>

<apex: pageBlockTable value =”{!LeadList}” var =”lead”>

<apex: column value =”{! Lead.name}”/>

<apex: column value =”{! lead. Company}”/>

</apex: pageBlockTable>

</apex:pageBlock>

<apex:pageBlock title =”opportunities”>

<apex: pageBlockTable value=”{!optyList}” var =”opty”>

<apex: column value =”{! opty.name}”/>

<apex: column value =”{!opty.StageName}”/>

</apex: pageBlockTable>

</apex: pageBlock>

</apex: form>

</apex:page>

E-Mail Programming:

When you want to send an email from the sales force to the external system or receiving a mail from the external system to the sales force then we use Email services. There are 2 types  of emails what we have,

Inbound email messaging

Outbound email messaging

Outbound email:

This is used to send an email to the external system using apex code. There are 2 types of outbound Emails.

Single Email Message

Mass Email Message

Note:

Messaging namespace provides classes and methods for sales force outbound and inbound email functionality.

Single Email Message:

This is a instantiates an email object used for sending a single email message.

Syntax:

Messaging.singleEmailMessage mail = new Messaging. SingleEmailMessage ();

This class contains methods of sending the single email message. When we want to send a message first we have to create the object of singleEmailMessage.

The list of methods available in the singleEmailMessage is

setBCC Addresses(String[])

This method will set BCC Address to whom the mail should be sent. We can set up to 25 email address.

Ex: String [] to bccaddress = new String [] {‘a1@gmail.com’, ‘a2@gmail.com’};

Myemail.setBccAddresses (tobccaddress);

SetCCAddresses (String [])

This method will set cc Address to whom the mail should be sent. We can set up to 25 email address.

Ex: String[] to ccaddress = new String[] {‘c1@gmail.com’}

Myemail.setccAddresses(toccaddress)

setToAddresses (String[])

This method will set the address, we can set up to 100 addresses.

Ex: String[] toaddresses = new String[] { ‘abc@gmail.com’,’xyz@gmail.com’};

Myemail.setToAddresses(toaddress);

setSubject (String):

This method will set the subject of the mail

Ex: myemail.setSubject(‘TestEmail’);

setplainTextBody (String):

This method will set the text body of the mail.

Ex: myemail.setplainTextBody(‘Hi Rcp’);

setHtmlBody(String)

This method will set the main body of the mail.

Ex: myemail.setHtmlBody(‘<h1> This is the link for Registration</h1>’);

Example:

Apex class:

Public class mail

{

Public pageReference show()

{

Messaging.singleEmailMessage msg = new Messaging.SingleEmailMessage();

String[] toaddress = new String[] { ‘abc@gmail.com’, ‘xyz@gmail.com’};

Msg.setToAddresses (toaddress);

String[] tobccaddress = new String[] {‘a1@gmail.com’ , ‘a2@gmail.com’};

Msg.setBccAddresses(tobccaddress);

String[] toccaddress = new String[] {‘c1@gmail.com’};

Msg.setCCAddresses (toccaddress);

Msg.setSubject (‘Test’);

Msg.setPlainTextBody(‘Hi RCP’);

Msg.setHtmlBody(‘<h1> This is the link for Registration</h1>’);

Messaging.sendEmail (new Messaging. singleEmailMessage[] {msg});

Return null;

}

}

Vf page:

<apex: page controller =”maileg”>

<apex:form>

<apex : commandButton value =”click” action =”{!show}”/>

</apex:form>

</apex:page>

In the above program when we want to send an Email, we use the following syntax.

Public Messaging. sendEmailResult[] sendEmail(messaging.Email[] emails, BooleanallorNothing)

This method sends list of email objects instantiated with either SingleEmailMessage or MassEmailMessage

In the method, the Boolean parameter is optional. When you give the Boolean value is false, if any one of email is failed it stops processing all other email, if Boolean value is true if any one of the email is failed, it discarded only that mail and the rest of the emails processed as usually.

SenEmailMessage:

Syntax:

Public messaging. sendEmailResult[] sendEmailMessage(List<ID> emailMessageIds, Boolean all or Nothing)

This method sends 10 draft email messages as specified by the email message Id’s.

 

Mass Email Message:

We can send a mass email message to a recipient list that Consists of contacts, leads, person accounts, or users you can view in a sales force.

Messaging. MassEmailMessage:

This class has all the methods defined in the Email class and also Email base class methods.

Methods:

Public void setDescription( String description):

This will give the description about the mail.

Public void setTargetObjectIds(ID[ ] target Object Ids):

We can add up to 250 Ids per email. If you specify a value for the target object Ids field optionally specifies a what Id’s as well.

Public void setWhatIds (ID [] WhatIds):

The values can be any one of the following, contract, case opportunity and product.

Syntax:

Messaging. MassEmailMessage mail = new Messaging. MassEmailMessage();

Example:

Apex Class:

Public class test email

{

Private final List <Id> Contactids;

Public List <Contact> con;

Public testemail (Apexpages.standardController controller)

{

Con = [ select Id from Contact limit 250];

For (Integer i =0; i<250; i++)

{

Contactids.add(con[i].Id);

}

}

Public void sendEmail()

{

Messaging.MassEmailMessage mail = new Messaging. MassEmailMessage();

Mail.setTargetObjectIds(contatids);

Messaging. sendEmail (new Messaging . MassEmailMessage[] {mail});

}

}

Vf page:

<apex: page StandardController = “contact” extensions =”testmail”>

<apex:form>

<apex: CommandButton value =”sendEmail” action =”{!sendEmail}”/>

</apex:form>

</apex:page>

 

Pdf Email File Attachment:

Messaging. EmailFileAttachment:

EmailFileAttachment is used in the single email message to specify attachments passed in as a part of a request in other terms sending file attachments in the email.

Methods:

Public void setFileName( String name):

This method will set the name of the file which we attach.

Public void setBody (Blob, attachment):

This method will set the attachments, when we want to set the attachments in the Blob format, we need to use the Blob methods.

Public static Blob to pdf(String):

This method cast the specified string into pdf format.

Public static Blob Value of (String):

This method cast the specified string into Blob format.

Public String toString(Blob b):

If we give a Blob value it is Converted into String.

Public void setContentType(String):

This will specify the what type of attachment Content we have added.

Public void setInline (Boolean b):

When you give the tree it doesn’t require any action when the content is open.

To attach a pdf file in an email, we have to write the code like below.

Pdf.getparameters().put(‘id’,(String)acc.id);

Pdf.setRedirect(true);

Blob b =pdf.getContent();

Messaging. EmailFileAttachment  myem = new Messaging. EmailFileAttachment();

Messaging.SingleEmailMessage em = new Messaging.singleEmailMessage();

Em.setFileAttachements(new Messaging.EmailFileAttachment[] {myem});

 

Create a visual force page within an attachment pdf

<apex:page  StandardController = “Account” rendasAs =”pdf”>

<apex:pageBlock>

<apex:pageBlockSection>

<apex:outputField value =”{!account.Name}”/>

<apex:outputField value = “{!account.Induetry}”/>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:page>

Write a program to add visual force page as an attachment to mail in pdf format.

Apex Class:

Public class MyAttachment

{

Account act;

Public String myname { set; get;}

Public MyAttachment()

{

Acc = [select id, name from Account where name =: my name limit];

}

Public pageReference Show()

{

Messaging.singleEmailMessage mymail= new Messaginin. SingleEmailMessage();

Messaging.EmailFileAttachment fmail = new Messaging. EmailFileAttachment();

PagReference pdf = page.attachementpdf;

Pdf.getParameters().put(‘id’,(String) acid);

Pdf.setRedirect (true);

Blob b =pdf.getContent();

Fmail.setFileName (‘attachment.pdf’);

Fmail.setBody(b);

Mymail.setSubject(‘MonthBill’);

String toad = new String[] {‘abc@gmail.com’};

mymail.setToAddresses(toad);

mymail.setBody(‘plz find the attachment’);

mymail.setFileAttachments(new Messaging.EmailFileAttachment[] { mail });

Messaging.sendEmail (new Messaging. Email[] {mymail});

Return null;

}

}

Vf page:

<apex:page Controller = “MyAttachement”>

<apex:form>

<apex:inputText value =”{!myname}”/>

<apex:Command Button action ={!show}” value =”Click”/>

</apex:form>

</apex:page>

Sending the documents through mail:

Public void setDocument Attachments (ID[]):

This method will send the document that we got in the salesforce in the email using messaging concept.

Step 1:

Create a document in salesforce

Go to Document object click on a new document.

Enter the name, description of the document.

Select External file, choose the document file and save.

Step 2:

In Apex program write a query to fetch the id of the document where document name =’Satish’.

Attach this document to single EmailMessage

Document d = [Select id from Document where name =’satish’];

Messaging.singleEmailMessage mail = new SingleEmailMessage();

Mail.setDocumentAttachments (new ID[]{d.id});

Example:

Apex class:

Public class mail

{

Public  pageReference Show()

{

Doucment d =[select id from Document where name =’satish’];

Messaging.singleEmailMessage msg = new Messaging.singleEmailMessage();

Msg.setDocumentAttachements(new ID[] {d.id});

Msg.set String[] krish = new String[] {‘abc@gmail.com’};

Msg.setToAddresses(krish);

Msg.setSubject(‘Hi’);

Msg.setplainTextBody(‘Hello’);

Msg.setHtmlBody(‘<h1> How r you</h1>’);

Messaging.sendEmail(new Messaging.singleEmailMessage[] {msg});

Return null;

}

}

Vf page:

<apex:page Controller =”maileg”>

<apex: form>

<apex: CommandButton value =”click” action =”{!show}”/>

</apex:form>

</apex:page>

Inbound Email Service:

Inbound email service is nothing but this will receive a mail from an external system to sales force and the apex class will process the email and attachments and perform requested operation.

To perform this operation, we got some classes defined in messaging namespace.

Messaging.InboundEmail Class:

This class object represents email received by the sales force. This class has following properties.

Public String textAttachments

Public String subject

Public String replyTo

Public String toAddress

Public String plainTextBody

Public String messageId

Public String inReplyTo {get; set;}

This in Replay to a field of the incoming email, identifies the email or emails to which this one is rep (parent emails) contains the parent email or email message.

 

Public String HtmlBodyTruncated {get; set;}

This indicates the whether the HTML body is truncated or not.

Public String CcAddress

Public String fromAddress

Public String fromName

Messaging.InboundEnvelope:

The object of this class stores the envelope information ( From address and To address) associated with the inbound email this class has got two properties. They are

Public String FromAddress

Public String toAddress

Ex: Messaging. InboundEnvelope em = new Messaging. InboundEnvelope();

Em.fromAddress =’xyz@gmail.com’;

Em.toAddress = ‘abc@gmail.com’;

 

Headers:

A list of RFC 2822 headers. In RFC 2822 includes following data.

Received from

Custom headers

Message-id

Inbound Email headers class we have 2 attributes.

The object of this class refers to the header contents of RFC 2822 format. Apart from that it also has 2 attributes. They are,

Name & Value

Messaging. InboundEmailResult class:

The Object of this class is used to return the result of the email service.

Note:  If the object is null the result is achieved to be successful. This class has 2 properties.

1.Public Boolean Success:

This attribute indicates whether the email received was successfully processed or not. In case if the email was not successfully processed, sales force rejects the inbound email and sends the reply to the original setup.

2.Public String message:

This message stores the message written by the sales force in the reply mail.

Any Apex class which want to process Inbound email should implement an interface Messaging. InboundEmailHandles

This interface has a method.

globalMessaging.InboundEmailResult hadleInboundEmail (

Messaging.InboundEmail email, Messaging.InboundEnvelope envelope)

In the above method first parameters, email object stores the email received from email object to the salesforce.

The second parameter stores the to & from address.

Ex: Write a program to handle the inbound email and Create a new task based on the address from which it has received.

Global class Create Task EmailExample implements Messaging.InboundEmailHandler{

Global Messaging.InboundEmailResult hadleInboundEmail (Messaging. inboundEmail email, Messaging. inboundEnvelope envelope)

{

Messaging. InboundEmailResult result = new Messaging. InboundEmailResult();

String ename = email.fromName;

String edescription = email.plainTextBody;

String eindustry = email.subject;

Account a = new Account (name = ename, description = edescription, industry = eindustry);

Insert a;

}

}

Example 2:

Global class createTaskEmailExample implements Messaging. InboundEmailHandler

{

Global Messaging.InboundEmail Result handlkeInboundEmail ( Messaging.inboundEmail email, Messaging.inboundEnvelope envelope)

Messaging.InboundEmailResult result = new Messaging. InboundEmailResult();

Try

{

Contact vcon =[select id,Name,Email from contact where email =:email.from Address Limit1];

Task t = new Task (Description = email. plainTextBody, priority =’Normal’, status =’Inbound Email’,Subject = email.subject, IsReminderSet = true, RemindarDateTime = System.now() +1k, WhoId = VCon.Id);

Insert t;

System.debug(‘New Task object :’ +new Task);

}

Catch (QueryException e)

{

System.debug(‘query Issue: ‘ +e);

}

}

}

Email Service:

Email Service is an automated process that use Apex classes to process the contents, headers, Attachments of Inbound Email.

Note:

Visual Force email templates can not be used for mass emails.

We can associate each email service with one or more sales force generated the email address to which the users can send messages for processing.

Navigation:

Setup > Build > Develop > Email Service > Click on new Email Service.

Give the service name, now select the Apex class to which the mail should be forwarded to process the mail and the class should implement Inbound Email interface.

Select which type of attachment we have to select list of address / domains whenever we want to receive the emails.

Convert text to Binary fields. Click on Active & Save.

Steps to Create Email service:

Go to setup > Develop > EmailServices

Click the new email service button

On the Email Service page, fill the form like below.

 

Email Service Name: Sbx_EmailAWSResponseHandler

Apex Class: Six _ EmailAWSResponseHeader

Accept Attachments: None

Advanced Email Security Settings: (unchecked)

Accept Email From: (Leave blank)

Convert Text Attachments to Binary Attachments (UnChecked)

Active: (Checked)

Over Email Rate Limit Action: Discard message

Deactivated Email Address Action: Discard message

Deactivated Email Service Action: Discard message

Unauthenticated sender Action: Discard message

Enable Error Routing: ( Unchecked)

Route Error Emails to This Email Address: (Leave blank)

4) Click Save and New Email Address button.

a) On the Email Service Address page, fill in the form as follows.

b) Email Address: Sbx_email aws responsehandler

c) Active: (Checked)

d) Context User: (Choose the user that will have full access  to the soap box mailer app, and to all related services)

e) Accept Email From: (Leave blank)

5) Click save.

6) Copy the full email address provided by salesforce, which will be utilized in the next step.

DML Operations:

The operations are

Insert

Update

Delete

Upset

There are two ways to perform DML Operations

By using DML Statements

Ex: List< Account > accList = new List <Account>  ();

accList.add(new Account (Name =’ Acno1″));

accList.add(new Account (Name= ‘Acno2′));

insert accList;

By using Database Class

Ex: List <Account > accList =new List <Account>();

accList.add(new Account (Name =’Accno1′));

accList.add(new Account (Name =’Accno2′));

Database.saveResult [] sr =Database.insert(accList,false);

There is one difference between above two operations.

In the Database class method, you can specify whether to allow partial processing of the records if any errors are encountered.

By parsing the Boolean value as a parameter to Database.insert.

If you give the parameter as true if any error occurs it doesn’t allow the operation to continue.

If you specify false the remaining DML Operations can still succeed, Whereas the insert in DML if any one of the record fails the total operation is discarded.

Ex:

Public pageReference show()

{

List <Account> acc = new List<Account>();

Account a1= new Account (Name =’Today4′ , Industry = ‘Banking’);

Account a2 = new Account (Industry = ‘Banking’);

Account a3 =  new Account (Name = ‘today4′ , Industry = ‘Banking’);

Acc.add(a1);

Acc.add(a2);

Acc.add(a3);

Database.SaveResult [] r =Database.insert(acc, true);

Return null;

}

In the above program when we give Database.insert (act, true), if any error occurs in any one of the records a1,a2,a3 the entire operation of an insert is rolled back.

When you give Database.insert (act, false) for above statements, if any error occurs in any one of the records a1, a2, a3, only that records are terminated and status is saved to save Result class rest of the operation are processed normally.

SOQL DML and loops:

SOQL for loops iterate over all of the SObject records returned by an SOQL query. The syntax of an SOQL for loop is either.

For(variable : [soql- query]

{

Code_block

}

(or)

For (variable_list : [SOql –query])

{

Code –block

}

Ex:

String s =’Bened’;

For(Account a : [select Id, Name from Account where name=:s])

{

//your code

}

Ex: 2

Write a code to fetch a list of accounts whose account name is ‘siebel’ and update them by oracle.

List <Account > accs =[ select Id, Name from Account where name =’siebel’];

// Loop through the list and update the Name field

for(Account a :accs)

{

a.name =’oracle’;

}

// update the database

Update access;

Ex 3:

Write a code a fetch list contacts for a given account and update contact email with account email id.

Account acc = [select email ,(select id, email __C from contacts)

From account where name =’same’ limit1];

List <contact> con =acc. Contacts;

List<Contact> my contacts = new List <Contact>();

For (contact X: con)

{

x.email =acc.email id __c;

myContacts. Add (x);

}

Update myContacts;

Ex 4: Write a code to fetch all the transaction records which are created yesterday and delete them.

List< Transaction __c> tran =[select id from Transaction __C where created date = YESTERDAY];

Delete train;

Ex5: Write a code to create new student records by fetching the data from college object where a branch is CSE.

List <Student __C> std = new List <Student>();

List <College __() > colg = Database. Query(‘select name, Branch__c, year__c   from college__c where branch __c = ‘CSE’);

For (college__c:colg)

{

Student __c s = new Student __c();

s.name = c. Name;

s.Branch __c =c.branch __c;

std.add(s);

}

Insert std;

How to count number of DML Statements in a transaction:

Ex:

Account a = new Account (Name =’sam’, Industry =’Banking’);

Insert a;

Account a1 = new Account (Name =’ram’, Industry =’Banking’);

Insert a1;

 

Ex2:

Void show()

{

Account a = new Account (Name =’sam’, Industry =’Banking’);

Insert a;

Account x =[select id, name from Account Limit1];

x.name =’sam’;

update x;

Account y = [select id, name from Account Limit1];

Delete y;

}

 

Ex3:

Void show()

{

For(integer i =1; i<=100; i++)

{

Account a = new Account (Name =’Sam’, Industry =’Banking’);

Insert a;

}

}

NOTE:

In a single transaction, we can not make more than 150 DML Statements.

Ex4:

Void show()

{

For (integer i=1; i<= 160; i++)

{

Account a = new Account (Name =’sam’ , Industry =’Banking’);

Insert a;

}

}

In the above transaction show, we made 160 DML Statements. So we get an an errors like below.

System.LimitException : Too many DML Statments :151

Errors are in expression ‘{!show}’ in page del Statment Count

 

Bulky the DML Operation:

When we are  performing DML operations on any record we have governors limits of 150 records for every statement.

To support the large number of DML Statements in a single transaction without bypassing the governors limits. To meet this requirement we are nullifying the operation by adding all the records to a list and calling the DML on the list.

Note:

If you all DML Operation on the List object it is Considered as single DML Stamens. This operation is called bullying operation.

Governor limit:

In a single transaction, we can perform DML Operation on maximum 10,000 rows. If you perform more than 10,000 rows it gives an exception like below.

System.LimitException: Too many rows 1000.

Ex:

List<Account> acc = new List <Account>();

For(Integer i=1; i< =4000;i++)

{

Account a = new Account (Name =’usastoday’, Industry =’Banking’);

Acc.add(a);

}

Insert act;

List <Customer__c> acc1 = new List <customer__c>();

For (Integer i =1; i<= 6002; i++)

{

Customer __ c a = new Custome__c (Customer__ Name __C = ‘usustoday’);

Acc1.add(a);

}

Insert acc1;

Return null;

}

 

Interface in Apex:

The interface is a collection of UN implemented methods. This will specify the signature of the method, types of inputs that we pass the method specifies what type is given as an output.

NOTE: Generally the interface methods we give it as global

Syntax: Public interface Exam

{

Account show (String s);

}

All the methods in the interface are public and abstract methods. The interface also contains final static data members.

The class which is implementing this interface should define all the methods in the interface.

Ex:

Interface test

{

Public String show()

Void disp();

}

Global class Example implements test

{

Public String show()

{

Return ‘sam’;

}

Public void disc()

{

Account a = new Account (Name =’sam’);

}

}

If you don’t define any methods in the interface it gives an error. We can create an object for the class.

Class Test

{

}

Test t = new Test();

Interface Demo

{

Void  show();

}

For interface, we can not create an object

Demo d = new Demo(); is not allowed. Because interface Contains only unimplemented methods and static methods.

Class Exam implements Demo

{

Public void show()

{

}

Demo d =e; is allowed. Because ‘e’ is the object of the class which is implementing the demo interface.

 

NOTE:

Interface reference variable can store the object of the class which has successfully implemented an interface.

 

In the above Scenario

Demo d = t; is not allowed. Because test class is not implemented interface demo.

 

Inteface Iterator <AnyType>:

This is the interface defined by the salesforce in an apex. It has 2 methods.

Boolean hasNext()

AnyType next()

1.Boolean hasNext():

This method returns true if there is another item in the collection being traverse else returns false.

2.AnyType next():

Returns the next item in the collection. Both the methods given above should be declared as a global or public.

NOTE:

We can use only custom iterators in the while loop, it is not supported for the loop.

Write a program to create Custom iterator:

Class Satish implements Iterator <Account>

{

Public List<Account> acc;

Public Integer;

Public Satish()

{

Acc = [Select name from Account];

I=0;

}

Public Boolean hasNext()

{

If(i>acc.size())

Return false;

Else

Return true;

}

Public Account next()

{

If(i==0)

Return null;

i++;

return a[i-1];

}

}

NOTE:

Satish s = new satish();

Iterator<Account> it =s;

Since Satish class as implemented iterator interface, we can store the object of the Satish class in Iterator it.

Interface Iterable:

Iterable is an interface in which we have methods.

IteratorClass iterator()

Ex:

Class Ben implements Iterable <Account>

{

Public Iterator<Account> iterator()

{

Satish s = new Satish(); // Satish class is implementing interface Iterato. So we can store this object in interface iterator.

Iterator<Account> it =s;

Return it;

}

}

Ex2:

Class Example

{

List <Account> acc;

Public Example()

{

Acc = new List <Account> ()j;

}

Public pageReference Show();

{

Bened b = new Bened();

Iterator<Account> it = b.iterator();

//Satish s = b.iterator();

While (it.hasNext());

{

Account a =(Account)it.next();

Acc.add(a);

Return null;

}

}

}

Ex3:

Global class satishIterator implements Iterator<Account>

{

Public List<Account> acc;

Public Integer I;

Public SatishIterator()

{

Acc = [ select name from Account Limit 5];

I=0;

}

Public Boolean hasNext();

{

If(i>acc.Size())

Return false;

Else

Return true;

}

Public Account next ()

{

If (i==5)

Return null;

I++;

Return acc[i-1];

}

}

Ex4:

Public class BenedIterable implements Iterable < Account>

{

Public Iterator <Account> iterator()

{

Return new satisIterator();

}

}

Ex5:

Public class ExampleIterator

{

Public List<Account> acc;

Public List<Account> getAcc()

{

Return act;

}

Public Example Iterator()

{

Acc = new List<Account>();

}

Public pageReference Show()

{

Iterable <Account> my = new BenedIterable();

Iterator<Account> test = my .iterator();

While(test.next()!= null)

{

Account a =test.next();

Acc.add(a);

}

Return null;

}

}

Vf page:

<apex: page Controller = “ExampleIterator”>

<apex:form>

<apex: CommandButton value =”Click” action =”{!show}”/>

<apex:pageBlock>

<apex:pageBlockTable value =”{!acc}” var =”a”>

<apex:column value =”{!a}”/>

</apex: pageBlockTable>

</apex:pageBlock>

</apex:form>

</apex:page>

Database.QueryLocator Class:

Database.QueryLoacator Class Stores the records set return by the database. getQueryLocator.

Methods:

There are 2 methods in the QueryLocator class.

getQuery():

Syntax: public String getQuery()

This method returns the query used to instantiate the

Database.QueryLocator object.

This is very much useful when testing the start method.

Ex: Database. QueryLocator dq = Database.getQueryLocator([ select name from Account]);

String str= dq.getQuery();

//Str = ‘Select name from Account’;

iterator():

Syntax: public Database.QuaryLocatorIterator iterator()

This will return the new instance of query Locator Iterable.

Ex: List

Ex:

List<Account> acc = new List <Account>();

Database.QueryLocator dq = Database.getQueryLocator();

Database.QueryLocator.Iterable iq =dq.iterator();

While (iq.hasNext())

{

Account a = (Account) iq.next();

Acc.add(a);

}

 

Batch Apex:

Batch Apex allows you to define a single job that can be broken top into manageable chunks, where every chunk can be processed separately.

Ex:

If you need to make a field update of every record of Account object in your organization, then we have governing limits that would restrict us from achieving the above task.

Reasion:

In a single transaction, we can process only 10,000 records. Now, in the above case if we have more than 10,000 records in the organization then we can not perform this field update.

Batch Apex:

In the Batch Apex, it will fetch all the records on which you want to perform the field update and divide them into the list of 200 records and on every 200 records operation is performed separately.

This would help us to execute on more than 10,000 records as it won’t perform an operation on all the records in a single transaction instead it dividing them into number of subtasks where each subtask may contain the records up to 2000.

Database .Batchable interface:

To use the BatchApex concept, the Apex class should implement Database.Batchable interface.

Database. The patchable interface consists of 3 methods, that must be implemented.

Start Method

Execute Method

Finish Method

Start Method:

Start method is automatically called at the beginning of the batch apex job.

This method will collect the records or objects on which the operation should be performed.

These records are broken down into sub-tasks and given to execute method.

Syntax:

Global( Database.QueryLocator | Iterable <SObject>)

Start (Database.BatchableContext bc)

{}

The return type of the Start method can be

Database.QueryLocator

Or

Iterable <SObject>

Database.QueryLocator:

Use database.QueryLocator as return type to the start method when you are fetching the records using a simple select query.

NOTE: The governing limit says

Total number of records retrived by SOQL Queries 50,000.

Total number of records retrieved by

Database.setQueryLocator  10,000.

But in the Batch Apex the governing limits for SOQL query are bypassed and we can fetch 50 million records using Database.QueryLocator.

Examples:

Global Database. QueryLocator Start(Database.BatchableContext bc)

{

return Database.getQueryLocator(‘select id, name from Account’);

}

Ex2:

Write a start method to fetch all customerName, AccountType from customer object whose AccountType is ‘saving’.

global Database.QueryLocator start(Database.BatchableContex bc)

{

String sql = ‘select id, Customer_name __c, Account_Type_C from customer __C where Account _Type __C = ‘+’\’saving\”;

}

ii)Iterable: use iterable as a return type when you want to use complex logic or scope to fetch the records for the batch job.

Ex: global class MyTest implements Iterable <Account>

{

}

Global Iterable <Account> start (Database.BatchableContext bc)

{

 

Return  new MyTest();

//This should return the object of the class that has implemented an iterable interface.

}

2.Execute Method:

The records which are fetched from the start method are divided into batches of 200 records each. Now every batch of 200 records are separately passed to the execute method separately and the operation what we want to perform on these records written in this execute method.

Syntax:

Global void execute (Database.BatchableContext BC, List<p>){}

This method takes two parameters.

A reference to the database. BatchableContext object.

A list of SObjects such as List<SObject>, or a list of parameterized types.

i.e., Set of 200 records which are passed to the execute method are stored in this list.

3. Finish Method:

When the start method has fetched 1000 records on which we want to perform the operations they are divided into 5 batches/ Groups of size 200.

On every batch to the group, the execute method is called.

Which means execute method is called 5 times.

After executing every group /batch, the governing limits are reset for the execute method.

Once all the batches are executed then finish method will be called to send the email notification or for post execution work.

Syntax:

Global void finish (Database. BatchableContext BC) {}

NOTE: All the 3 methods of the Batchable interface refers to Database.BatchableContext Object. Where this object is used to track the progress of the batch job.

Example:

Write a Batch Apex program to update Account Name within the Account object with suffix Mb. Before the AccountName.

global class AccountBatch implements Database.Batchable<SObject>

{

String Database.QueryLocator start(Database.BatchableContext bc)

{

String query = ‘select id, name from Account’;

Return Database.getQueryLocator(Query);

}

Global void execute (Database.BatchableContext bc, List<Account> scope)

{

List<Account> acc = new List<Account>();

For(Account a:acc)

{

a.name =’Mb.’ +a.name;

acc.add(a);

}

Update act;

}

Global void finish (Database.BatchableContext bc)

{

}

}

Example2:

Write a batch apex program to phone no in the  contact object with the phone no in the corresponding Account object. Where Contact is a child of Account.

Global class contactUpdate implements Database.Batchable<SObject>

{

Global Database.QueryLocator start(Database.BatchableContext bc)

{

String query = select id, phone, Account. Phone from Contact;

Return Database.getQueryLocator(query);

}

Global void execute (Database.BatchableContext bc,  List <Contact> scope)

{

List<Contact> con = new List <Contact>();

For (contact c: con)

{

c.phone = c.Account.phone;

Con.add(c);

}

Update con;

}

Global void finish (Database.Batchable context bc)

{

}

}

How to invoke batch apex job (or) how to execute the batch apex job programmatically:

We can use Database.executeBatch() method to programmatically begin the batch job.

Syntax:

Public static ID executeBatch(SObject className)

Public Static ID executeBatch(SObject className, Integer Scope)

The above two methods are static methods of Database class. We can use any one of the method to execute the batch job.

NOTE:

The class name what we are passing to the

Database.executeBatch() method should be an object of the class which has implemented Database.Batchable interface.

Orders of execution of Batch Apex job when we invoke through Database.executeBatch():

Step1:  Create an object for the class which has implemented Database.Batchable interface.

Step2: Pass this object which you have created in the first step as a parameter to the Database. Batchable interface.

Step3:

When database. executeBatch() method is called it will add the batch job to the queue.

Step4: Once the resource is available in the queue automatically Start() method will be involved and it will collect all the records on which we need to perform the operation.

Step 5: The records that are fetched from the start method are divided into small group / batch of the size given in the Database.execute() method.

NOTE:

In case if you don’t specify the size by default it takes 20000

Step6: On every batch of records execute method will be invoked.

Stpe7:

Once all the batches are executed, then finish method will be called.

NOTE:

Database.execute method is going to return the id of the batch job.using which we can monitor or abort the operation.

All the asynchronous jobs are stored to ‘AsyncApexJob’ object from this we can monitor, no of jobs processed for our asynchronous job and states of the job.

Example:

ID batch processed = Database.executeBatch (reassign);

AsyncApexJob aa = [ select id, status, JobItemsProcessed from AsyncApexJob where  ID=: batchprocessid];

Scenario:

Create a visual force page with Input text button.

When we click the Replace button in the custom visual force page.

Fetch all the records in the customer object with the customers name matching with the name given in the visual force page.

Update their Account Type as ‘saving’ account.

Step1: Create a batchApex class to perform update of the Account Type.

Globat class CustomerBatch implements Database.Batchable<SObject>

{

Public String my name;

Global customerBatch(String my name)

{

This.myname= myname;

}

Global Database.QueryLocatorStart(Database.BatchableContext BC)

{

Return Database.getQueryLocator(‘select id, Account_Type__C from Account where name =’+myname);

Global void execute (Database.BatchableContext bc, List<Customer __C> scope)

{

List<Cusomter__C > cust  = new List <Customer __C>();

For(customer –C c:cust)

{

C.Account__Type__C =’saving’;

Cust.add(c);

}

Update cust;

}

Global void finish (Database.BatchableContext bc)

{

Messaging.singleEmailMessage myemail = new Messaging.singleEmailMessage();

String[] toadd = new String [] {‘abc@gmail.com’};

Myemail.setToAddresses (toad);

Myemail.setSubject(‘Batchprocessed’);

Myemail.setPlainTextBody(‘Batch Completed Successfully’);

Messaging.sendEmail(new Messaging.Email(){myemail};

}

}

Step 2:

Create Apex class to invoke the batch apex job.

Public class TestMybatch

{

Public string cname {set;get;}

Public pageReference show()

{

CustomerBatch mybatch = new CustomerBatch (cname);

Id id = Database.executeBatch(mybatch, 400);

System.debug(‘My job id’+id);

}

}

Step 3:

Create a visual force page to call the TestMyBatch class

<apex:page controller =”TestMybatch”>

<apex:form>

<apex: outputLabel> Enter Name </apex:outputLabel>

<apex: inputText value =”{!myname}”/>

<apex:commandButton value =”click” action =”{!show}”/>

</apex:form>

</apex:page>

Database.Stateful:

Each execution of batch apex job is considered as the discrete transaction. Which means when you have a batch job with 1000 records executed with optional scope of 200 records then

5 batch   Batch1 > 1 -200

Batch2  > 201-400

Batch3  > 401 – 600

When we call execute on batch1 to summarize the value Integer sum =0;

Public void execute(Database. BatchableContext bc, List<Account> scope)

{

For(Account a: scope)

Sum = sum +a.AnnualRevenue;

}

First Batch of 1 -200 records call the execute method: with 200 records.

Before calling execute() : sum =0

After Calling execute() : sum = 20000 (assume it)

When the execute() is called on batch 2 of records 201 – 400 then the Initial value of sum again set to zero.

Before calling execute() on Batch1 : 1 -200 records : sum =0;

After Calling execute() on Batch 1: 1-200 records : sum =30000

Before Calling execute() on Batch2 : 201 -400 records.

First sum is set = 0 again : sum =0

Then again fresh summary value is calculated again.

Which means the state of the batch is forwarded from one execute() to another execute().

If you specify Database.Stateful in the class definition,  you can maintain state across these transactions. This is useful for counting or summarizing records as they are processed. For eq. Suppose your job processed opportunity records. You could define a method in executing to the aggregate total of the opportunity amounts as they were processed.

Global calls summarizeAccountTotal implements Database.Batchable <SObject>, Database.Statful

{

Global final String query;

Global integer summary;

Global summarizeAccount Total(String q)

{

Query = q;

Summary =0;

}

Global Database.QueryLocatorStart (Database.BatchableContext Bc)

{

Return Database.getQueryLocator(query);

}

Global void execute(Database.BatchableContext Bc, List<SObject> scope)

{

For(SObject s: scope)

{

Summary = Integer.valueOf(s.get(‘total __c’))+ summary;

}

}

Global void finish (Database.BatchableContext Bc)

{

}

}

Governing Limits:

Only one batch apex jobs start method can run at a time in an organization.

Up to 5 queued or active batch jobs are allowed for an apex.

The maximum number of batch apex method executions per a 24- hour period is 2,50,000.

The batch Alex start method can have up to 15 query cursors open at a time per user.

A maximum of 50 million records can be returned in the Database QueryLocator object.

The Start, execute, and finish methods can implement up to 10 callouts each.

NOTE:

If we have 1000 records with a scope of 200 records then they are divided into 5 batches.

SO execute() method is called 5 times. Which means in every execute() we call 10 call outs. So in this scenario we call

Start() > 10 callouts

Execute() > 10 * 5 =50 Call outs

Finish ()  > 10 Call outs/ 70 call outs in entire operations

Limitations:

Method declared as future are not allowed in the classes that implement Database. Batchable interface.

Methods declared as future can’t be called from Batch Apex Class.

For sharing re calculation, we recommend that the execute method delete and then re create all apex managed sharing for the records in the batch.

For each 10,000 AsyncApexJob records, Apex Creates one additional AsyncAPexJob record of type BatchApexWorker for internal use.

Apex Scheduler:

It will invoke the Apex class to run at a specific time.

Any body who want to schedule their class they have to implement a schedulable interface.

Schedulable interface:

The class that implements this interface can be scheduled to run at different intervals. This interface has several methods they are

Public void execute (SchedulableContext sc)

 

Ex: public class MySchedule implements Schedulable

{

Public void execute (SchedulableContext sc)

{

Account a = new Account (Name = ‘RCP’)

Insert a;

}

}

 

The scheduler will run in systemContext, which means all the classes are executed whether the user has permission or not.

We can monitor or stop the execution of scheduled apex job using salesforce user interface from a setup.

Navigation:

Setup > Monitoring >Jobs > scheduled jobs

The execute() method must be declared as public or global.

Using system.schedule.

System.Schedule:

Once you are implemented a schedulable interface use system.schedulable method to execute the class

Syststem.Schedule() method takes 3 parameters.

1.Name of the job.

2.An expression that is used to represent time and date of the operation.

3.The object of the class which you want to execute.

* Expression is written in the form of ‘seconds, minutes, hours, day of the month, month day of the week, optional year’.

‘seconds Min Hours DAY-MONTH MONTH DAY-WEEK Optional Year’

0-60   0-60   0-24    1-31   1-12   1-7

 

Special Characters:

?:

Specifies no specific value. This is only available for day of the month and day of the week.

Ex1: Write the expression to schedule an operation 10 the of August at 12.30 PM.

Ans:  ‘ 0  30  20 10 8  ? ‘

‘ 0  30 12  10  AUG ?  ‘

‘0  30  12  10 Aug ? 2013′

Ex2: Write an expression to schedule an operation on Jan Monday 12.30

Ans:

‘0 30 12 ? 1 MON’

‘0 30 12 ? 1 ?’

*:

Specifies all the values.

Ex: Write the expression to schedule an operation on everyday of the AUG at 12.30 PM.

‘ 0 30 12 * AUG ? ‘

‘0 30 12 * 8 ?’

Ex: Expression to schedule on every hour on 10th Aug.

‘0   30  *   10  8  ?’.

L:

Specifies the end of the range. This is available only day of the month or day of the week.

Ex: Write an expression to schedule the operation on last Friday of the March at 10:20.

‘0  20  10  ?   3  6L’.

W:

Specifies nearest week day of the given day this is available for only day of the month.

Ex: If we specify 20W and 20th is a Saturday so the class runs on 19th. If I give 1W and 1st is a Saturday then it runs on Monday, not a previous month.

Ex:

Write an expression to schedule an operation the nearest weekday of March 20th at 10:20.

‘0 20 10 20W 3 6L’

This is to specify the last working day of last week day of last of the month.

#:

This specifies an nth day of the month.

Week –Day #Day_Month

2#2 it will run Monday of every 2nd month.

JAN, MAR means JAN-MAR.

If you want to schedule any operation we have to create an object for the class which has implemented for a schedulable interface.

Class MySchedule implements Schedulable

{

Public void execute(SchedulableContext sc)

{

}

}

MySchedule my = new MySchedule();

String str = ‘0 0 10 * 3 2 ‘;

System.schedule (‘MyJob’,str,my);

Name   Time Format   Object

System.scheduleBatch ():

System.scheduleBatch () is used to run a schedule a batch job only once for a future time. This method has got 3 parameters.

Param1:

Instance of a class that implements

Database.Batchable interface.

Param2: Job name.

Parma3: Time internal after which the job should start execute.

Param4: It’s an optional parameter which will define the number of processed at a time.

The system.scheduleBatch () returns the scheduled job

Id (CronTrigger id)

We can use this job id to about the job.

Example:

You have to first implement the schedulable interface for the class the specify the schedule using schedule Apex page or System.schedule method.

Apex Class:

Global class purge implements Schedulable

{

Global void execute (SchedlableContext sc)

{

List<Credit _Card__C> creditCard = new List<Credit-Card __c> ();

For (Credit_card __c cc: [select Id, Name from credit_card__C where Age __c>2])

{

CreditCard.add (ccc);

cc.cw__C = ‘0000′;

}

Database.update (credit card);

}

}

Example: If we want to schedule

Create an object for the class which has implemented the schedulable interface.

Create the time frame.

Invoke the System. Schedule method with the job name, Schedule Object, timeframe.

 

Global class My Batch implements Database.Batchable<SObject>

{

Global Database.QueryLocator start (Database.BatchableContext bc)

{

Return Database.getQueryLocator (‘select Id, name from Account’);

}

Global void execute (Database.BatchableContext bc, List<SObject> scope)

{

List<Account> acc = new List <Account> ();

For (SObject x: scope)

{

Account a = (Account) x;

a.name =’Mb’ + a. Name;

acc.add (a);

}

Update act;

Global void finish (Database.BatchableContext bc)

{

}

}

global class My Schedule implements schedulable

{

Global void execute (schedulable Context sc)

{

My Batch mb = new MyBatch ();

Database. Execute (my);

}

}

global class Text Schedule

{

Public page Reference show()

{

String timeframe = ‘0 10 8 10 *? ‘;

My Schedule ms = new MyScheule ();

}

}

 

Vf page:

<apex: page Controller =’Text Schedule’>

<Apex: form>

<apex: Command Button value =”Click” action = “{!show}”/>

</apex: form>

</apex: page>

Schedulable Apex limitations:

We can schedule only 100 jobs at a time.

Max number of apex schedule jobs in 24 hours is 2, 50,000 number of jobs.

Synchronous web service callouts are not supported in schedulable Apex.

 

 

 

 

 

Real Time Scenario’s and Use Cases

 

Real Time Scenario 1:

 

Database.Stateful Interface:

I have batch apex code updating two fields in Opportunity line Item (OLI). While I run the code for complete batch the values in the field are updating correctly. However, if I split the batch apex in two or many, I am facing the issue of the last batch value getting updated in Opportunity line item instead of the complete one.

For example:

Global class SummarizeAccountTotal implements Databae.Batchable<sObject> , Database.Stateful{

Global final String query;

Global Map<Id, Account> account map;

Global SummarizeAccountTotal ()

{

Account map = new Map<Id, Account> ();

}

Global Database.QueryLocator start (Database.BatchableContext BC)

{

Return Database.getQueryLocator (query);

}

Global void execute (Database.BatchableContext BC, List<sObject> scope)

{

List<Opportunity> ops = (List<Opportunity>) scope;

For (Opportunity o: ops)

{

If (accountmap.containskey (o.AccountId))

{

Account a = accountmap.get (o.AccountId);

a.Test_Amount __c + = o.Amount;

accountmap.put (o.AccountId, a);

}

Else

{

Accountmap.put (o.AccountId. New Account (Id =o.AccountId.Test_Amount__c = o.Amount))

}

}

}

Global void finish (Database.BatchableContext BC)

{

Try {

Update account map values ();

}

Catch (Exception Ex)

{

System. Debug (Ex);

}

}

}

 

Testing:

If you want to validate whether the application what we have created is working as expected.

There is two sales force user interface.

Testing bulk functionality (up to 200 records can be passed through your codes)

Before you deploy your code or package to the Force.com

App exchange the following conditions should be satisfied.

At Least, 75 % of your Apex Code must be covered by unit test.

All the test cases will be successful.

Note:

When you deploy any code production will be executed.

Test methods and the test classes are not past of Apex code coverage.

Every Trigger must have some test case.

All classes and Triggers should compile successfully.

What are the factors that concern to be tested in Apex Programming?

1. Single Action:

This is to test a single record, produces the correct expected result.

2. Bulk Actions:

Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only the single record case but the bulk cases as well.

3. Positive behaviour:

Test to verify that the expected behaviour occurs through every expected permutation that is that the user filled out everything correctly and did not go past the limits.

4. Negative behaviour:

There are likely limits to your applications. Such as not being able to add a future date, not being able to specify a negative amount and so on.

5. Restricted user:

 

 

Apex Unit Test:

Unit test is the class methods that verify whether a particular piece of code is working properly or not.

Unit test method takes no arguments and commits no data to the database, will not send any emails.

Test method Keyword:

When you want to create a test method should be prefixed with keyword test method.

All the test methods are static.

Ex: public class myClass

{

Static test Method void myTest ()

{

//Add test method logic using System. Assert (), system.assertEquals ()

//and System.assertNOtEquals () here

}

}

NOTE: Test methods cannot be defined in Apex trigger.

@isTest Annotation:

If you define any method as @isTest then the method is test method just like what we have defined.

If any class is defined with annotation @isTest then that class is defined as test Class.

Ex: @isTest

Private class my class

{

Static testMethod void myTest ()

{

//code-block

}

}

This is the same test class as in the previous example, but it defines the test method with the isTest annotation instead.

Ex2: @isTest

Private class my class

{

@isTest static void myTest ()

{

//code –block

}

}

Note:

A class defined with the isTest annotation don’t count against your organization limit of 3MB for all apex code.

Ex3:

@isTest

Private class MyTestclass

{

// Method for testing

@isTest static void test1 ()

{

//Implement test code

}

}

Test classes must be defined as isTest with access specifies as public / private.

By default access level is private.

Methods of the test class can be called only from the running method.

A test method cannot be invoked in non – test method.

Ex:

ApexClass (TV Remote Control):

Public class TvRemoteControl

{

//Volume to be modified

Integer volume;

//Constant for maximum volume value

Static final Integer MAX_VOLUME = 50;

//Constructor

Public TvRemoteControl (Integer v)

{

//set initial value for volume

Volume = v;

}

Public Integer increase Volume (Integer amount)

{

Volume + = amount;

If (volume > MAX_Volume)

{

Volume = MAX_VOLUME;

}

Return volume;

}

Public Integer decrease Volume (Integer amount)

{

Volume = amount;

 

If(volume<0)

{

Volume=0;

}

Return volume;

}

Public static string getmenuoptions()

{

Return ‘AUDIO SETTING-VIDEO SETTING’;

}

}

Test class:- (true mote control test):-

@istest

Class TVremote control test

{

@ istest static void testvolume increase()

{

Tvremotecontrol .rc=new tvremotecontrol(10);

Integers newvilume = rc.increasevolume15);

Sustem.assarequals (25, newvolume);

}

@istest static void tstvolumedecrease()

{

Tvremotecontrol rc= new Tvremotecontrol (20);

Integer newvolume= rc.decreasevolume (15);

System.assurtequals (5, newvolume);

}

@istest static void testvolumedecrease undermin()

{

Tvremotecontrol rc =new tvremotecontrol(10);

Integer newvolume  = rc.decreasevolume(100);

System.assertequals(0, newvolume);

}

@istest static void testgetmenuoptions()

{

//static method call.no, read to create a class instance

String menu= tvremote control.getmenuoptions();

System.assertnot equals(null,menu);

System.assertnotequals(‘’,menu);

}

}

Note: from ADI 28.0 test methods no longer resides in the non-test class.

Accessing private members of the  class in test class:-

•    Private members of the class can’t be accessed outside the class. This will create a problem in checking private members.

•    If you want to check the private members of the class add annotation @testvisible to before private| protected members of the class.

•    When you keep the annotation 2testvisible before the private  members those are visible within a test class.

Eg:-

Apex class(visible sample class):-

 

Public class visible sample class

{

//private members variables

@testvisible private integer recordnumber =0;

@ testvisible private string areacode = ‘(415)’;

//public member variable

Public integer maxrecords= 1000;

//private inners class

@testvisible class employee

{

String fullnem;

String phone;

//constructor

@testvisible employee(string  s, string ph)

{

Fullname = s;

Phone= ph;

}

}

//private method

@testvisible private string private method(employee e)

{

System.dubug(‘ I am private’);

Recordnumber++;

String phone = area code + ‘ ‘ +e.phone;

String s= e.fullname + ‘\’s phone number isn ‘+phone;

System.debug(s);

Return s;

}

//public method

Public void public method()

{

Maxrecords ++;

System.debug(‘ I am public’);

}

@testvisible private class myexception extends visible sambleclass()

}

Test class(visible sample class test):-

 

// test class for visible sample class

@istest

Private class visiblesampleclasstest

{

//this test method can access private members of another class

 

 

//that are annotated with @testvisible

Static test method void test()

{

Visiblesampleclass sample = new visiblesampleclass();

// access private inner class employee (‘joe smith’,’555-1212’);

//call the private method.

String s = sample.privatemethod(emp);

//verify result

System.assert(

s.contains(‘(510)’) &&

s.contains(‘joesmith’)&&

s.contains(‘555-1212’));

}

Static test method void test()

{

Try

{

Throw new visible sample class myexception(‘trown from latest’);

}

Catch(visiblesampleclass. Myexception e)

{

// handle exception

}

}

Static test method void test3()

{

//access public method

//no @testvisible is used

Visiblesample class sample= new visiblesampleclass();

Sample.publicmethod ();

}

}

Batch apex example with testcase:-

Batch apex class:-

Blobal class batchclass implements database.batchable<subject>

{

Public string query=’select id from account’;

Global databse.querylacator start(database.batchablecontext Bc)

{

Return database.getquerylocator(query);

]

Global void excute (database.batchablecontext Bc,list<subject>scope)

{

For(account a list<account> scope)

{

System.debug(a);

}

}

Global void finish(database.batchablecontext Bc)

{

Sytem.debug(‘finished’);

}

}

Test case:-

Private class testbatchclass

{

Static test method void test batch class()

{

Batchclass bc = new batchclass();

Bc.query = ‘select id from  account limit  ‘200’;

Test.starttest();

Database . excutebatch(bc,200);

Test.stoptest();

}

}

Schedule apex example with test case:-

Batch class:-

Blobal class customer batch implements database.batchable<subject>

{

Global final string query;

Global final string entity;

Global final string fields;

Global final string value;

Global customerbatch(string q,string e, string f, string v)}

Query= q, entity = e; field= f; value= v;

}

Global databse.querylocator start(databse.batchablecontext BC)

{

Return database.getqerylocator(query);

]

Global vod excute (database.batchablecontext Bc, list<subject> scope)

{

For(subject s:scope)

{

s.put(fields,value);

}

Update scope;

}

Global void finish(database.batchablecontext Bc){

}

}

Global class customer schedule implements schedulable

{

Global void execute(schedulable context sc)

{

Customer batch cb= new customerbatch ();

Database.excuebatch(cb);

}

}

Test case:-

@istest

Private class schedule test{

Static test method void my unit test()

{

Test.starttest();

String CRON_EXP = ‘0 00 11 ? 2025’;

String jobid= system.schedule(‘testscheduleapex’, CRON_Exp,new

customerportlrevoke schedulelable ());

contrigger ct =[select id,conexpression,timestriggered.nextfiretime from crontrigger where id=: jobid];

system.assertequals(CRON-Exp, ct.cronExperssion);

system.assertequals(‘2025-01-01 00:00:00’,  string.value of(ct.nextfiretime));

test.stoptest();

}

}

Triggers:-

The trigger is an apex code that executes before or after the following types of DML operations.

•    Insert

•    Update

•    Select

•    Merge

•    Upsart

•    Undelete

Triggers are divided into 2 types.

•    Before triggers

•    After triggers

Before triggers:-

Before triggers can be used  to update or validate values of a record before they are saved to the database.

After triggers:-

After triggers can be used to access field values of the records that are stored in the database and use this values to make changes in other records.

Syntax:-

Trigger triggername on  objectname(triggers_events)

{

Code-block

}

Where trigger_event can be comma separated list of events.

Types of events in the triggers:-

•    Before insert

•    Before delete

•    After insert

•    After update

•    After delete

•    After undelete

Ex:-

Trigger sample on account(before insert,after delete)

{

//code-block

}

Note: – triggers can only contain keywords applicable to an inner class.

•    You do not have to commit the data manually, it automatically saves into database.

Trigger new:-

•    Triggers new is a context variable which contains a list of records which has caused the trigger to fire.

•    Triggers new can be used in the trigger events

  • Before insert
  •    Before update
  •    After insert
  •    After update
  •  After undelete

Note :- there is  no concept called trigger new in delete operations.

Create a table customer:-

CIDNAMEAGEPHONE
111222333aaabbbccc233445123434559876

 

In this object if we are trying to insert new records, into customer object.

 

444          ddd           34          1234555           eee          23           3456

 

Then the new records which we are trying to insert are stored in triggers new in before insert event which means

List< customer—c> cus= triggers.new;

444          ddd           34          1234         555           eee          23           3456

 

 

 

These records are stored into triggers new.

Note :- the records which are stored in the trigger new we can directly perform changes in before insert.

Ex:-   for (customer—c c:triggers.new)

{

c.age—c = 30;

}

Note :- before insert event will occur before new records are inserted into the database. so we can not retrieve the new records using DML operations in before triggers. i.e,

When we have customer table with following records

CIDNAMEAGEPHONE
111222333aaabbbccc233445123434559876

When we are trying to perform insert these two new records

444          ddd           34          1234555           eee          23           3456

 

 

 

If these are any before insert trigger and we have written any DML in it.

Trigger example on Customer –c (before insert)

{

List <customer –c> my=(select cid—c, name, age – c, phone—c from customer –c];

Phone—c from customer—c];

//this query will only fetch their records

111222333aaabbbccc233445123434559876

 

As  remaining two records are not ye inserted.

}

Before insert:-

These triggers will fire when we are trying to insert a new records into a specified objects.

•    Operations which we have written in triggers will be implemented before new records are saved to the  database

•    In before insert, trigger.new stored the list of ew records which we are trying to insert.

Before insert:-

These triggers will be fired when we are trying ti insert a new records into a specified object.

•    Operations which we have written in the trigger will be implemented before new records are saved to the database.

•    In before insert, triggers.new stores the list of new records which we are trying to insert.

Scenario 1:- when we are trying to insert new records into an object. If these are any records existing with same  account name it should prevent duplicate record.

Triggers accountinsert on account*before insert)

{

For(account a: triggers.new)

{

List<account>mynew=[select id,name from account where name=:a.name];

If(mynew.size()>0)

{

a.name.adderror(‘account with name is existing’);

}

}

}

Test case:-

@istest

Public class accountinsert

{

Public class account insert

{

Public static testmethod void testinsert()

{

String  add error;

String myname= ‘madhuri’;

Accunt a2= new account(name=myname);

List<account> X=[select name from account where name=: myname];

If (x.size()<1)

{

System.assertequals(0,x.size());

Insert a2;

}

Else

{

Adderror=’exisisting’;

}

System.assertequlas(‘existig’, adderror);

}

}

Scenario2: – write a trigger to prefix account name with ‘MP’ when even new records are inserted.

Triggers:-

Triggers account prefix on account(before insert)

{

For(account a:trigger.new)

{

a.name=’Mr’+ a.name;

}

}

Testcase:-

@istest

Public class account insert

{

Public static test method void test insert()

{

Account a= new account(name=’sam’);

a.name= ;mr’+a.name;

Insert a;

}

}

Scenario 3:-

Whenever a new record is created in account objects. Before this new record is inserted into account,delete all the contacts records with this account name.

 

Triggers:-

Triggers contactdeletion on account(before insert)

{

List<string>mynames=new list<string>();

For(accounts a:triggers.new)

{

Myname.add(a.name);

}

List<contact>mycontacts=[select  id,name from contact where namein : mynames];

Delete mycontact;

}

Testcase:-

@istest

Public class accountinsert

{

Public static testmethod void testdeletion()

{

String myname=’sam’;

Account a = new account(name=myname);

Contact con = new contract(lastname = ‘sam’);

Insert con;

Contract c= [select id,name from contract where name=:myname limit1];

If ( c!=null)

{

System.assertequals(c.name, a.name);

Delete c;

}

Insert  a;

}

After insert:-

•    This trigger will be fired after new records are successfully saved to the database.

•    We can use a trigger.new to refer to the list new records which we have inserted.

•    On trigger.new, we can only perform read-only operations.

•    On the new list of records, we can perform DML operations.

Note :- on any records that are successfully saved to the database . if we want to perform any changes on those records we have performed DML operations

Eg:-

111222333aaabbbccc233445123434559876

When we insert a new record

444          ddd           32          3456555           eee          56           7655

 

 

 

After triggers will be performed after committing the new records into database which means

 

 

 

 

CIDNAMEAGEPHONE
111222333444555aaabbbcccdddeee233445325612343455987634567655

After saving this records then  after insert trigger will be called, so operation written in the trigger will be performed after records are successfully inserted.

 

Scenario 1:- (Exercise)

Whenever a new transaction is performed successfully then update the customer object balance field based on if transaction     type = deposit, balance= balance + amount;

= withdraw balance= balance – amount;

Note :- customer  and transaction have lookup details relation.

Scenario :-  whenever a new contact is created for an account update the corresponding account phone with new contact phone field.

Trigger:-

Trigger update phone on contact( after insert)

{

List<account> acc=new list<account>();

For(contact c: trigger.new)

{

Account a=[select id, phone from account where id=: Accountid};

a.phone= c.phone;

acc.add(a);

}

Update acc;

}

Test case:-

@istest

Public class testphone

{

Static testmethod void updatephone ()

{

Account a = new accunt (name= ‘sam’, phone=’123’);

Insert a;

Account my=[select id from account where name=’sam’];

Contact c = new contact (lastname = ‘kumar’, account id=a.id, phone=’456’);

Insert c:

Account acc=[select id,phone from account where id =:c.accountid limit1];

Acc.phone= c.phone;

Update acc;

System.assert equals(acc.phone, c.phone);

}

}

Update events in salesforce:-

There are two update events

•    Before update

•    After update

Trigger.old nd trigger.new are in update events in salesforce

•    We have a customer object with the following records

Customer :-

CIDNAMEAGEPHONE
111222333444aaabbbcccddd233427563455234498762346

In the above table when we are trying to update the records

333         ccc              27      9876444         ddd            78      2346

 

333         ccc      29      7654444         ddd       35      1234

 

Triggers.new:-

Triggers.new will strore the set of records on which new values on which yu are performing update.

i.e trigger.new will have

333         ccc      29      7654444         ddd       35      1234

 

 

These two records will store into trigger.new

Trigger.new :-

Triggers will  store the  set of records on which we are performing the update. This store the records with old values.

i.e in the above case trigger.old will have

333         ccc      27      9876444         ddd       78      2346

 

 

 

 

Event:  before update –

Whenever we are trying to update any records in the objects the operations which need to be performed before saving the  change to database are written in before an update.

Eg:-  customer:-

CIDNAMEAGEPHONE
111222333444aaabbbcccddd233427563455234498762346

Step 1:- update these records:-

333    ccc    29    7654

444    eee    35    1234

Step 2:- before update operations are performed

Step 3:-

111222333444aaabbbcccddd233429353455234476541234

 

•    When we modify the value of records and click on update

•    Before trigger will be called on the object and all the operation written it will be performed.

•    Records are updated with new  values in the database

Note :- if we want to make any changes in the values of new records we can directly perform using changes in the values of new records we can directly using trigger.new in before trigger.

•    We can not perform any changes in the records that are in a trigger.new using DML operations as they are not at commited in before  the update.

After update:-

The operations written in the after update trigger will be fired when the changes that we have done are saved to the database.

Ex:-  customer

     CIDNAMEAGEPHONE
111222333444aaabbbcccddd233427563455234498762346

 

Step 1:-

Update these records

333    ccc    29    7654

444    eee    35    1234

     CIDNAMEAGEPHONE
111222333444aaabbbcccddd233427353455234476541234

 

Operations written in after update performed now on the new set of data.

•    When we make some changes on the records of the object and click on update.

•    First before trigger operations are performed on the object.

•    All completing before operations all values in  triggers.new are updated to object.

•    Once records trigger.new are updated to object then after trigger operations are performed.

Note :- in the after update trigger operation we can only read the data from the trigger.

•    If we want to perform any changes on the records in after update trigger we have to write DML statements.

Scenario 1:-

Whenever customer records are updated, before updating the records create new records in test object with old values of the customer record.

Trigger:-

trigger customerupdate on customer_c(before update)

{

List<test_c>test – new list<test_c >c);

For (customer_c x: trigger.old)

{

Test_ c t=new test_c();

t.name=x.name;

t.salary-c= x.salary_c;

t.phone_c = x.phone_c;

test.add (t);

}

Insert test;

}

Testcase:-

@istest

Public class insert customer

{

Static Testmethod void Testcustomer ()

{

Customer_c x=new customer_c();

x.name=’Satya’;

x.salary_c=1000;

x.phone_c=’123’;

insert x;

test_ c t=new test_c();

t.name =x. name;

t.phone _ c= x.phone_c;

t.salary_c=x.salary_c;

insert t;

system.assertequals(t.name, x.name);

sysem.assertequals(t.salary_c, x.slary-c);

x.name=’Satya k’;

x.salary_c=30000;

update x;

}

}

Scenario 2:-

Trigger:- trigger customer on customer_c(before update)

{

List<test_c> test= new list<test_c>();

For(customer_c x : trigger.new)

{

Test_ c     t=new     test_c();

t.name= x.name;

t.salary_ c = x.salary _ c;

t.phone _ c = x.phone_ c;

test.add(t);

}

Insert test;

}

Testcase:-

@istest

Public class insertcustomer

{

Static testmethod void testcustomer()

{

Customer _ c x =new customer _ c();

x.name = ‘satya’;

x.salary _ c = 1000;

x.phone _ c= ‘123’;

insert x;

x.name = ‘satya k’;

x.salary _c = 30000;

update x;

test_ c t=new test _ c();

system.assertequals(t.name, x.name);

system.assertequals(t.salary_ c, x.salary_ c);

t.name = x.name;

t.phone _ c= x.phone _ c;

insert t;

}

}

Scenario 3:-

To update the owner of a case based on the values selected within a pick list and populated the owner field with the created by field data.when we have selected any

Fieldname = status

Pick list values =

Priced –(initial)

Priced –(re-priced)

Price file loaded

Trigger case trigger on case(before update)

{

For (case c: trigger.new())

{

If(c.status ==’priced –(initial)’ || c.status == ‘priced –(repriced) ‘ || c.status == ‘price file loaded’{

c.ownerid = c.createdbyId;

}

}

}

Scenario 4:-

Write a trigger that will prevent a user from creating a load that already exist as a contact. We ‘ll  use the  load/ contacts email address to detect duplicates

Lead is created or updated

•    Lead has an email address

•    Try to find a matching contact based on email address (using SOQL !)

•    If a match is found, give the users an error 4.

•    If a match is not found, do nothing.

Trigger find dupes on lead(before insert, before update)

{

For(lead mylead: trigger.new)

If(mylead.email != null)

{

List< contact> dupes=[select id from contact where email= : mylead.email];

If(dupes ! = null && dupes.size() > 0) {

String errormessage=’ duplicate contact found!’;

Errormessage + =’read Id is ‘ + dupes[0].id;

Mylead.adderror(errormessage);

}

}

}

}

Delete events in salesforce triggers:-

There are two types f delete events

•    Before delete

•    After delete

Trigger.old in before or after delete :- this will store the list of records which are trying to delete.

•    On this records, we can only perform read-only operations.

Customer :-

     CIDNAMEAGEPHONE
111222333444aaabbbcccddd233427353455234498762346

 

•    If we are trying to delete       333 – ccc -27 – 9876

444  – ddd  – 56  – 2346

Then trigger.old will contain their two records.

Scenario 1:-

When we are trying to delete customer record delete all the corresponding child records from a test object. Where the customer is lookup fields in the load object.

Trigger :-

Trigger customerupdate on customer _ c(after delete)

{

List<test _ c> test = [select id from test _ c where cdetails_c in !trigger.old];

Delete test;

}

Test case:-

@istest

Public class test exam

{

Static testmethod void custest()

{

Customer _ c c=new customer _ c(name = ‘satya’, salary _ c =1000);

Insert c;

Test _ c = new test _ c(name = ‘chandu’, cdetails _ c = c.id);

Insert t;

List <test – c> test = [ select id from test _ c where cdetails _ c = : c.id];

If (test.size() >0)

{

Delete test;

}

Delete c;

}

}

Note :- there is no concept called trigger new in  after delete, before delete triggers.

Event: after undelete:-

When we are undelete the records from the recycle bin this operations written in after undeleting will be performed.

Trigger.new:- the records which we have undeleted are stored in trigger.new

Scenario 1:-

When we create the opportunity with probability = 50% then the opportunity owner will be automatically added to account team of the associated account for the opportunity.

Trigger :-

Trigger adds to account on opportunity(after insert,after update)

{

List <accountshare> acc_ share = new list<accountshare>();

List<accountteammember>acc_team=new list<accountteammember>();

For(opportunity opp: trigger.new)

{

If(opp.probabiity==50)

{

Accountteammember team=new accountteammember();

Team.accountid = opp.accountid;

Team.userid = opp.ownerid;

Accountshare share = new accounthare();

Share.accountid = opp.accountid;

Share.accountaccesslevel = ‘read/write’;

Share.opportunityaccess level= ‘read only’;

Share .caseaccesslevel = ‘read only’;

Acc – share .add(share);

Acc _team.add(team);

}

}

If(acc_team !=null)

{

Insert acc _team;

}

If(acc –share != null && acc _share.size() >0)

{

Insert acc _share;

}

}

Scenario 2:- invoking the apex class from the trigger.whenever new customer records is created / updated then  income tax should be calculated based on salary and should be updated to filed ittax(currency field).

Trigger :-

Trigger customer update on customer _ c *(before insert,before update)

{

For(customer _ c cuts:trigger.new)

{

Incometax it =  new incometax();

Cus.ittax _ c = it.calculaed tax(cuts.salary _c);

}

}

Testcase :-

@istest

Public class incometeest

{

Static testmethod void testincome()

{

Customer _ c c +new customer _ c(name =’sam’, salary _ c = 30000);

Incometax t= new incometax ();

c.ittax  _ c= t.calculate tax(c.salary _c);

insert c;

cunstomer _ c cuts= [select id,salary _ c, ittax _ c from customer _ c where id = : c.id};

cuts.irtax _ c= t.calculatetax (cuts.slary _ c)

update cuts;

}

}

Apex class:-

Public class income tax

{

Public decimal tax{ set; get;}

Public decimal calculate tax(decimal amount)

{

If(amount > 5000)

{

Tax= amount * 0.20;

}

Else

{

Tax= amount * 0.10;

}

Return tax;

}

}

Scenario 3:-  before we insert a new record in the customer object calculate the tax dfield value based on salary field value and then insert.

•    If we delete any of the existing customer records then first create new test object records with customer records values then delete customer records.

Apex class:-

Global class trigger example

{

Global static void calculate tax(customer _ c[] cuts)

{

For (customer _ c c: cuts)

{

If (c.salary _ c< 5000)

{

c.ittax _ c= c.salary _ c* 0.10;

}

Else

{

c.ittax _ c = c.salary _ c * 0.20;

}

}

}

Global static void create test(customer _ c[] cuts)

{

List<test _ c>test = new list<test _ c>();

For(customer – c c:cuts)

{

Test _ c t=new test_ c(name=c.name,salary _c= c.salary _c);

Test.add(t);

}

Insert test;

}

}

Trigger :-

Trigger customerupdate on customer _ c(before insert,before delete)

{

If(trigger.isbefore && trigger.isinsert)

{

Triggerexampe.calculatetax(trigger.new);

}

Else

{

If(trigger.isbefore && trigger.isdelete)

{

Triggerexample.createtst(trigger.old);

}

}

}

Test class:-

@istest

Public class triggerexampletest

{

Static testmethod void testtriggerexample()

{

Customer_ c  c=new customer _ c(name= ‘satya’, salary _ c = 40000);

List<customer _ c> cuts = new list<cunstomer _ c>();

Cuts. add(c);

Trigger example. calculateTax(cuts);

Insert cuts;

Test _ c  t=new  test _ c(name = c.name , salary _ c= c.salary.s);

Insert t;

Delete c;

}

}

Usage of trigger.newmap and trigger.oldmap:-

Scenario :-

Whenever we try to update the  phone of account record then update the related contact phone no. with the new account phone no before account record is updated.

When we delete the account record then delete the corresponding contact records.

Trigger contact update on account(before update, after delete)

{

If(trigger.isbefore && trigger.isupdate)

{

Map<id,account>mymap= trigger.newmap;

List<contact> con= newlist<contact>c();

List<contact>cons=[select id, phone,account id from contact

where account id in : mymap.keyset()];

for(contact c: cons)

{

c.phone = mymap.get(c.accountid).phone;

con.add(c);

}

Update con;

{

If(triggers.is after && trigger.isdelete)

{

Map<id,account> deleteacc = trigger.oldmap;

List<contact>mycontact=[select id from conta ct where accounted in :delete.keyset()];

Delete mycontact ;

}

}

Recursive triggers:-

•    You want to write a trigger that creates a new record as part of its processing logic. However, that records  may then cause  another trigger to fire and so on . you don’t know to stop that recursion.

•    We a static variable in an apex class to avoid an infinite loop static variables are local to the context of a web request ( or test method during a call to run tests()).s o all triggers that fire as a result of a user’s action have access to it.

Scenario:-

Suppose there is a scenario where in one trigger perform an update operation, which result invocation of a second trigger and the update operation in second trigger acts as triggering criteria for trigger one.

Class :-

Public class utility

{

Public static Boolean future update;

}

Trigger:-

Trigger update something on account(after insert,after update)

{

/* this trigger performs its logic when the cal is not from @future */

If (utility.isfutureupdate !=true)

{

Set <id> idstoproces = new set<id>();

For (account acct: rigger.new)

{

If(act.numbeerofemployee>500)

{

Idstoprocess.add(acct.id);

}

}

/* sending ids to !future method for processing*/

Futuremethods.processlarge accounts(idstoprocess);

}

}

Class :-

Public class future methods

{

@future

Public static void processlarge accounts(set<id>acct id)

{

List<account>acctstoupdate=new list<account>();

/*isfutureupdate is set to true avoid recusion*/

Utility.isfutureupdate= true;

Update accts to update;

}

}

 

SCENARIOZ:-Recursive trigger error.

to explain about recursive triggerd.

Trigger Recursive on Account (after insert, after update)

{

If (Trigger.is before & Trigger. is Insurt)

{

Account acc = [Select id, Name from Account where name = ‘Madhuri’ limit 1];

Acc.name = ‘Y Madhuri’;

Updata acc;

}

If (Trigger. Is After & Trigger, is Update)

{

A0ccount a new Account (name = ‘Satish’);

Insurt a;

}

 

*The above trigger would generate Recursive trigger error as when you try to update one account record it will call after update trigger on Account object, which would insert new records  into Account object. Which in turn again call after update trigger on Account object? This would continue recursively.

To avoid Recursive trigger error we will use static variable.

Global class Triger var

{

Global static book an flag = false;

}

TRIGGER:-

Trigger recursive on account (after insert, after up Date)

{

If (Trigarvar.Flag! = true)

{

If (Trigger .is before & & Trigger. isInsurt)

{

Trigarvar.flag = true;

Account acc = [Select id, Name from Account where name = ‘madhuri’ limit 1];

Acc.name = ‘Y madhuri’;

Update acc;

}

If (Trigger.isafter & & Trigger. Is update)

{

Triggar Var.flag = True;

Account a = new Account (name = ‘Satish’);

Insert a;

}

}

*In this case the Triggar operation will be executed only when flag vale will be false. Once the trigger is

Executed for the first time the flag values are set to true.

NOTE:-The flag variable should be a static variable.

Q:-Can we call batch apex in the triggers?

A:-Yes, we can call batch apex from the trigger. But sales force allows only 5 batch jobs in the query. So if the trigger raises an error if more than 5 jobs.

Q:-Can we call callouts form the trigger?

A:-We can’t call the callouts directly from the trigger, instead we will define callouts in the future annotated methods & this future annotated methods can be called from the trigger.

NOTE:-We can only call 10 callouts in a single transaction.

Order of Execution in triggers:-

When we save a record with an insert update or upset statement sales force performs the events in

Order because when the event happens, order of execution is very important because they are multiple things field to a single event and when the event gets fired we need to know which processor is running first and which process is running last.

The order of execution is in the following order

  1. Executes all before triggers.
  2. System validations are performed.
  3. Customer validations are performed.
  4. Save the record but does not commit.
  5. Executes all after triggers.
  6. Executes assignment rules.
  7. Executes auto response rules.
  8. Executes workflow rules.
  9. If the record was updated with work flow field updates, fires before and after triggers are more time in addition to standard validations. Customer validations rules are not run again.
  10. Executes escalation rules.
  11. Commits to the data base.

TRIGGER CONTEXT VARABLES:-

There are some implicit variable that are defined with in a trigger .That allows the developers to access run time context.

*These variables are defined in system.Triggers class.

1. Trigger .New:- This stores list of new records of Sobject which were trying to insert in to database or list of records which we are going to update.

*This Variable is available in Triggers whish perform insert events or update events.

*Tr.

2. Trigger.Newmap:- This is a map of IDs as keys the new versions of the Sobject records as values.

Map<Id, Sobject>

These will be available only in after insert, after update and before update triggers.

3.Trigger.old:-Returns a list of the old versions of the Sobject records. (This will store the list of old records with old values .What it has before the operation).

This is available in before update, after update, before delete, after delete.

NOTE:-We can only perform read operation on Trigger. Old records.

Trigger.Oldmap:- A map of ID’s to the old versions of the Sobject records.

Syntax:-Map<ID, Sobject>

Note that this map is only available in update and delete triggers.

Trigger.is Executing :- Return true if the current context for the Apex code is trigger, not a visual force page, a web service or an execute anonymous() API call.

Trigger .isInsert:- Returns true if this trigger was fired due to an insert operation, from the sales force uses interface, Apex, or the API.

Trigger.isInsert:-Returns true if this trigger was fired due to an update Operation, from the salesforce uses interface, Apex or the API.

Trigger.isDelete:-Returns true if this trigger was fired due to a delete operation, from the Sales uses interface, Apex or the Apex.

 

TRIGGERS:-

Scenarios:-

Scenarios 1:-

Create “Sales Rep” Field with data type (Text) on the account object. When we create the Account record, the account owner will be automatically added to sales RCP field. When we update the Account Owners of the record, then also the sales Rep will be automatically updated.

Trigger update sales Rep on Account (Before insist, Before update)

{

Set<ID> SetAccowner = new Set<Id>();

For (Account Acc:trigger.New)

{

Set Accowner.add(Acc.OwnerId);

}

Map<Id,user> user_map = new Map<Id,user>([select Name from user where id in :SetAccownar]);

For (Account Acc: Trigger.New)

{

User = user_map.get(Acc.Owner Id);

Acc.sales_repl _ _ C = usr.Name;

}

}

Scenario 2:-

Create the field called “Contact Relationship “check box on the contact object and create the object called “contact Relationship” which is related list to the contacts.(Lookup Relationship). Now logic

Is when we create contact by checking contact relationship check box, then contact Relationship will be created automatically for that contact.

Trigger Createcponcontact Creation on contact (after insert)

{

If(trigger.is after)

{

If (trigger.isInsert)

{

Contact masterhandler ConIns = NewContactMasterttandler();

ConIns. Create contact Relationship by Contact (Trigger.New);

}

CLASS:-

Public Class Contact Master Handler

{

Public void Create Contact relationshipbycontact (list<contacts> List contacts)

{

List<contact_Relationship _ _ C> conList = new List <contact_Relationship _C> ();

For (Contact newconts : List_ contacts)

{

If(newconts.contact_Ralationship _ _ C = =True)

{

Contact _Relationship _ _ C CR = new contact-Relationship _ _C ();

CR.Name = newconts.LastName;

CR.Contact _ _ C = newconts.id;

ConList.add(CR);

}

}

InsertconList;

}

SCENARIOZ:-

When we change the owner of the contact Relationship, then the owner name will be automatically populated in the Contact Relationship Name Field.

TRIGGER:-

Trigger contactrelationshipmaster trigger on contact_Relationchip _ _ C (Before update)

{

If (trigger.isBefore)

{

If (trigger.isupdate)

{

//Call the handler for the before update trigger event update CROwner Name conrelupd = New update CROwner name ();

Conrelopd.updatecontact relationchipname by owner (Trigger.New);

}

}

}

 

CLASS:-

Public class update Cfomnername {

Public void update contactrelationshipnamebyowner(List<contact _ Relatipnship _ _ C> cont_Rel)

{

Map<Id, Id> map_id_Own = new map<id, id> ();

Map<Id, string> map _id_name = new map<id, String> ();

Set<id>Idset = new Set <id> ();

For (contact_Relationship _ _ C List _recs :cont_ Rd)

{

Idset.add(List_recs.Ownerid);

}

List<user> u= [Select id,Name from use where id in :Idset];

For (user list_user iu)

{

Map_id_Name.put (list_user.id, list_user.Name);

}

If (u! = null & & u.size ()>0)

{

For (contact_relationship _ _ C List_recs; sont tel)

{

If(List_recs.Owner id !=null)

{

List_recs.Name = map_id_Name.get (List_recs.Ownerid);

}

}

}

}

}

SCENARIO 4:-

Create the field called “contact relationship” check box on the contact object and create the object called “Contact Relationship” which is related list to the contacts.(Look up Relationship).

Trigger scenario 12 logic will says then when we create contact by checking contact Relationship checkbox, then contact Relationship will be created automatically for the contact. Now, this logic will for when we delete the contact, then contact Relationship will be deleted automatically.

Trigger deleteCroncontactdeletion on contact (befordelete)

{

If (trigger.isbefore)

{

If (Trigger.isdelete)

{

For (contact:Trigger.old)

{

For (contact C: Trigger.old)

{

Contact_relationship _ _ C CR = new contact_reationship _ _ C ();

Contact_ralationshup _ _ C CR = new contact _ relationship _ _ C ();

CR = [Select Id from contact _Relationship _ _ C .Where contact _ _C Where Contact _ _ C IN: Global utility.

Getenique Ida (Trigger.Old)];

Delete CR;

}

}

}

GLOBAL UTILITY CLASS:-

Public Static Set <Id> get unique Ids (list<Sobject>Sobs)

{

Set<Id> Ids = new set<Id> ();

For(Sobject Sob:Sobs)

{

Ids.add(Sob.Id);

}

SCENARIO 5:-

Create the field called “contact Relationship” checkbox on the contact object and create the object called “Contact Relationship”

Which is related list to the contacts.(Lookup Relationship).

1. Trigger scenario 14 will says that when we delete the contact. Then Relationship will be deleted automatically.

2. Now the logic is when we undelete the contact, then contact Relationship will be undeleted automatically.

Trigger:-

Trigger undeleteCroncontactundeletion on contact (After undelete)

{

If (trigger.isundelete)

{

//call the handler for the after undelete trigger event

Contact MasterHandlar_undelete conIns = NewContactMasterhandlar_undelete();

ConIns.undeleteContactReltionshipbycontact(Trigger.New);

}

}

Class:-

Public class Contact masterHandlar_iudelete

{

Public void undeleted contactelationByucontact(list<contact> List_contacts)

{

Set<Id> ContactIds = New Set <Id> ();

If (List_contacts! = null & & List_contacts.size()>0)

{

List<Contact_Relationshi[ _ _ C> List_Conrets = new list <Contact_Relationship _ C >();

List_conrels = [select id from contact _ Relatipnship_C where is Deleted = TRUE and contact _ _C in:

Global Utility.geteunique Ids (List_contacts);

Undelete List_conRets;

}

SCENARIO 6:-

Created field called “count of Contacts” on Account object. When we add the contacts for that Account then count will populate in the field on Account details page .When we delete the Contact for that Account, then count will update automatically.

NOTE:-The above logic will be applicable when we have lookup relationship. But when we have theMaster_details Relationship, then we can create rollup summary filed to get the count of child record

Using” Count” function.Trigger count of contact on contact (after insert, after delete)

{

Set<id>acid = new set<id> ();

List<contact> Contactlist = new list <contact> ();

List<contact>listcon=newlist<contact> ();

List<account>acclist = new list<account> ();

List<account>listAcc = new list<account> ();

Map<id, integer> mapcount = new map <id, intezer> ();

If (trigger.isinsert)

{

For (contact con:trigger.new)

{

Accid.add(Con.accountid);

}

}

If (trigger.isdelete)

{

For (contact con:trigger.old)

{

Acid.add(con.accountid);

}

}

Acclist = [Select id, Name, account id from contact where account in: acid];

For (account acc; acclist)

{

Listcon.clear ();

For (contact C: Contactlist)

{

If (C.accountid = = acc.id)

{

Listcon.add(C);

Mapcount.put(C.accountid, listcon.Size());

}

}

}

If (acclist.size()>0)

{

For (Account a: acclist )

{

If (mapcount.get(a.id)= =null)

a.count_of_contacts_ _ C = 0;

Else

a.count_of_contacts _ _C = mapcount.get(a.id);

listAcc.add(a);

}

}

If (listAcc.size()>0)

Update list Acc;

}

Future annotation(@future):-

1. Use the future annotation to specify that these methods that are executed asynchronously.

2. Method with future annotation must be static methods.

3. Method with future annotation can only return a void type.

Syntax:-global class className

{

@future

Static void methodname (Parameters)

{

// Body of the method.

}

Eg :- global Class Myfutureclass

{

@future

Static void mymethod(String a, Integer I)

{

System.debug(‘Method called with : ‘+a+’ and ‘+I’);

// do callout, other long running code.

}

}

4.@ future(Callovt = true), this indicates that this future method can use callouts.

Eg:-@ future (Callout = true)

Public static void docallout from future ()

{

//Add code to perform callout

}

5. @ future (Callout = false) this is used to prevent a method from making callouts.

6. The parameters specified must be primitive datatypes, arrays               of primitive datatype or collections of primitive datatypes.

7. Method with the future annotation can’t take Sobjects or objects as segments’.

Imp:-How to pass Sobjects/ Apex Class object as parameters in the  @ future methods.

Step 1:- First create Apex class Address.

Public with sharing class Address

{

Public string street {Set; get ;}

Public string city {set; get ;}

Public string State {set; get ;}

Public string Zip {set; get ;}

Public Address (Stings, string C, String St, String Z)

{

Street = S;

City = C;

State = St;

Zip = Z;

}

}

STEP 2:-Create Address Future Class.

1. Within the constructor create object for Address class and serialize the objects.

2. Create a future method call future (String) With string as parameter in the method descrialize the string to objects and use them.

Public with sharing class Address Future

{

Public Address Future ()

{

List<string> addresses = newList<string> ();

Address Helper ab1 = new AddressHelpers (‘1 here st’,’san Fransisco’, ‘CA’ , ‘941056’);

AddressHelper ah2 = mew Address Helper (‘2 here’,’sanFrancisco’, ‘CA’, ‘94105’);

AddressHelper ab3 = mew AddressHelper (‘3 here st’, ‘sanFrancsico ‘, ‘CA’,’94105’);

//serialize my object ah1, ah2, ah3

addresses.add(JSON.serialize(ah3));

addresses.add(JSON.Serialize(ah2));

addresses.add(JSON,serialize(ah3));

Callruture(addresses);//invoke the future method by passing a string addresses where it a serialized   from of Apex class objects.

}

@future

Static void callfuture(List<String>addresses)

{

Address currAddress = null;

For (string sar ;addresseser)

{

CurrAddress = (Address)JSON.deserialize(ser,AddressHelper.Class);

System.dubug(‘Deserialized in future:’ +CurrentAddress.Street);

}

}

}

NOTE:-

1. No more than 10 method calls per Apex invocation.

2. You can’t call a method annotated with future from a method that also has the future annotation, nor you can call trigger from an annotated method that calls another annotated method.

3. All asynchronous calls made after the start test method are collected by the system. When stop test is executed, all asynchronies process is run synchronously.

APEXPAGE SHATING RULES:-

To share a record programmatically we use Apex sharing (sharing record using Apex).

1. The sharing object is named as object Name _ _ share. Where object name can be a name of customer or standard object.

2. for standard Objects Account.

Object Name                                     Share Object Name

Account                                               Account share

Contact                                                Contact share

Opportunity                                       Opportunity share

3. for custom objects

Object Name                                     Share Object Name

Customer_C                                       Customer_ _share

Staudent_details_C                        Student_datails_share

Sample _ _ C                                      Sample _Share

4. Share Object includes record supporting all 3 types of sharing

a. Force.com manage sharing

b. User managed sharing.

c. Apex managed sharing.

5. Sharing’s are granted to the users implicitly by

a. Organization wide default

b. Role hierarchy

c. New all &modify all permissions.

NOTE:-using share object we can’t track view all data a7 modify all data permission of the object.

*Every share Object has the following properties.

1. Access Level :-This specifies level of access to the granted uses or group on as Object.

Access levels are

Edit

Read

All

Note:-

1. This field must be set to an access level that is higher than organization default access level.

2. Parent Id:-Id of the object on which we are performing sharing.

3. User or Group Id:-The user or Group id’s to which you are grating access the group can be public group, role or territory.

4. Row Cause:-The reason why the user or group is being granted access.

 

Sharing Reason Field:-

1. Force.com Managed sharing:-This involves sharing access granted by the Force.com baesd on role hierarchy, record Ownership and sharing rules.

Reason Field Value                                          Row Caues Value

Account sharing                                                                implicit child

Associated recordOwner                              Implicit Parent

Or sharing

Owner                                                                  Owner

Opportunity Team                                           Team

Sharing Rule                                                       Rule

Territory Assignment                                     Territory Rule

Rule

2. User managed Sharing:-It is also called as manual sharing. This allows record owner or any user with full access to a record to share the record with a user or a group of users.

*This is generally done by an end user for single record.

*All the record owners and users above the owner, the role hierarchy or granted full access.

Reason Field value                                          row cause value

Manual sharing                                                 Manual
Territory Manual                                              Territory Manual

3. Apex Managed Sharing:-Apex managed sharing provides developers with the ability to support an application to share a requirements.

*This type of sharing available to only users with modifies all data permissions. Only this users can add / change apex managed Sharing.

*Apex managed sharing user a share reason (Apex sharing reason).

Steps to create Apex sharing reason:-

1. Setup-Built-Create-Objects.

2. Select the customer object.

3. Click new in Apex sharing reason related list.

4. Enter Label Name:-This label is display in reason column when viewing in user interface.

5. Enter Name:-This name is used when referring the reason in ApI Apexprogramming.

Eg:-If Reason name is ‘Test sharing‘ it is referred in the Apex Program as schema.customobject – – share.Rawcause.Testshaing _ _C.

Schema.custome _ _ share.rowcause.Testsharing_ _C.

Schema.Student _ _share.rowcause.Testsharing _ _ C.

NOTE:-Apexsharing reasons are only available for custom Objects.

Public Class Jobsharing

{

Public static bookan manualshareRead(Id record Id, Id user or groupId)

Job _ _ share jobshr = new Job_ _share ();

Set the ID of record begins shared.

Obshr.parentID = recorded;

//set the Id of user or group being granted access

Obshr.user or group Id = UserorGroupId;

//set the access level

Obshr.AccessLevel = ‘Read’;

//set rowcause to; Manual’ for manual sharing

Jobshr:Rowcause = Schema.Job_ _Share.Rowcause.Manual;

Database.saveresult fr = Database.insest(jobshr, false);

//Process the save result

If (sr.issucess())

{

//Indicates success

Return true;

}

Else

{

Return False;

}

Database.Error err = so.getErrors()[0];

If(err.getstatus code()= =Status code.FIELD_FILTER_VALIDATION_EXCEPTION & &

Err.get Message ().contains (‘AccessLevel’))

{

Return true;

}

Else

{

Return false;

}

  • The following trigger grants the recruiters and hiring manager access when the job record is created. This example requires a custom Object called job, with two lookup field associated with user records called Hiring _Manager Recruiter. Also, the job custom object should have two sharing reasons added called Hiring_Managerand Recruiter.

 

Trigger Job Apexsharing on Job _ _ C (after insert)

{

//Created if (trigger.isInsert)

{

//Create a new list of sharing objects for Job.

List<job_share> jobshrs = new List<Job_share> ();

//Declare variables for recruiting and hiring manager sharing

Job_share recuitershr;

Job_sharehmshr;

For(Job_ _C Job :Trigger.new)

{

//Instantiates the sharing objects

Recruitesshr = new Job_ _ Share ();

Hmshr = new Job _ _share ();

Hmshr = new job _ _share ();

//set the Id of the record being shared.

Recruitershr .Parent Id = job.Id;

Hmshr.Parent Id = job.Id;

//Set the ID of user or group being granted access.

Recruitershr.User or GroupId = Job.recruiter _ _ C.

Hmshr.user or GroupId = job.Hiring _Manager _ _C;

//Set the access level.

Resruitershr.AccessLevel =’Edit’;

Hmshr.AccessLevel = ‘Read’;

//Set the Apex sharing reason for hiring manager and recruiter.

Recuitershr.rowcause = Schema .job_sahre.Rowcause.Hiring_Manager_ _ C;

//Add Objects to list for inset.

Jobshrs.add(hmshr);

}

Database.saveResult[] lsr = Database.insert(jobshrs,false);

}

Flows:-

When the process involves the number of step when the sate need to be transferred between the pages we preferred to use flows.

Navigation:-

Setup-Build-Create –Workflows- Flows-New Flow

We have

  1. Palettes
  2. Resources
  3. Explorer

PALETTSE:-We have

DRAFT TOOLS

USER Interface

LOGIC

DATA

DRAFT TOOLS:-It’s a place holder element which we can use to quickly sketch out a flow and convert into screen element.

SCREEN:-It’s a user facing screen where we can take the inputs and give the outputs .When you click on the screen we are going to get

General Ifo

Add a field

Field Settings

General Info:-

Name of screen:

Unique name of screen:

Navigation options:-No navigation restrictions

Don’t show previous button

Don’t show finish button

Add a field:-

This is to add a field to the screen. The type of fields are Input Field, Choice, Multi-Select Fields and output.

INPUT FIELDS:-

*Textbox

*Long text area

*Number

*Currency

*Data

*Password

*Checkbox

1 .TEXTBOX:-Drag the text box from inputs and drop it into the view screen.

Double click on the text box

Enter Label Name, Unique name*

Input type : Text Box

Default value: We can assign any default value to this field.

Required (v ) by checking this we can make the field required Input Validation

 

 

By Clicking on Input validation we can write the validation rules.

ü  Currency:-Add the currency field to the screen.

Similarly we can create the rest of the input fields given above,

Choice Fields:-

*Radio Buttons

*Dropdown List

RADIO BUTTONS:-Add the Radio button fields to the Screen.

 

 

Creating Choice

Click on Create New

Choice

When you select this you want to shoe come additional fields by checking this check box

When we click on above checkbox we get

 

DROPDOWN LIST:-Dropdown list is nothing but a pick list.

Choice

Create new choice

Logic:-

Decision:-

Write the logical conditions to verify whether the data what we have entered is valid or invalid.

Navigating from one page to another page based on the input what we given.

 

 

DATABASE OPERATIONS FROM VICUALFORCE:-

We can perform record create, record update, Lookup, delete operations on sales force objects form visual force.

Record create:-When you want to create a new record in the flow

Click on –Record create& Enter

Map the fields of an object with the values in the flow.

Once the record is successfully crested it is going to return id of the record store that id to variable so that we can refer to this record with this id in future context.

Record Lookup:-When you want to perform some search operation and fetch the fields.

*Perform search on object based on the input values given in the flow and fetch the record and stored into a variable .so we can use this variables in the flow.

*The records whish are satisfying this filter are fetched and assigned to the variables.

Map the field and variable:

Lookup *

Record Update:-Given filter criteria and select the object. The records which are satisfy the condition are fetched now map field and values.

Record delete:-Select the object then given the filter criteria. The records whish are satisfying the condition are deleted.

Adding flows to visual force page:-

<apex:page>

<apex:sectionHeader title = “user Login” subtitle = “verification”/>

<flow:interview name = “user test”></flow:interview>

</apex:page>

 

Process.Plugin:-

Process.plugin is a built.in interface that allows you to pass data between your organization and specified flow.

The process.Plug interface contains two methods. They are

Describe &

Invoke

Any class which is implementing this interface should define these two methods.

1.*Global Process.PluginResult invoke (Process.Pluginrequest request)

{

}

*This is the first method whish will be invoked by the system when we implement the Plugin.interface.

*This method is used to perform the business logic what we want to implement.

2. Global process.plugindescribleResult describe ()

{

}

*This method defines what type of inputs the plug in requires how many inputs plugin requires and how many outputs it’s going to return.

Process.Plugin Describe result:-

*This clause id used to deter mind the input parameters and output parameters needed by process.plugin result.

*The pocess.plugin interface describe () dynamically provides both input and output parameter for the flow . That’s why the method returns process.plugindescibeesult.

Properties of process.PluginDescriberesult:-

Description:-This is an optional field which will describe about purpose of the plugin.

We can take upto 255 characters.

Name:-It’s the name given for a plugin.

The length can be 40 characters.

Input parameters:-It’s a list of input parameter passed by the process.plugin request class from the flow to the class that implements process.plugin interface.

Syntax:-List<process.plugin describe result.Inputparameter >Inputparameters

Describing the process.describeresult.Inputparameter:-s

Process.Plug inDescibeResult.Inputoarameter One = new

Process.pluginDescriberesult.Inputparameter (name,optional Description,

Process.pluginDescribeResult.parameterType.Enum,bookan_required)

Name:- Name of the input parameter.

Description:-This is an optional field where you can give the description of field.

Parameter type:-This gives the data type of the parameter.

Required:- If it is true input value is required.

Creating the input parameters:-

Process.plugDescribeResult result = new process.plugindescribeResult ();

Result.inputparameter =new List<process.pluginDescriberesult.Inputparameter>

{

New process.pluginDescribeResult.Inputparameter(‘SName’,’Student name’,

process.plugindescribeResult.parameter.Decimal,true)

};

Process.plugDescribeResult.parameter type can take

Boolean

Data

Date& Time

Decimal

Double

Float

Id

Integer

Long

String

Note:-By default every currency Field is a decimal field.

Output parameters:-It’s a list of output parameter passed by the process.PluginResult class to the flow.

Describe process.plugin DescribeResult.output parameters:-Process.pluginDescribeResult.outputparameter(name,

Description,process.pluginDescriberesult.parametertype)

Process.pluginDescriberesult result = new process.plugDescriberesult();

Result.outputparameters = newList<process.pluginDescribeResult.outputparameters

{

New process.piugindescreberesult.outputparameter(‘myval’,’This is result’,

Ptocess.plugindescriberesult.parametertype.String)

};

Process.pluginrequest Class:-

Process.pluginrequest class process the input parameters from the class that implements the interface to the flow.

Syntax:-

Process.pluginrequest(map(string,object))

This going to pass the map objects to flow.

Reading the parameter values from the flow to the plugin:-

Invoke (Process.Pluginrequest request)

{

Data type var = (datatype)request.inputparameters.get(parameterName);

}

Process.PluginResult:-

This class return the output parameter from the class that implements interface to the flow.

Map<string,string>m = new Map<string,string>();

m.put(‘value1’,’sam’);

m.put(‘value2’,’’Ram’);

Process.plugresult pr = new process.pluginresult(m);

Process.pluginresult(string,object)

We can add all the output values that we want to return it to the flow from plugin in the below form.

Map<String,string>m = new Map<string,string>();

m.put(‘value1’,’sam’);

m.put(‘value2’,’Ram’);

Write a plugin program to read the value of subject1 &subject 2 from the flow and calculate the total and return the result as result:-

Global class satyaFlow implements process.plugin

{

Global process.pluginresult invoke (process.pluginRequest request)

{

Integer m1 = (Integer)request.inputparameters.get(‘sub1’);

Integer m2 = (Integer)request.inputparameter.get(‘sub2’);

Interger C=m1+m2;

Map<string,Integer> output = new map<string, Integer>();

Output.put(‘total’,c);

Process.pluginResult result = newprocess.pluginresult(Output);

Return result;

}

Global process.plugindescribeResult describe ()

{

Process.plugindescribeResult result = new process.plugdescribeResult();

Result.Inputparameter =newList<process.plugindescribeResult.inputparameter

>{

New process.pluginDescriberesult.Inputparameter(‘Sub1’,

Process.pluginDescriberesult.parameterType,type’;

New process.plugindescribeResult.Inputparameter(‘Sub2’,

Process.PluginDescribeResult.parameterType,true)

};

Result.outputparameters = newList<process.plugindescribeResult.outputparameter>

{

New process.pluginDescribeResult.outputparameter(‘total’,

Process.plugindesceibeResut.parameterType.Integer,true)

}

}

}

Replace “Decimal” in the place of “Integer” in the above program.

Passing the Values from Visual force to flow:-

When you want to pass the value from visual force to flows use the tag called<apex:param> in between

<apex:page>

<flow:interview name = “usertest “>

<apex:param value = “12” name = “one”/>

<apex:param value = “14” name = “Two”/>

</Flow:interview>

</apex:page>

Overwrite the finish button:-

When you click on the finish button of the flow specify to which page you want to navigate back.

Error:-

An unhandled fault arrow

This is cause when datatype mismatcher

Plugin program:-

Global class satyaflow implements process.plugin

{

Global process.pluginresult invoke (process.pluginRequest request)

{

Decimal m1 = (decimal)request.inputparameter.get(‘sub1’);

Decimal m2 = (Decimal)request.inputparameter.get(‘sub2’);

Decimal c =m1 +m2;

Map<string,Decimal>output = new map<string,Decimal>();

Output.put(‘tatal’,C);

Process.pluginResult result = newprocess.pluginresult(output);

Return result;

}

Global process.pluginDescribeResult result = new process.plugindescribe Result ();

Result.Inputparameter = newList<Process.pluginDescribeResult.

Inputparameter> {

New process.pluginDescribeResult.OInputparameter(‘sub1’,

`               process.pluginDescribeResult.parameterType.Dscimal, true)

New process.plugin DescribeResult.inputparameter(‘sub2’,

processinginDescribeResult.parameterType.Decimal,true)

};

Result.outputparameter = newlist<process.pluginDescribeResult.outputparameter>

{

New pocess.pluginDescribeResult.outputparameter(‘total’,

Process.plugindescribeResult.parametertype.Decimal)

};

Returnresult;

}

}

SELECTOPTION:-

Select option object specifies one of the possible value for visualforce select, checkboxes, select list, select radio component.

It consist of label that is display to the end user, and the value that will be written to the controller.

Note:- The Select option can be displayed in disable state.

Contructors:-

We have 2 constructors in this class.

Instantiating

Selectoption one = new selection (value, label, is disabled)

String    String    String

If isdiesble ie trues, the option is disable we can’t select.

Selectoption one = new Selection (Value, label)

String    String

 

Methods:-

1. String getlabel ()

This method returns the label of the displayed to the user.

Eg:-One.getLabel();

o/p:-One

2. String get Value()

This method returns the value of the object.

Eg:- One.getvalue()

o/p:-One

3. VoidsetDisabled (Boolean)

This will set the value ofIsFisable attribute in the selection.

Eg:-One.setDisable(false);

4. Boolean getDisabled()

This will return the is disable attribute value.

5.Void setLabel(String LabelName)

This will set the value for the given label.

6.Void set value

Selectoption Example program:-

Select Example:-

Public classselect Example {

String [] counteies = new string [ ] {};

Public pagereferance test (){

Return null;

}

Public List<selectoption> getItems(){

List<Selectoption>options =new List<selectoption>();

Options:add(new selectoption (‘US’,’US’));

Options.add(new Selectoption(‘CANADA’,CANADA’));

Option.add(new selectoption(‘MEXICO’,’MEXICO’));

Return options;

Public Sting [] get countries (){

Return countries;

}

Public void set countries (string [] countries){

This .countries = countries;

}

}

<apex:page controller = “Select Example”>

<apex:from> [/sociallocker]