Wednesday, November 30, 2016

How to export data in .csv by using apex code?

public class Cls_RecordsAsCSVExporter {
    public static void mainmethod(){
        List<Account> extractAccountMemList = new List<Account>();
        List<Account> AccList = [select id,name,(select id from contacts) from Account];
        for(Account acc: AccList){
            List<contact> conlist = acc.contacts;
            if(conlist.size() == 0){
                extractAccountMemList.add(acc);
            }
        }
        String generatedCSVFile ='';
        String fileRow ='';
        for(Account acc: extractAccountMemList){
            fileRow ='';
            fileRow = fileRow +','+ acc.Id;
            fileRow = fileRow +','+ acc.Name;
            fileRow = fileRow.replaceFirst(',','');
            generatedCSVFile = generatedCSVFile + fileRow + '\n';
        }
        Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
        Blob csvBlob = blob.valueOf(generatedCSVFile);
        String csvName = 'acc details which doesn ot have contacts.csv';
        csvAttachment.setFileName(csvName);
        csvAttachment.setBody(csvBlob);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'XXXXXXXXX@gmail.com'};
            String subject = 'acc details which does not have contacts CSV';
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody('acc details which does not have contacts CSV');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
    }
}

Open Developer Console and call the mainmethod() it will send all your Accounts which don't have Contacts to mail id which is mentioned in the program.

Sending email with attached document by using Apex

What is Document in Salesforce?
Document object in Salesforce represents a file that user has uploaded. Now this example helps you to understand sending documents as attachment.

How to create a document?

1. Login to Salesforce -> click all tabs (+) and click on Documents tab.
2. Click on new button & enter required fields and upload document and save. See
below image for reference.



To send document as attachment write a query to get the id of the document and pass this id to the “setDocumentAttachments(ID[])” method. setDocumentAttachments(ID[]) is the method in SingleEmailMessage class.

Query to get the id of the document :

Document doc = [SELECT Id,Name FROM Document WHERE Name = ‘DocName’];

Page:

<apex:page controller="SendingDocasattachmentExample">
<apex:form >
         <apex:commandButton value="Send Doc" action="{!sendDocAttach}"/>
</apex:form>

</apex:page>

Controller:

public class SendingDocasattachmentExample{
public pagereference sendDocAttach(){
        Document doc = [SELECT Id,Name FROM Document WHERE Name = ‘Sample’];
        Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
        semail.setDocumentAttachments(new ID[]{doc.id});
        semail.setSubject('Sending Document as attachemnt example');
        String[] sendTo = new String[]{'XXXXXXXX@gmail.com'};
        semail.setToAddresses(sendTo);
        semail.setPlainTextBody('Please find the attached document details');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});

        return null;
     }
}

Sending emails by using SingleEmailMessage

Sending emails: By using Single email message we can send emails.
SingleEmailMessage class contains methods for sending emails. SingleEmailMessage contains below methods.

1. setBccAddresses(String[])
2. setCcAddresses(String[])
3. setCharset(String)
4. setDocumentAttachments(ID[])
5. setFileAttachments(EmailFileAttachment[])
6. setHtmlBody(String)
7. setInReplyTo(String)
8. setPlainTextBody(String)
9. setOrgWideEmailAddressId(ID)
10. setReferences(String)
11. setSubject(String)
12. setTargetObjectId(ID)
13. setToAddresses(String[])
14. setWhatId(ID)

Example Apex Class: Below class is a simple apex program to understand single
email message. I have created vf page with button. & when we click on that button
that calls sending emails method in below class. Try this for sending emails

Page:


<apex:page controller="singleEmailExample">
<apex:form >
             <apex:commandButton value="SendEmail" action="{!sendingEmail}"/>
</apex:form>
</apex:page>

Controller:

public class singleEmailExample{
        public PageReference sendingEmail(){
               Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
               String[] sendingTo = new String[]{'XXXXXXXXXXXXXX@gmail.com'};
               semail.setToAddresses(sendingTo);
               String[] sendingToBccAdd = new String[]{'XXXXXXXXX@gmail.com'};
               semail.setBccAddresses(sendingToBccAdd);
               String[] sendingTocAdd = new String[]{'XXXXXXXXXXX@gmail.com'};
               semail.setCcAddresses(sendingTocAdd);
               semail.setSubject('Single Email message Example');
               semail.setPlainTextBody('Hello!!!!!!!!!!This is a test email to test single email message program');
              Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
              return null;
      }
}

How to deploy Validation Rules using Apache ANT tool in Salesforce?

Sample Package.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
         <members>Object Name.Validation Name</members>
         <name>ValidationRule</name>
</types>
<version>35.0</version>
</Package>

Note:

Use API names for Object Name and Validation Name.

Tuesday, November 29, 2016

Apex Triggers in Salesforce

Trigger is piece of code that is executes before and after a record is Inserted/Updated/Deleted from the force.com database.


Syntax:

Trigger <trigger name> on <Object name> (trigger Events) {
// Implement the Logic here
}

Types of Triggers:

– Before Triggers
– After Triggers

Before Trigger
Before triggers are used to perform the logic on the same object and specifically we cannot use the DML operation (Insert, update, delete) on these triggers. These triggers are fired before the data is saved into the database.

After Trigger: 
After triggers are used to perform the logic on the related objects and these triggers are used access the fields values that are created by system (Ex: CreatedBy, LasteModifiedBy , Record Id etc..).

Bulk Triggers:
By default every trigger is a bulk trigger which is used to process the multiple records at a time as a batch. For each batch of 200 records.

Trigger Context Variables:

All the trigger context variables are prefixed with “Trigger.” (Ex: Trigger.isInsert,etc..)
isInsert : Returns true if the trigger was fired due to insert operation.
isUpdate : Returns true if the trigger was fired due to update operation.
isDelete  : Returns true if the trigger was fired due to delete operation.
isBefore : Returns true if the trigger was fired before record is saved.
isAfter : Returns true if the trigger was fired after record is saved.
New : Returns a list of new version of sObject records.
Old : Returns a list of old version of sObject records.
NewMap : Returns a map of new version of sObject records. (map is stored in the form of map<id,newRecords>)
OldMap : Returns a map of old version of sObject records. (map is stored in the form of map<id,oldRecords>)
Size : Returns a integer (total number of records invoked due to trigger invocation for the both old and new)
isExecuting : Returns true if the current apex code is a trigger.

The below table is tells what are the events we can use in the new trigger and old trigger.




Trigger Context Variable considerations:
– Trigger.Old is always readOnly
– We cannot delete trigger.new
– In before triggers, trigger.new can be used to update the fields on the same object.
– In After trigger, we get run time exception is thrown when user try to modify the fields in the same object.


Salesforce Developer Certification Question & Answers

1. Select the right sequence to be followed to upload data in salesforce.com
a) Load Accounts, User, and Contacts
b) No difference, you can do it in whichever sequence you like
c) Users, Accounts and Contact
d) Users, Contacts and Accounts

2. You want to track the changes on your data over the past one month. What is
the best way to achieve this?
a) Reports
b) Dashboards
c) Analytical Snapshots
d) S-Controls

3. Define a junction Object
a) Standard Object with two Master Detail Relationship
b) Custom Object with two Master Detail Relationship
c) Standard Object with three Master Detail Relationship
d) Custom Object with one Master Detail Realtionship

4. You want to display a Dashboard with Grand Total.Which Dashboard
Component is required for this choose any two
a) Chart
b) Guage
c) Pivot
d) Metric

5. You want to extract data from SF right at2:00 are everyday.Waht is the
process today the same
a) Run Data loaders from the prompt
b) User import scheduler in Sales force
c) User Export scheduler in Sales force
d) Use Export scheduler in the data loader

6. For testing if the Workflow is working fine, what tests can a developer do?
Choose any two
a) Time based Workflow queues
b) Debug Log
c) Bug History Tracking
d) Activity History

7. What data type of fields can be the external ID?
a) Text, Number and Formula fields only
b) Text, Email and Number only
c) Text and Number only
D) Text only

8. which of the following features are available on Custom Objects Choose any
three
a) Assignment Rules
B) Sharing
c) Field History Tracking
d) Queues

9. What determines access a user must have to master record to
created/edit/delete a record?
a) Record Type
b) Data Type
c) Field Level Security
d) Sharing settings

10. Developers want users to access tags. What all needs to be done Choose any
three
a) Enable Tags for the Organization
b) Enable Tags for Page Layouts
c) Enable Tags for user profiles
d) Enable Tags for public Groups
e) Add tags to the sidebar of the Home page Layout

11. How do you determine if an application process has been changed, Choose
ant two:
a) Setup Audit Trail
b) Look at “Modified by “on Approval Definition
c) Field History Tracking
d) Debug Log

12. Analytical Snapshot has field. What could be the probable reasons for the
same choose any two?
a) Running user is inactive
b) Custom Object Contains Triggers
c) Source reports is resaved as matrix
d) Reports is not working properly in sales force

13. What is viewed using process visualizer?
a) Sales process
b) Approval Process
c) Support Process
d) Workflow Rules

14. What type of report would you run to show the number of positions grouped
by Department?
a) Summary
b) Analytical Snapshot
c) Tab
d) Pivot

15. Match the following
Database            Controls application appeance
UI                       Environment and tools for force.com application
Development     Defines objects field relation
Logic                  Task assignment rules, time based actions

16. What is true about Force.com sites? Choose any three
a) Leverage declarative Page Layouts as Web page
b) Enable developer to build public unauthorized sites
c) Build with visual Force
d) Leverage Date in content in the sales force Organization

17. Tab can be used by a developer to create————-? Choose any three
a) Standard Objects Tabs
b) Web Tabs
c) Apex Tabs
d) Visual Force Tabs
e) Custom Object Tabs

18. Which development tools can be used to create a data model? Choose any
two.
a) Force.com lookup
b) Application Setup Menu
c) Force.com IDE
d) Web Services API

19. If you were maintain consistency among two fields of a custom object which
option would you choose
a) Validation rules
b) Look up
C) if function
d) Regex function

20. If a parent object has a lookup relationship defined with a child object.
What happens in the child object when you delete a record from the parent?
a) The child record deleted
b) Nothing happens
c) The parent record cannot be deleted
d) The child record cannot be deleted

21. How can a developer get a Custom Object added to the quick create list?
a) Add the object through home page component settings
b) It is added automatically
c) Expose a custom tab for the custom object
d) Enable the quick create on the user profile

22. Select the features that are available through custom report types, please
select two (2) items.
a) Define object relationships and field’s fir reports
b) Define up to 4object relationships
c) Define anti-Join relationships
d) Create analytic snapshot reports

23. Developers must know of the following issues while uploading data to sales
force using the data loader choose any two.
a) Universally required field settings are respected
b) Required fields on page Layouts are enforced
c) Triggers are not enforced
d) Validation rules are respected

24. An organization wishes to have everyone view/edit records on an object
except for a single person x who should only have read-only access to the
object. What is the best way to implement the requirement?
a) Modify the sharing access for the object to public read/write And remove user x
from the role hierarchy
b) Modify the sharing access for the object to private and remove User x from the
role hierarchy
c) Modify the sharing access for the object to public read only, Create a public
group with everyone except user x; Create a sharing rule and define read/write
access to the public group.

25. Using a formula field how a developer would calculate the number of days
since a record has been created, the created date field is a Date Time field.
a) TODAY ()-DATEVALUE (Created Date)
b) Now () DATEVALUE (Created Date)
c) TODAY ()-Created Date
d) Created Date-) TODAY ()

26. Salesforce.com has notified you that they have enabled the ability to update
audit fields for your organization. When inserting a record which field can you
set?
a) Create Date
b) Is Deleted
c) SysModStamp
d) Updated Date

27. Developer needs to create a trending report what should he/she use to get
the historical data?
a) Reports
b) Analytic Snapshots
c) Roll-Up Summary
d) Report Types
d) Audit History Records

28. What is the best type of dashboard component to display a list of your top 10
customers?
A) Metric
B) Table
c) Guage
d) Chart

29. The salseforce.com edition that is NOT available today?
a) Professional
b) Unlimited
c) Enterprise
d) Expert

30. Using the force.com platform declarative model to build an application.
Which of the following do you NOT have to do? Please select three (3) choices.
a) Install a database server
b) Configure an application using clicks not code
c) Deploy a web server
d) Administer and email server

31. An organization wants to create a field to store manager data on the user
object. The manager field is a reference to another user record. What type of
relationship should be used?
a) Master-detail
b) Hierarchical
c) Lookup
d) Many-to-many

32. What are the data types that are supported by formula field? Please select
three (3) choices.
A) Text
b) Percentage
c) Email
d) Currency
e) Phone

33. What records will a user be able to view if the permission to view data
depends on the Role?
A) Data which is owned by users above the role hierarchy of the user
b) Data which is accessible by users above the role hierarchy of the user
c) Data which is owned by users bellow the role hierarchy of the user
d) Data which is accessible by users bellow the role hierarchy of the user

34. in a lookup Relationship
a) Child can refer to the parent data only
b) Parent can refer the child only
c) Both can access each other’s data
d) Both cannot access each other data

35. What is the Maximum no.of master-detail relationship that can be created
on a custom object?
a) 1
b) 2
c) 4
d) Unlimited

36. An organization has decided to manage hiring and positions. A custom
object has been created to manage all new job positions. All positions below
$50,000 must be approved by the hiring manager, and positions above $50,000
must be approved by the hiring manager, and the regional hiring
manager/What would a developer use to declarative fulfill the requirement?
a)ApexCode,to check the position’s salary and assign to the appropriate resource for
approval
b) Approval process
c) Validation rules
d) Dynamic Routing Approval

37. A developer has created a junction object what is the significance of the first
master-detail (primary) relationship?
a) Look and feel, the junction oats detail and edit pages use the color and any
associated icon of the primary master object.
b) You cannot delete the primary relationship
c) You cannot rename the primary relationship
d) There is no significance

38. An organization has created an application manage new hires and job
positions. A custom object has been created to manage all job positions. Using
an approval process they configure the application to have first step of the
process require approvals from three different hiring managers. Select the two
(2) possible approval choices based on multiple based on multiple approvers
for an approval step.
a) Approve or reject based on the first response
b) Require unanimous approval from all selected approvers
c) Require majority approval from all selected approvers
d) Require x out of y approval from all selected approvers

39. Which of the following is NOT a step in creating a junction object?
a) Creating the custom object to serve as the junction object Between the two master
objects
b) Creating two master-detail relationships
c) Customizing the related lists on the page layouts of the two master objects
d) Creating two lookup relationships

40. When a record has been rejected by all approvers, sales force executes all
final rejection actions. Which of the following is NOT a possible final rejection
action?
a) Lock the record from being edited
b) Send an email to a designated recipient
c) Delete the record
d) Update a field on the record

41. Which of the following cannot be used on a User page Layout? Please select
two (2) choices.
a) Tags
b) Links
c) Buttons
d) Custom Fields
e) Inline Visual force

42. An organization wants to leverage a custom objects to track bugs. The
organization wants the ability to related bugs to parent bugs in a parent-child
relationship. What type of relationship should be used?
A) Master-Detail
b) Self
c) Hierarchical
d) Many-Many

43. An organization wants to leverage the import wizards to import different
types of data. What type of data cannot be imputed through the wizard?
a) Accounts and Contacts
b) Leads
c) Custom Objects
d) Users

44. An organization is interested in leveraging the data Loader to load data into
salesforce.com which of the following are NOT capabilities of the data loader?
Please select two (2) choices.
a) Import greater than 50,000 records
b) Import data into 2objects in a single transaction
c) Rollback import transactions
d) Run by command line

45. Using page Layouts you can do the following field Edits Choose any two
a) Read only
b) Controller field
c) Display
d) Dependency
e) Required Field

46. An organization needs the ability to view the value of the Opportunity Stage
field on an Opportunity product related list. Please choose the declarative
method of fulfilling the requirement.
a) Create an Apex method to replicate the value on the child object, and set the field
level security to read-only and expose the new field on the Opportunity product
related list.
b) Create an object formula field on the opportunity product Object and expose
the formula field on the opportunity product related list.
c) Create a validation rule on the opportunity product object.
d) Create a new pick list field called stage on the opportunity Product object, and
expose the field on the opportunity.

47. A developer wants to leverage the console to view to see the parent object of
the child object in focus on the console. How would a developer specify what
related list fields are displayed on the parent object?
a) On an child object’s mini-page layout
b) On an parent object’s mini-page layout related lists field selection
c) On the parent object’s page layout related lists field selection
D) You can’t modify the related fields on the console view

48. An organization has two custom objects to track job positions and salaries
for the positions.Every one on the orgnization should b eable to view the
positons however, only select users can viewThe salary records. What steps
should a developer take to ensure the requirement is fulfilled?
A) Create a lookup relationship between positions and salaries; define public
access on position and private access on salary.
B) Create a master-detail relationship between positions and salaries; define public
access on position and private access on salary.
C) Create a master-detail relationship between positions and salaries; define private
access on position and private access on position and create sharing rules on salary.

49. A developer has created a custom field marked as an external id on an
object. If two words in the object have the same external id,and an upsert
action occurred for that same external id what would happen.
a)The first matching external id record would be updated
b)Both matching external id records would be updated
c)A new recorded is creted
d) An error would be reported

50. A developer has a requirement to collect the state and the cities for the state
selected on an account page layout.Once the user selects a state only the
possible cities I thatstate should be available for entry,what is the best
declarative method for fulfilling this requirement.
a)Create a workflow rule that will update the city once a state is entered
b)create a validation rule which will cause an error if the city is not in the state that
has been entered
c) Create a dependent pick list for cities based on the state that has been
entered
d) Create a formula field that lookups the valid cities for the state entered

51. A developer has created an approval process.What would require that a
formula entry criterion be used versus standard criteria?
a) User profile evaluates to’System Administrator’
b) Determine if the record is newly created
c) Detemine if a record has been updated
d) Detemine if a field has been changed

52. An organization has created a HR application which contains a custom
object for job positions and candidates for the positions.The HR managers want
to see a view of the position with the best candidates for that position and not
just all the candidates listed.What is the best method to fulfil the requirement?
a) Add a visualforce page
b)Add the candidate related list to the job position page layout
c)Create a vaslidation rule on the job position page layout
d)Create a formula field on the job position object and add to the page layout

53. Which of the following is not process or data intensive
a) Time entry application
b) Inventory managemnet
c) Word processing
d) Human resouce management

54. Which two(2)items most closely relate to the view layer of the Model view
Controller paradigm?
a) Page Layout
b) Validation Rule
c) Custom Tab
d) Custom Field

55. A developer has created a time-based workflow that escalates a Lead record
10 days after it has been created if no updates have occurred.What is the best
way for the developer to test that the new time based workflow rule is
functioning? Please select two(2)choices.
a)User Debug Logs setup the Developer,create a new lead record,review debug
logs
b) Create a new lead record;view the time –based workflow queue;
c)setup the developer for the time-based workflow queue;create a new load
record;view the time-based workflow queue;

56. Which are true regarding field level security
a) Specified on profiel
b) Enforced in webserver API
c) Decides the Record Level
d) Defines the Visible Picklist

57. What settings can you specify on a profile?Please select two(2)choices.
a) Revoke sharing permissions
b) Enable record types
c) Enable create read,create,edit,and delete on objects
d) Specify laguages

58. While uploading data using the data loader the CSV file must contain
a) Profile of the user who owns record
b) Role of the record owner
c) Force.com ID for the record to be updates
d) List views in which the dates should be stored

59. Which of the following have the same ID’S?
a) Production and Development Sandbox
b) Production and Full copy Sandbox
c) Production, Development Sandbox and Full copy Sandbox
d) Production, Unit Testing, Full copy Sandbox

60. Which is not a part of the standard Force.com Application Development?
a) Custom Tab
b) Default page
c) Data warehouse
d) Custom Object

Different Types of Salesforce Packages

Packages in Salesforce


A package is a bundle/Collection/container for list of components or related 
application. We can distribute these package to other salesforce organization and users. 

There are two types of package.

1. UnManaged Package
2. Managed Package

What is UnManaged Package?

– Unmanaged package is used to distribute open source applications to provide
developers with with basic functionality.
– We can edit unmanged package components after installing the unmanaged
package in a salesforce organization.
– The developer who created unmanged package has no control on installed
components, can’t edit & can’t upgrade.

What is Managed Package?

– Managed package is used to distribute and sell application to customers. By using
the App exchange developers can sell and mange user baser based licences to the
managed package application.
– Managed packages are fully upgradable.
– To ensure seamless upgrades, certain destructive changes, like removing objects or
fields, can not be performed.

actionStatus Tag in Visualforce

This tag helps Us to display the status AJAX request like an AJAX request can either be in progress or Complete.

Below Visualforce helps you to search opportunity based on name:






Page:

<apex:page controller="OppsearchController">
<apex:form >
    <apex:pageBlock id="pb" mode="edit">
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="Search String">Search String</apex:outputLabel>
                <apex:panelGroup >
                    <apex:inputText value="{!searchString}"/>
                    <apex:commandButton value="GO" action="{!oppResult}" status="as" reRender="pbt"/>
                    <apex:actionStatus startText="Searching……." id="as"></apex:actionStatus>
                </apex:panelGroup>
              </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        <apex:pageBlockSection title="Result">
            <apex:pageBlockTable value="{!OppSearchResult}" var="opp" id="pbt">
            <apex:column value="{!opp.name}"/>
        </apex:pageBlockTable>
       </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>

Controller:


public class OppsearchController {
    List<Opportunity> OppSearchResult;
    public String searchString { get; set; }
    public List<Opportunity> getOppSearchResult() {
        return OppSearchResult;
    }
    public PageReference oppResult() {
        OppSearchResult = (List<Opportunity>)[FIND :searchString RETURNING
        Opportunity(Name)][0];
        return null;
    }
}


Standard List Controllers In Visualforce

By using standard standard list controllers we can manage set of records. For every standard controller there exists a standard list controller that allows you to create pages that display and act on a set of records, such as list pages, related lists, and mass action pages. We can associate define standard list controller by using recordSetVar.

<apex:page standardController="Account" recordSetVar="accounts">

Standard list controller provides additional four pagination actions.
Those are first,last, next and previous.

We can use standard list controllers with the following objects.

Account, Asset, Campaign, Case, Contact, Contract, Idea, Lead, Opportunity, Order,

Product2, Solution, User, Custom Objects.

Page:

<apex:page standardController="Account" recordSetVar="accounts">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable value="{!Accounts}" var="a">
            <apex:column headerValue="Account Name">
                <apex:outputField value="{!a.name}"/>
            </apex:column>
        </apex:pageBlockTable>
    <!-- pagination actions supported by standard list controller -->
    <apex:pageBlockButtons >
        <apex:commandButton value="First" action="{!first}"/>
        <apex:commandButton value="Last" action="{!last}"/>
        <apex:commandButton value="Next" action="{!next}"/>
        <apex:commandButton value="previous" action="{!previous}"/>
    </apex:pageBlockButtons>
   </apex:pageBlock>
  </apex:form>
</apex:page>



actionFunction Tag in Visualforce

By using actionFunction tag you can call controllers methods from java script code using an AJAX request.

This component must be a child of <apex:form> tag. And we cannot place this tag inside an iteration tag like <apex:pageBlockTable> & <apex:repet> now. Earlier we were able to do this.But with api version 23 we cannot place <apex:actionFunction> inside iteration tags.

Here I am providing an example, How to use <apex:actionFunction> tag is visualforce. I have created simple Lead form to enter lead details from custom page. Last name, Company & email are mandatory fields in below page. If any miss those required fields, I am displaying alert by Javascript and i am calling method from java script to save the record. See below code to understand, how
<apex:actionFunction> will work.

Page:

<apex:page controller="InsertLeadController" showHeader="false">
<script type="text/javascript">
    function validate()
        {
            if(document.getElementById('{!$Component.LF.LDB.Lname}').value == ''|| document.getElementById('{!$Component.LF.LDB.comp}').value == ''){
                alert("LAST NMAE & Company are requird fields");
            }
            else{
                CallsubmitLead();
                alert("Lead has been inserted");
            }
        }
</script>
<apex:form id="LF">
    <apex:actionFunction action="{!submitLead}"  name="CallsubmitLead" reRender="LDB"/>
    <apex:pageBlock title="Lead Form - Enter lead details" id="LDB">
    <table>
        <tr>
            <td><apex:outputText value="First Name"/></td>
            <td><apex:inputText value="{!firstName}"/></td>
        </tr>
        <tr>
            <td><apex:outputText value="Last Name"/></td>
            <td><apex:inputText value="{!lastName}" id="Lname"/></td>
        </tr>
        <tr>
            <td><apex:outputText value="Comapany"/></td>
            <td><apex:inputText value="{!comapany}" id="comp"/></td>
        </tr>
        <tr>
            <td><apex:outputText value="Mobile"/></td>
            <td><apex:inputText value="{!mobile}"/></td>
        </tr>
        <tr>
            <td><apex:outputText value="Lead Status"/></td>
            <td><apex:selectList value="{!statusOptions}">
            <apex:selectOptions value="{!items}"/>
            </apex:selectList></td>
        </tr>
    </table>
    <apex:commandButton value="Save" onclick="validate();"/>
    </apex:pageBlock>
  </apex:form>
</apex:page>

Controller:

public class InsertLeadController {
    public String statusOptions { get; set; }
    public String comapany { get; set; }
    public String mobile { get; set; }
    public String firstName{get;set;}
    public String lastName{get;set;}
    public Lead l = new Lead();
    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Open – Not Contacted','Open – Not Contacted'));
        options.add(new SelectOption('Working – Contacted','Working – Contacted'));
        options.add(new SelectOption('Closed – Converted','Closed – Converted'));
        options.add(new SelectOption('Closed – Not Converted','Closed – Not Converted'));
        return options;
    }
    public PageReference submitLead() {
        l.FirstName=firstName;
        l.LastName=lastName;
        l.Company=comapany;
        l.MobilePhone=mobile;
        l.Status=statusOptions;
        insert l;
        return null;
    }
}





actionPoller Tag in Visualforce

actionPoller tag specifies a timer that sends an AJAX update request at specified interval.
Minimum interval time to refresh is 5 sec.

Here in this post i am providing a simple example to explain about actionPoller. I am calling a simple method from controller to display Date & TIme and recalling that method by using actionPoller tag to change the time for every 5 sesc. See the below code to understand how actionPoller will work.


Page:

<apex:page controller="actionpollerDemoController">
    <apex:form >
        <apex:pageBlock id="pb">
               <apex:actionPoller action="{!dateTimeMethod}" reRender="pb" interval="5"/>
                Hello!!! Date and Time: {!dateAndTime}
               <p>Note: Time will refresh fror every 5 sec.</p>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Controller:

Public with sharing class actionpollerDemoController {
        Public DateTime dateAndTime{get;set;}
        Public void dateTimeMethod(){
            dateAndTime = System.now();
        }
}

OutPut: In below Image Date and Time will refresh for every 5 secs



Friday, November 25, 2016

Using REGEX function in validation rule.

Using REGEX function we can build validation rule to enforces proper data format.

Example : 

Validates Account Name Whether it Contains only Alphanumeric,Underscore and Space Character only.

Steps to create validation rule:

Go to steps -> Build -> Customize -> Account -> Validation Rule and enter required fields and save validation rule.

Error condition formula for this example:

NOT(REGEX(Name,"[a-zA-Z0-9_ ]+"))

See the below screen for reference.



Testing above validation Rule:

To test this validation rule go to account tab and give any Account Name which Contains special characters and try to save account record, you will get error message.

See below screen for reference.



Using VLOOKUP function in validation rules.


VLOOKUP function searches an object for a record where specified field matches the specified lookup value. If a match is found, returns another specified value.

Syntax of vlookup:

VLOOKUP(field_to_return, field_on_lookup_object, lookup_value)

Example:

Create validation rule that checks the Billing ZIP/postal code entered in an Account against a table to validate that the zip code and state match.

To track ZIP Codes I have created custom object called Zip Code in this object I am storing Zip code(as a Standard Name Field), State(as State__c Custom Field) And Created below records (sample records) in this Zip Codes object.

See the below image for a record reference in Zip Code Object.



Below validation rule validate Billing zip/postal code in Account object with the codes in Zip Code object. If you enter wrong zip code this validation rule throw an error.

Creating validation rule:

To create validation rule go to setup -> Build -> Customize -> Account -> Validation rule and enter required information.

Error condition formula:

UPPER(VLOOKUP($ObjectType.Zip_Code__c.Fields.State__c,$ObjectType.Zip_Code__c. Fields.Name,BillingPostalCode))<>UPPER(BillingState)

See the below image for reference.


How to test this validation rule?

To test this validation rule go to Account tab and create new account record with enter Billing State/Province = AP and postal code =524000 and save this record, you will get associated error message. If you enter correct data which is mentioned in above Zip Code record, record will save. If you enter wrong data validation rule will fire an error.

See the below image for reference.



Web-to-Lead Creation In Salesforce.



What is web to lead in salesforce?

Salesforce web to lead is to directly collect capture the leads form your website andloaded into Salesforce. This is built in functionality in Salesforce. Nothing you needto download or install.

How can I set up web to lead in Salesforce?

1. Login into Salesforce. 
2. Go to “set up” -> Customize -> Leads -> click on web-to-Lead



Here we can see web to lead set enabled checkbox is checked. By default web to lead
is enabled in sales force. And default lead creator is owner of the lead creator inSalesforce. By default it will display System Administrator who created Salesforceorganization.You can edit the owner of the default web to lead creator and also you can selectdefault Response template by click on the “EDIT” button.


3. Click on “Create Web-to-Lead Form” button then you will navigate to followingscreen.



Here you can see the familiar list of fields to display on the web to lead formincluding custom fields from Lead object. You can add or remove fields by using“add” and “remove” buttons. And also you can reorder fields by using “up” and“down” buttons.And in the above screen Return URL and Language are mandatory fields you need tomention.Basically “Return URL” is after the lead form is submitted this is the URL that userwill be direct to. It’s good idea to set up thank you page and best offers provided byyour company to customers.

4. Next click on Generate button then you will navigate to following screen.



Salesforce creates HTML code you can insert directly into your website.

Take that code and do customization to that code according to you requirements.
You can add your company logo and you can do additional customization to that
HTML code.



Once you have done with customization to this code you can place this code in your website.


Enter the Details and click on the Submit Button.

Open Salesforce Org Click on Leads Tab,You can see the Lead That is Created in the website.

Thursday, November 24, 2016

VisualForce Page to display Available Accounts and Selected Accounts using Wrapper Class.



Page:

<apex:page controller="SelectedAccountsWrapperController"  >
<apex:form id="pg" >
    <apex:panelGrid columns="2" width="100%" id="pgr">
        <apex:pageblock title="Available Records" id="Available_PBS">
          <apex:pageBlockSection Title="List of Available Records">
                <apex:dataTable value="{!ServicesList}" var="s" columnswidth="50px,50px" cellpadding="4" border="1">
                    <apex:column headerValue="Action">            
                        <apex:inputCheckbox value="{!s.selected}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelected}" rerender="Selected_PBS"/>
                        </apex:inputCheckbox>
                     </apex:column>
                    <apex:column headervalue="Name" value="{!s.sr.Name}" />
                 </apex:dataTable>
        </apex:pageBlockSection>
      </apex:pageblock>
      <apex:pageblock title="Selected Records" id="bloc">
        <apex:pageBlockSection Title="List of Selected Records" id="Selected_PBS" >
            <apex:dataTable value="{!RServicesList}" var="ss" columnswidth="50px,50px" cellpadding="4" border="1">              
                <apex:column headervalue="Name" value="{!ss.rsr.Name}" />
                <apex:column headervalue="Industry" value="{!ss.rsr.Industry}" />     
                <apex:column headerValue="Action" >
                  <apex:inputCheckbox value="{!ss.Rselected}" id="checkedone" >
                  <apex:actionSupport event="onclick" action="{!RemoveSelected}"  rerender="Selected_PBS,Available_PBS,pg,bloc"/>
                  </apex:inputCheckbox>
                </apex:column>       
            </apex:dataTable>
        </apex:pageBlockSection>
       </apex:pageblock>
    </apex:panelGrid>
  </apex:form> 
<script>
    function checkAll(cb)
       {
        var inputElem = document.getElementsByTagName("input");
        for(var i=0; i<inputElem.length; i++){
            if(inputElem[i].id.indexOf("checkedone")!=-1)
                inputElem[i].checked = cb.checked;
         }
       }    
</script>
</apex:page>

Controller:

public class SelectedAccountsWrapperController{

    public List<Servicewrapper> ServicesList {get;set;}
    public  list<RServicewrapper> RServicesList {get;set;} 
    List<Servicewrapper> selectedServices = new List<Servicewrapper>();
    List<RServicewrapper> RselectedServices = new List<RServicewrapper>();
    List<Servicewrapper> Services {get;set;}
    
    public SelectedAccountsWrapperController(){
        ServicesList  = new List<Servicewrapper>();
        RServicesList = new list<RServicewrapper>();
        for(Account a : [select Id, Name, Industry from Account Where Industry!=null order by Name asc]){
        Servicewrapper sw = new Servicewrapper();
        sw.sr  = a;
        sw.selected  = false;
        ServicesList.add(sw);
      }
    }
   public PageReference getSelected()
    {
        selectedServices.clear();
        RServicesList.clear();
        for(Servicewrapper srwrapper: ServicesList)
            if(srwrapper.selected == true){
                rServicewrapper swobj =new rServicewrapper ();
                swobj.rsr = srwrapper.sr;
                swobj.rselected = true;
                RServicesList.add(swobj);
            }
                
        system.debug('selectedServices++++'+selectedServices);
        return null;
    }
    
     public List<Servicewrapper> GetSelectedRecords()
    {
        if(selectedServices.size()>0){
            return selectedServices;
            }
        else
            return null;
    }    
    
    public PageReference RemoveSelected() {
         
         for(RServicewrapper rsrwrapper: RServicesList){
             for(Servicewrapper srwrapper: ServicesList){
                if(rsrwrapper.Rselected == false){
                    if(srwrapper.sr.id== rsrwrapper.rsr.id){
                        srwrapper.selected = false;
                        }
                  }
              }
           }
        List<RServicewrapper> tempServices = new List<RServicewrapper>();
        for(RServicewrapper rsrwrapper: RServicesList){
             if(rsrwrapper.Rselected == true){
                 tempServices.add(rsrwrapper);
             }
         }
         RServicesList = tempServices;
        return null;
    } 
    
    public class Servicewrapper
    {
        public Account sr{get; set;}
        public Boolean selected {get; set;}
    }
    
    public class RServicewrapper
    {
        public Account rsr {get; set;}
        public Boolean Rselected {get; set;}
    }
}

Monday, November 21, 2016

How to Know how many Records are there In the Org ?

Answer:

If you are an administrator, you can view the total number of records you have in an object by going to       

Setup -> Administer -> Data Management -> Storage Usage.

Thursday, November 17, 2016

Apex Code to Recall The Approval Process.

ProcessInstanceWorkitem[] workItems = SELECT Id FROM ProcessInstanceWorkitem WHERE ProcessInstance.TargetObjectId = 'recordId' AND ProcessInstance.Status = 'Pending' ];
Approval.ProcessWorkitemRequest pwr = new Approval.ProcessWorkitemRequest();
pwr.setAction('Removed');
pwr.setWorkItemId(workItems[0].id);
Approval.ProcessResult result = Approval.process(pwr);

Note: This Code will work only If you replace recordId with an Id in the org in Soql query.

VisualForce Page to Display Number of Opportunities for an Account based on StageName Using Map in Pageblock Table



Page:

<apex:page StandardController="Account" extensions="OppCountInAccountController">
<apex:form >
<apex:pageBlock mode="edit">

<apex:pageBlockSection title="Account Details" >
<apex:outputText value="{!Account.name}"></apex:outputText>
</apex:pageBlockSection>

<apex:pageBlockSection title="Opportunity Details">
<apex:pageBlockTable value="{!listStrings}" var="stage"  >
<apex:column headerValue="Stage" value="{!Stage}" />
<apex:column headerValue="Count" value="{!omaps[stage]}" />
</apex:pageBlockTable> 

</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Controller:

public class OppCountInAccountController {
    
    public list<opportunity> listOpps {get;set;} 
    public set<String> Stageslist {get;set;} 
    Public list<Integer> Countlist {get;set;}
    Public List<String> listStrings {get;set;}
    Public Map<String,Integer> omaps {get;set;}
    
    public OppCountInAccountController(ApexPages.StandardController controller) {
        listOpps= [select id,Name,StageName,accountid from Opportunity where accountid=:apexpages.currentpage().getparameters().get('id')];
        Stageslist = new set<String>();
        for(Opportunity opp : listOpps){
            Stageslist.add(opp.stageName);
        }
        listStrings  = new List<String>(Stageslist);
        
        Countlist =new list<Integer>();
        omaps = new Map<String,Integer>();
        for(Integer i=0;i<listStrings.size();i++){
             Integer Num  = [select Count() from Opportunity where accountid=:apexpages.currentpage().getparameters().get('id') And stageName=:listStrings[i]];
             Countlist.add(Num);
             omaps.put(listStrings[i],Num);
         }
        
     }    
}

Note: This Page will work only if you pass an Account id to the page like this,
https://Test-Org-dev-ed--c.ap2.visual.force.com/apex/OppCountInAccount?id=00128000011VoTr

Wednesday, November 16, 2016

Inline VisualForce Page to Freeze/UnFreeze the User without Having Manage Users permission to Profile.


Page:


<apex:page standardController="user" extensions="Freezer" id="pg">
    <apex:form id="frm">
        <apex:pageBlock >
      <!--     <span style="font-size:16pt;font-style:bold;color:red;"> Press The Button to Freeze/Unfreeze The User </span> -->
           <apex:commandButton style="width:150px;height:50px;background:green;color:white;font-size:14pt;font-style:bold" action="{!Freezermethod}" value="{!btnname}" oncomplete="RefreshPrimaryTab('{!user.id}')"/> 
        </apex:pageBlock>
    </apex:form>
    <script type="text/javascript">

        function RefreshPrimaryTab(id) 
        {
                  window.top.location.href = '/'+id+'?noredirect=1&isUserEntityOverride=1';
        }

   </script>
</apex:page>

Controller:


public class Freezer {
    public string btnname {get;set;}
    set<id> ids=new set<id>();
    user urs = [SELECT Id,Name FROM User WHERE      id=:apexpages.currentpage().getparameters().get('id')];
    
    public Freezer(ApexPages.StandardController Controller) {
        
        UserLogin users = [SELECT IsFrozen,UserId FROM UserLogin WHERE UserId=:urs.id];
            if(users.isFrozen)
                btnname='Unfreeze';
            else
                btnname='Freeze';
        }
    
    public void Freezermethod(){   

      UserLogin users = [SELECT IsFrozen,UserId FROM UserLogin WHERE UserId=:urs.id];
             if(users.isFrozen) 
                users.isFrozen= false; 
            else
                users.isFrozen= true; 

            update(users); 
        }
        
    }

Note:This Page will work only After It is added to the User Page layout Other wise it will display QueryException.

VisualForce Page to Create the Trigger Dynamically.



Page:

<apex:page controller="TriggerCreator" sidebar="false" tabStyle="TriggerCreator__tab">
  <div style="float:right" >
      <apex:image value="{!$Resource.TriggerCreatorLogo}" />
    </div>
    <div >
  <apex:form id="fm" >
  <apex:pageBlock id="pg" > 
  <h1>Enter Trigger Details </h1><br/><br/>  
         <apex:panelGrid columns="2" > 
             <apex:outputLabel styleClass="outputLabel" value="Trigger Name:"/>    
             <apex:inputText styleClass="inputText" value="{!TrName}"/>
             <apex:outputLabel styleClass="outputLabel" value="Object Name:" />    
        <!--     <apex:inputText styleClass="inputText" value="{!ObjName}" id="ObjName"/>  -->
                      <apex:actionRegion >      
                           <apex:selectList value="{!selectedObject}" size="1">
                                    <apex:selectOptions value="{!ObjectNames}"/>
                            </apex:selectList>
                     </apex:actionRegion>                         
                  
             <apex:outputLabel styleClass="outputLabel" value="Trigger Event:"/> 
             <apex:selectList value="{!type}" multiselect="true"  >
                <apex:selectOption itemValue="Before Insert" itemLabel="Before Insert"/>
                <apex:selectOption itemValue="After Insert" itemLabel="After Insert"/>
                <apex:selectOption itemValue="Before Update" itemLabel="Before Update"/>
                <apex:selectOption itemValue="After Update" itemLabel="After Update"/>
                <apex:selectOption itemValue="Before delete" itemLabel="Before delete"/>
                <apex:selectOption itemValue="After delete" itemLabel="After delete"/>
                <apex:selectOption itemValue="after Undelete" itemLabel="After Undelete"/>
            </apex:selectList>
         </apex:panelGrid>
             <div style="padding-left:105px;" >
             <apex:commandButton style="background:black;width:150px;height:40px;color:white;font-size:12pt;" action="{!TriggerCreator}"  oncomplete="Showoptions('{!str}','{!type}','{!TrName}');fun('{!str}','{!tid}','{!type}','{!TrName}');"  value="Create Trigger" status="actStatusId" rerender="fm"/>  
              <apex:actionStatus id="actStatusId" >
                <apex:facet name="start" >
                  <img src="{!$Resource.Searching}" />                    
                </apex:facet>
            </apex:actionStatus>
           </div>
         <apex:pageMessages ></apex:pageMessages>
      </apex:pageBlock>
   <p id="options" ></p>
   <p id="refresh" ></p>
  </apex:form>
  </div>  
   <script type="text/javascript">
        function Showoptions(str,tp,tnam){    
            if(!str.includes('Invalid')&&!str.includes('DUPLICATE')&&!str.includes('UNKNOWN')&&tp!='[]'&&tnam!=''&&/^[a-zA-Z0-9- ]*$/.test(tnam)){
        <!--    document.getElementById("options").innerHTML='<h2>To edit the Trigger </h2><a style="text-decoration: none;" href="javascript:fun(dd);"><h3>clickhere</h3></a>';    -->
            document.getElementById("refresh").innerHTML='<h2>To Create New Trigger </h2><a style="text-decoration: none;" href="javascript:refresh();"><h3>clickhere</h3></a>';
            
        }
       } 
   </script> 
  <script>
    function refresh() {
       window.location.reload();
    }
</script>
 <script>
    function fun(st,eid,tp,tnam){
        if(!st.includes('Invalid')&&!st.includes('DUPLICATE')&&!st.includes('UNKNOWN')&&tp!='[]'&&tnam!=''&&/^[a-zA-Z0-9- ]*$/.test(tnam)){  
         if(confirm("Press OK to Edit the Created Trigger")) 
             window.open("/"+eid+"/e?retURL=%2Fsetup%2Fbuild%2FviewApexTrigger.apexp%3Fid%3D"+eid+"%26id%3D"+eid);     
        } 
    }
</script>

  <style>
      h1  {
    color:#04cef7;
    width:150px;
    clear:left;
    font-size:15pt;
    
   }
   .outputLabel{
    width:100px;
    clear:left;
    text-align:right;
    font-weight:bold;
    
    }

    .inputText, .outputLabel{
        float:left;
    }
      h2 {
    font-weight:bold;
    font-size:20px;
    color:#04cef7;
    clear: left;
    text-align:center;
    width:500px;
   }
   a,h3{color:#0655d3;
       font-weight:bold;
    font-size:18px;
    text-decoration: none;}
  </style>    
</apex:page>

Controller:

public class TriggerCreator {

    public String type { get; set; }

    public String ObjName { get; set; }
    public String TrName  { get; set; }
    Public String str {get;set;}
    public string tid {get;set;}
    
    public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

    public String selectedObject {get; set;}

    public String selectedField {get; set;}

    Public void TriggerCreator(){
    map<string,string> mapinfo= new map<string,string>();
    system.debug('++++++++++++++++++'+type);
  //  string patte = '/^[a-zA-Z0-9_]+$/';
    if(TrName=='' ||!Pattern.matches('[a-zA-Z0-9_]+',TrName)){ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Enter Valid TriggerName.'));}
    else if(selectedObject ==''){ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Enter ObjectName.'));}
    else if(type=='[]'){ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please select Event.'));}
    else{
    mapinfo.put('Name',TrName);
    mapinfo.put('TableEnumOrId',selectedObject);
    string type1=type.remove('[');
    string type2=type1.remove(']');
    mapinfo.put('Body','trigger '+ TrName + ' on '+ selectedObject +' ('+type2+'){ }');
    String serialized = JSON.serialize(mapinfo);
         
    Httprequest req = new HttpRequest();
    req.setEndpoint('https://ghattamaneni-chaithanya-dev-ed.my.salesforce.com/services/data/v27.0/sobjects/ApexTrigger'); // Enter the org.
    req.setMethod('POST');
    req.setHeader('Content-Type','application/json');
    req.setHeader('Authorization','Bearer '+UserInfo.getSessionID());
    req.setBody(serialized);

    Http httpReq = new Http();
    HttpResponse res = httpReq.send(req);
    System.debug('>>>>>>>>'+res.getBody());
    str=string.valueof(res.getBody());
    system.debug('-----------'+str);
    if(str.contains('true')){ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.CONFIRM, 'Trigger Created Successfully!'));
        string rstr=str.remove('"');
        string[] strs=rstr.split(':');
        string[] fstr=strs[1].split(',');
        tid=fstr[0];
        system.debug('.................'+tid);
    }
    else if(str.contains('INVALID')){ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, 'Error Occured Please Check The Trigger Name OR Object Name and Try again'));}
    else if(str.contains('DUPLICATE')){ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, 'Trigger with this name is already Exist Please Enter different Name'));}
    else if(str.contains('UNKNOWN')){ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, 'Error Occured Please Check Trigger Name and Try again'));}
    }
   }
     public List<SelectOption> getObjectNames() 
    {
        List<SelectOption> objNames = new List<SelectOption>();
        List<String> entities = new List<String>(schemaMap.keySet());
        entities.sort();
         ////////////////////////////////
         Schema.DescribeSobjectResult[] results = Schema.describeSObjects(entities );
        for (DescribeSObjectResult result : results){
            if(result.isUndeletable())
            objNames.add(new SelectOption(result.getName(),result.getName()));
            }
      /*  for(String name : entities)
        {
            if(isundeletable())
            objNames.add(new SelectOption(name,name));
        }*/
        return objNames;
     }
}