Salesforce

An effort to bring a revolution in Salesforce.

Wednesday, 3 August 2016

How to read text file from static resource Salesforce.

 Method to read Text File from static resource.

 
public String textFromSomeUniqueName {

    get {
        StaticResource sr = [
                select Body
                from StaticResource
                where Name = 'SomeUniqueName'
                ];
        return sr.Body.toString();
    }
}
, ,

New Quote button is not visible

Seems like an access issues, please follow below steps:
 
1. Go to Setup --> Profile
2. Open your profile, and scroll down to "Standard Object Permission".
3. Please check if you have "create" permission on Quote Object.

If above steps seems fine to you, please check below steps:
1. Go to Setup --> Opportunity
2. Open the layout assigned to you profile. (Check page layout setting for profile wise page layout)
3. Click on Related List, and scroll down to Quote related list.
4. Add standard button "new Quote" and hit save.

,

Tuesday, 2 August 2016

Created Day of the Week formula

​CASE( MOD( datevalue(createddate) - DATE(1900, 1, 7), 7),
0, "Saturday",
6, "Sunday", "Weekday")

,

Monday, 1 August 2016

OWD VS PROFILES

OWD - Controls Record Access.
Sharing Rule - Controls Record Level Access.
Profile - Object Level Access
 

 The user cannot edit the records for other user ( sharing rule will not be created, will give an error that profile is read only) . However they can see each others record.

See Link : http://salesforce.stackexchange.com/questions/60656/profile-permissions-v-s-org-wide-defaults


Profile works on object and OWD on record ( they are two different things ).
It won't be a good idea to say that profile over rides OWD. But yes, Profile level permisson have a high preference, hence Profile permission will stand.

Consider a case where
OWD - Private
Profile - Read /Write


In this case he users will not be able to edit each others record due to OWD being private.
, , , ,

Tuesday, 26 July 2016

Read csv file then create Account in Apex Salesforce.

Sample logic code. 



Document doc=[SELECT Body,ContentType,Description,DeveloperName,Name FROM Document WHERE Name = 'Csv File'];
    String[] columns=doc.Body.toString().split('\n');
    String[] columnNames=columns[0].split(',');
    columns.remove(0);

    for(String str:columns)
    {
        Account acc=new Account();
        String[] fields=str.split(',');
        for(Integer i=0;i<fields.size()-1;i++)
        {
            acc.put(columnNames[i],fields[i]);
        }
        lstAccounts.add(acc);
    }


Insert  lstAccounts;
, ,

How can I change the visualforce page to a public one?

Please follow the below steps for make visual force page public.
  • go to Setup > Develop > Sites,
  • register your Force.com subdomain name,
  • create a new Force.com Site
  • next to 'Site Visualforce Pages' click Edit
  • add your page to the list of Enabled Visualforce Pages

Please check the below links for more details.

https://developer.salesforce.com/page/An_Introduction_to_Force.com_Sites

https://help.salesforce.com/HTViewHelpDoc?id=sites_public_access_settings.htm

,

how to display two objects fields in visualforce page by using wrapper class?



Please find below an example of how to accomplish this.

I've included 2 ways to do this:
Using a single query

Using a wrapper class My controller (AccountContactWrapperController.class): 

public class AccountContactWrapperController {

    public List<Account> accounts{get;set;}
    public List<ACWrapper> ACWrappers{get;set;}

    public AccountContactWrapperController(){
        this.ACWrappers = new List<ACWrapper>();
        this.accounts = new List<Account>();

        //Get Accounts & Related Contacts in 1 query
        List<Account> accs = [Select Id, Name, (Select Id, FirstName, LastName From Contacts) From Account Limit 1];
        this.accounts = accs;

        //Get Accounts & Contacts in separate queries for Wrapper
        List<Account> accsForWrapper = [Select Id, Name From Account Limit 1];
        List<Contact> consForWrapper;
        Account acc;
        if(accsForWrapper != null && !accsForWrapper.isEmpty()){
            acc = accsForWrapper.get(0);
            consForWrapper = [Select Id, FirstName, LastName From Contact Where AccountId =:acc.Id];
        }
        if(consForWrapper != null){
            ACWrapper wrapper = new ACWrapper(acc, consForWrapper);
            this.ACWrappers.add(wrapper);
        }
    }

    public class ACWrapper{
        public Account account{get;set;}
        public List<Contact> contacts{get;set;}

        public ACWrapper(Account acc, List<Contact> cons){
            account = acc;
            contacts = cons;
        }
    }

}


My VF page (AccountContactWrapperTest.page): 

<apex:page controller="AccountContactWrapperController" >
<apex:form >

<!--Display Account & Contact info from 1 Query-->
<apex:pageBlock title="Info From Query">
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:Column value="{!a.Name}" />
<apex:Column headerValue="Contact Names">
<apex:repeat value="{!a.Contacts}" var="c">
{!c.FirstName} {!c.LastName} <br />
</apex:repeat>
</apex:Column>
</apex:pageBlockTable>
</apex:pageBlock>

<!--Display Account & Contact info from 1 Wrapper class-->
<apex:pageBlock title="Info From Wrapper class">
<apex:pageblocktable value="{!ACWrappers}" var="w">
<apex:Column value="{!w.account.Name}" />
<apex:column headervalue="Contact Names">
<apex:repeat value="{!w.contacts}" var="c">
{!c.FirstName} {!c.LastName} <br/>
</apex:repeat>
</apex:column>
</apex:pageblocktable>
</apex:pageBlock>
</apex:form>
</apex:page> 


      Output:

, , ,

difference between trigger.old and trigger.oldmap

Trigger.old: Returns a list of the old versions of the sObject records.
Note that this sObject list is only available in the update and delete triggers.

Trigger.oldMap: A map of IDs to the old versions of the sObject records.Note that this map is only available in the update and delete triggers.

Let say  you have a custom object Account.

Trigger.old&nbsp;means it is a&nbsp;List<Account>

Trigger.oldMap&nbsp;means it is a&nbsp;map<Id,Account>

Salesforce System.assert(Methods)

System.assert()

System.assert() detailed explanation below.

A simple scenario would be to create a test class +methods in which some work is done (e.g. put something into the DB, update a field or whatever). Once this is done you would use System.Assert functions to check what has been done.

For example:-

integer i = 0;
integer j = 1;

//this would throw an error and cause your test to fail
System.assertEquals(i,j);
//this would pass
System.assertNotEquals(1,i);
etc...

You may put something into the DB via an insert. You may then expect a trigger to run so you would then reload the item and check that the trigger has fired correctly as certain fields have been updated.

Really you could interchange any of the Assert functions dependent on your logic. Up to you. I find it easier to use AssertEquals as I mostly want to check that a proper number of records have been returned or that something I know about has happened and I'm expecting a certain result etc...

You are really just trying to create a method to test that some logic (i.e. code - trigger, apex...) is working correctly. Testing is required to cover a certain percentage of a class to enable packaging and a trigger must be tested (greater than 0%) to enable packaging.

Example for system.assert logic :

System.Assert(Today.Year()==2016);

Alternatively System.AssertEquals(2016,Today.Year());

Or System.AssertNotEquals(2015,Today.Year());

Could call a user function like:-

System.Assert(isYear2016());

public boolean isYear2016(){
return (Today.Year==2016 ? true : false);
}
, , , ,

Salesfrorce Batch apex and schedulable apex

Batch Apex in Salesforce
 
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
 
Start method


          The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.

Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

 This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.
 
Execute Method

          The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

Syntax: global void execute(Database.BatchableContext BC, list<P>){}
 
This method takes the following:
o    A reference to the Database.BatchableContext object.
o    A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
Batches of records execute in the order they are received from the start method.
 
Finish Method

Syntax: global void finish(Database.BatchableContext BC){}
 
The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
 
Example of Batch Apex Class: 
 
Batch Schedule Class
 
global class batchContactUpdate implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Id, FirstName,LastName FROM Contact';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
         for(Contact a : scope)
         {
             a.FirstName=a.FirstName+'FirstName is Updated';
             a.LastName = a.LastName +'LastName is updated';         
         }
         update scope;
    } 
    global void finish(Database.BatchableContext BC)
    {
    }
}
 
Schedule Class
 
global class BatchScheduleUpdate implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
      
        // We now call the batch class to be scheduled
        BatchContactUpdate b = new BatchContactUpdate ();
      
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,200);
    }
  
}
 

Schedule from Developer Console

BatchScheduleUpdate batchSch=new BatchScheduleUpdate();
String sch='0 5 2 * * ?';
//System.schedule(String jobName, String cronExp, APEX_OBJECT schedulable);
System.schedule('Batch Schedule', sch , batchSch);

 

, , ,

difference between a normal wrapper and a REST API wrapper



Please find the difference between a normal wrapper and a REST API wrapper.


Wrapper Class : A Wrapper Class (or the Wrapper Pattern) is where you declare a Class as a container for an sObject to extend the functionality only for display or processing purposes (i.e. you don't intend for that attribute to be persisted) - the classic example is a checkbox to select records. I would say that a DTO is a slightly dumbed down version of such a wrapper (used in conventional OOP to pass structured data between the layers)

REST API Wrapper : A REST API wrapper is something slightly different. Salesforce exposes a REST API and if you were to invoke that say from C#, you would have to perform a set of common steps such as login, query, etc. To make this available in C# by abstracting the innards of the actual REST calls to salesforce and exposing only the developer relevant detail, you could write a rest wrapper which performs these commonly used functions - creates requests, parses responses, etc.

For use cases please refer to the below link.
https://www.godaddy.com/garage/webpro/wordpress/3-practical-use-cases-wp-rest-api/
, , ,

How can I show/ hide a div when the checkbox is selected?

Here is simple code With javascript.


<apex:page >
 <head>

 </head>
 <apex:form >
  <script>
  function HideMsg(istrue)
  {
    var checkval = document.getElementById("msg")
    if(istrue.checked )
    {  
        var checkval = document.getElementById("msg").style.display='block';
    }
    else
    {
        var checkval = document.getElementById("msg").style.display='none';
    }
  }
  </script>
  <apex:pagemessages />

  <div>
   <apex:inputCheckbox id="checkbox" onchange="HideMsg(this);"/>
  </div>
  <div class="showp" style="display: none" id="msg">
  <p>Hello World</p>
  </div>
 </apex:form>
</apex:page>
,

Convert Date to DateTime in salesforce


 

Simple code is used to convert Date to DateTime data type using Apex


Sample Code:

 
 
Date dToday = System.Today();
Datetime dt = datetime.newInstance(dToday.year(), dToday.month(),dToday.day());
, ,

Convert String to Date in salesforce

 

Simple code is used to convert String to Date data type using Apex


Sample Code:

String today = '7/26/2016';

Date dt = Date.parse(today);

,

Thursday, 30 June 2016

How to Installation box.com and Initial Setup Salesforce?



Installation Prerequisites Two Box accounts are required to install the Box for Salesforce integration:
  • Box Service Account:
    • to be used exclusively for integration purposes and does not belong to an individual end user, 
    • owns the Salesforce content on Box and makes API calls from Salesforce to Box for the entire enterprise
    • If you don’t already have a Box Service Account, create one (i.e., add boxforsalesforce@example.com as a managed user).
  • Box User Account: to link a user’s Salesforce account to their Box account.
Note: The Service Account and User Account must be two different accounts (although both can be managed users in your enterprise). The integration will not allow you to login with the same account in both places.

Two types of Salesforce accounts will access the Box for Salesforce integration:
  • Salesforce Admin Account:
    • to install packages in Salesforce in order to link the installed package to the Box Service Account
    • can also be a regular user of Box for Salesforce integrations.
  • Salesforce User Account: to link a Box User Account and access Box content.


Installing Box for Salesforce

  1. Log into Salesforce as a Salesforce Admin.
  2. Navigate to the package installation link.
  3. At separate points during the installation, you will be asked to:
    • Accept and Approve Third-Party Access for remote settings.
    • Grant access to all users.
    • Click Next or Continue in other screens to complete the installation.
  4. When you complete the installation, the screen will return to the Salesforce Box Connector App (Managed) page.

    box for salesforce setup.jpg
  5. Click the + tab to view the All Tabs page.
  6. Click Box Settings to view the Connect Salesforce to Box page.
  7. Click the Box API Admin Login button to view the Box API login page.
  8. Enter the Box Service Account credentials (see the Installation Prerequisites section above).

    box admin settings setup.jpg
  9. Specify the name for your Root Folder, e.g. Salesforce-<Org Identifier>.
  10. Specify folder settings for Lead conversions (optional)
  11. Specify your company's subdomain, e.g. if you log into Box at cloud.app.box.com, your subdomain is "cloud".
  12. At this point, you can enable (suggested) or disable Seamless Login and Auto-Collab on the same page, and click Save Settings. See the Enabling Auto-Collab for a User section below for more information.
  13. Add the Box functionality to Salesforce objects (e.g. Opportunities, Accounts, etc.) by following the steps under Embedding Box in a Salesforce Page.




Salesforce box integration.

, ,

Saturday, 18 June 2016

Salesforce auto-create folders for all Account? Box.com




 This is batch class use to auto-create folder for account .






global class autofolderCreator  implements Database.Batchable<sObject>,Database.Stateful,Database.AllowsCallouts{
  global

 Map<String,String> boxFmap = new Map<String,String>();
   global autofolderCreator(){
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
        // this loop use to map existing folder with account so prevent for duplication.
       for(box__Folder_Meta__c mp :[select id,name,box__Folder_Id__c ,box__Folder_Name__c,box__Folder_Share_Link__c from box__Folder_Meta__c limit 9999]){
           boxFmap.put(mp.box__Folder_Name__c,mp.id); 
       }
      String query = 'Select id,name from account';
      return Database.getQueryLocator(query);
   }
  
   global void execute(Database.BatchableContext BC, List<Account> scope){
       box.Toolkit boxToolkit ;
       for(Account a : scope){
            if(!boxFmap.containsKey(a.name)){
                boxToolkit = new box.Toolkit();
                String accountFolderId = boxToolkit.createFolderForRecordId(a.id, null, true);
                boxToolkit.commitChanges();
            }
      } 
    }
   global void finish(Database.BatchableContext BC){
   }
}

 Box.com,Auto create folder for account.

, , ,

Get Gmail, Docs, Drive, and Calendar for business