Search In This Blog

2016-10-29

Output data in 3 columns by repeat in Visualforce


There're a lot way to output a list of strings in 3 columns, like 3*n.

Here are two ways.

First need to get the value of list before output, list should be able to public get. Here is an example.
// [sample] string[]
public String[] getSampleStrings() {
    return new String[]{'ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE'};
}
Way 1: Use first and rows in apex:outputPanel
// Repeat sample start (by first and rows)
<apex:outputpanel layout="block">
    <apex:repeat first="1" rows="3" value="{!sampleStrings}" var="sampStr">
        <apex:outputtext style="padding: 0 10px;" value="{!sampStr}">
    </apex:outputtext></apex:repeat>
</apex:outputpanel>
<apex:outputpanel layout="block">
    <apex:repeat first="4" rows="3" value="{!sampleStrings}" var="sampStr">
        <apex:outputtext style="padding: 0 10px;" value="{!sampStr}">
    </apex:outputtext></apex:repeat>
</apex:outputpanel>

2016-09-28

Changing a user's email address without confirmation.

When try to change user's email, Salesforce will send a confirmation mail to new email address and a notification mail to old email address in security purpose.But sometimes user don't want to get further notifications.

To avoid send notification mail to old email, try ways follow. (All ways are no working with owner)

Way 1. Set Setup | Manage | User Management | Users
When change the email address, "Generate new password and notify user immediately" checkbox (at the bottom of the edit screen) need to be checked. Then the email address will get committed right away, no more confirmation needed! But obviously the user then gets sent a new password.


Way 2. Change email through Develop console
1.Select user data [select id,email,username from user]
2.Change the target user's email and click [Save Rows]
3.Click [Refresh Grid] to check if email is been changed.
*(2016/09/28) Some license may not working, like "Company Communities".


Way 3. Change email by code
User user = [select id,email from user where id = 'target user id'];
user.email = 'new_email@exmple.com';
update user;
*If use upsert, it will have a error: "DML not allowed on User". No matter if the record already exists or updating or creating new
*(2016/09/28) Some lisence may not working, like "Company Communities"
*(2021/11/5 update) Looks like Salesforce had removed Way 3 completely.

2016-09-27

[Regex]Check English / Spanish / Franch / Arabic characters

Keep these here as a memo.


English characters:
Public Boolean checkEnglish(String value){
    return Pattern.matches('[^a-zA-Z0-9 ]+', value);
}

Spanish characters:
Public Boolean checkSpanish(String value){
    return Pattern.matches('^[0-9a-zñáéíóúü]+', value);
}

France characters:
Public Boolean checkFrance(String value){
    return Pattern.matches('[^a-zA-Z0-9 àâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]', value);
}

How to write Apex test class


An Apex test class is used to confirm if instructions and methods in an application or program are working correctly as desired. Tests can be written for many classes.

Since Salesforce require at least 75% of the code to be tested before it can be deployed to the organization. There are different test classes run to achieve the 75% minimum requirement tests on task codes.

To create an Apex class: [Setup]-[Develop]-[Apex Classes]-[New].
It can also be create through develop console, [You username]-[Develop console]-[File]-[New]-[Apex Class]

Basic strunction of test class
@isTest 
public class BaseTest { 
    // Test Method 
    public static testmethod void Test1(){ 
        // Prepara data for test
        List<Account> accounts = new List<Account>{};
        for(Integer i = 0; i < 200; i++){
            Account a = new Account(Name = 'Test ' + i);
            accounts.add(a);
        }
        Test.startTest(); 
        // Put test target here
        insert accounts;
        Test.stopTest();  
    } 
} 

2016-09-26

Loops in Apex class

For now(2016/9/26), Apex supports do-while, while, and for loops.

do-while:
Integer count = 1;
do {
    System.debug('count' + count);
    count++;
} while (count < 3);

while:
Integer count = 1;
while (count < 4) {
    System.debug('count' + count);
    count++;
}

for(loop in array):
Integer[] is = new Integer[]{1,2,3,4,5};
for (Integer i: is) {
 System.debug(i);
}
Queries can also be embedded in the special for syntax.
for (Test__c tmp : [SELECT Id FROM Test__c]) {
   // ...
}

2016-09-21

Use template in Visualforce page

If pages have same part like header or footer, use page template will be more efficient.

Salesforce provides some page template. For example, when you create a community site, Salesforce will create a page template named CommunitiesTemplate.

<apex:page showHeader="false" sidebar="false" id="CommunitiesTemplate">
  <apex:stylesheet value="{!$Site.Prefix}/communities/CommunitiesStyles.css"/>
  <apex:insert name="header"/>
  <apex:insert name="body"/>
  <apex:insert name="footer"/>
</apex:page>

<apex:insert name="header"/> is the header part.
<apex:insert name="body"/> is the main content part.
<apex:insert name="footer"/> is the footer part.

<!-- Import template by id -->
<apex:composition template="CommunitiesTemplate">
       <apex:define name="header">This is header used to contain something like: logo, nav menu...</apex:define>
       <apex:define name="body">This is the body  used to contain contents and sidebar.</apex:define>
       <apex:define name="footer">This is the footer. Usually use to contain copyright.</apex:define>
</apex:composition>

2016-09-17

How to validate email address with Regex expression in Visualforce page by Apex

When user input email address in Visualforce page, normally need to input the email address again as a confirm email address to make cross check.

If you create a field to save confirm email address. For example, this email address will be saved to Field(Email) in object(Contact), and use inputField tag will be convenient.
<apex:inputField value="{!Contact.Email}"/>
When you try to save, Salesforce will make the format check for you.

But if confirm email address is not a field in object, you may need to check format of confirm email address by Apex. Use Pattern.matches() will be a choice.
Regex foremail format check:
'^([0-9a-zA-Z+_.-]*[0-9a-zA-Z]+[@][0-9a-zA-Z+_.-]+\\.[0-9a-zA-Z+_.-]*)$'
*example email: huang.hai@randsfdc.blogspot.jp

Return the result of format check:
return Pattern.matches('^([0-9a-zA-Z+_.-]*[0-9a-zA-Z]+[@][0-9a-zA-Z+_.-]+\\.[0-9a-zA-Z+_.-]*)$', val); 
*val is the value of email address

To check are these two email address same, you can use String.equals(). Like: emailOne.equals(emailTwo).

String.equals(): Upper char and lower char will be treated as different char.

How to get random strings by Apex?

This post will introduce how to make a random string for using as a token or as a special code.

First, make sure what string you want to get. If you just want a random string within all number, use Math.random() and do for loop will be a easy way. But if you want to pick up the chars or numbers from a special list, try below.

// the list that you want to pick chars and numbers from
String CharList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';

// position in list, count will start from 0. EX. 'a' is in position 0, 'b' is in position 1
Integer position;

// length of random strings, ex. 20
Integer LengthRequired = '20';

// get 20 chars from list randomly
for(Integer i = 0; i <= LengthRequired; i++) {

    position = Integer.valueof(String.valueof(Math.roundToLong(CharList.length()*Math.random()))) -1;

    // the random Strings
    String Res += CharList.substring(position,position+1);

}

2016-09-09

How to set robots.txt file for force.com site?

When use force.com to public a website, it will be unsure whether the site can be indexed by google search engine or not if you don't set Site Robots.txt. Normally it is hard to be indexed.

To make it 100% can be indexed, it is better to create a robots.txt file. It is easy to use Visualforce page to create one.

Step 1.
New a Visualforce page. Ex. named as 'robots'.

Step 2.
Set contentType of tag <apex:page> as 'text/plain' to make Visualforce page 'robots' will be treat as a text file. As below:
<apex:page contentType="text/plain">
User-agent: *
Disallow:
Allow: /
</apex:page>
*If there are something that don' t want to be indexed, you can disallow they. Ex. 'Disallow: /unindexed_page/'. Same to Allow.

By the way, it will be unindexed as follow:
<apex:page contentType="text/plain">
User-agent: *
Disallow:/
Allow:
</apex:page>
Step 3.
Set Site Robots.txt. In Setup | Develop | Sites | Edit
Use magnifier glass mark to find the Visualforce page 'robots' or just input the name, and save.

2016-09-08

Bounced email: all failed error mail:#< #5.3.0> #SMTP#

Try to do some test cases, I sent a lot of mails(more than 60) to invalid mail address by mail alert through SFDC workflow.

#Workflow rule: When create an new record, a mail will be sent to the invalid email.

After some a lot failed mail, I sent a mail to available email, but it was failed either.

#Debug log shows mail was sent out by workflow, but I can't find the mail in inbox of "sample@mail.com".

#Get error info from error mail as "sample@mail.com#< #5.3.0> #SMTP#"

As email received succeed just before the test and the mails from salesforce isn't in block list. It should not be the problem in mail setting.

Check Configure Deliverability Settings says:
Bounced email
Email that is addressed to an invalid recipient and returned to the sender. If a sender sends several email messages that bounce, the email server might slow or block the delivery of all email from that sender.
It looks like the reason why mail can't be received. So wait the next day(UTC00:00) and it is fixed.

2016-09-06

How to get time in Salesforce?

There are a few way to get time.
1. Date.today()
  Returns the current date in the current user's time zone.
  Return Type: Date
  More info:Date Class

2. System.now()
  Returns the current date and time in the GMT time zone.
  Return Type: Datetime
  More info:System Class

3. datetime.now()
  Returns the current Datetime based on a GMT calendar.
  Return Type: Datetime
  The format of the returned datetime is: 'MM/DD/YYYY HH:MM PERIOD'
  More info: Datetime Class

4.datetime.now().time()
  Returns the current time based on a GMT calendar.
  Return Type: Time
  The format of the returned time is: 'HH:MM PERIOD'

5.datetime.now().getTime()
  Returns the current time from 1970/1/1.
  Return Type: Integer

6.NOW()
  Returns the current Datetime based on a GMT calendar.
  Return Type: Datetime


2016-09-02

Use Apex class to redirect page

Use Apex class to do this action: When open page 'RedirectPage', move to 'TargetPage' directly.

RedirectPage is name of Visualforce page
Code:
<apex:page controller="RedirectCtrl" action="{!doRedirect}">
    Redirect to TargetPage directly...
</apex:page>

RedirectCtrl is name of Apex class that use to control 'RedirectPage'
Code:
public class RedirectCtrl {
   // create redirect function
   public PageReference doRedirect() {
        // set target page
        PageReference pageRef = Page.TargetPage;
        // set a parameter to url, format 'site.com?PARAME_TYPE=PARAME_TYPE_STR'
        pageref.getParameters().put('PARAME_TYPE','PARAME_TYPE_STR');
        // do page redirect
        pageRef.setRedirect(true);
       // begin to redirect
        return pageRef;
    }
}

TargetPage is name of Visualforce page that 'RedirectPage' will redirect to.
Code:
<apex:page>
    This is target page of redirect action.
</apex:page>

That is all.

2016-08-18

Eclipse with Force.com IDE

Prerequisites
  • Eclipse
  • JDK, Runtime Environment 7 or later
Step 1.
Launch Eclipse, Help > Install New Software, click Add

Step 2.
Set Name as "Force.com IDE"
Set Location as "http://media.developerforce.com/force-ide/eclipse42"
Then click OK

Step 3.
At least select Force.com IDE from the download list. If you don't konw which one is needed, select all. Then click Next
If you want an older version, uncheck the "Show only the latest versions of available software".

Step 4.
Click Next in Install Details dialog. Then accept the terms and click Finish. When Eclipse finished installation, you will be prompted to restart Eclipse.

Step 5.
You can check is Force.com installed successful by Eclipse > Window > Perspective > Open Perspective > Other. If you can see Force.com in list, it means success.

Step 6.
Select Force.com and click OK. You can start to develop now.

2016-08-17

How to create a public website or application by Salesfore

Recently, I supported a few of  SFDC beginners build an online membership management system.

Then they asked me a question: how to create a public site and application with salesforce? No need to log in with a username and password.

Public website is available in Salesforce Classic Developer/Enterprise/Performance/Unlimited Edition. There are steps below.

Step 1.
Need a Manage User

Step 2.
Log in Salesforce with Manage User, click the setup link in right-top.

Step 3.
Use Quick Find box to search 'sites' and select 'Sites'. Or find it in left bar: Build > Develop > Sites
There will be a introduce to What is a Site? You can read it to get more information about Force.com site.

Step 4.
Choice a unique name for your site, you can check it by 'Check Availability' button. If the name is available, then check the agree checkbox and click 'Register My Force.com Domain' button to register a custom Force.com for your org.
Attention: This name can't be modified after be registered.

Step 5.
New a page for this site and input the fields. You can just input the necessary fields.
  • Site label: Appears in user interface.
  • Site Name: Will be used when referencing the site in the SOAP API
  • Site Description: An optional description.
  • Site Contact: The account to receive site-related communications.
  • Default Web Address: Public will use this URL to access your site.
  • Active: Publish the site right after save or not.
  • Active Site Home Page: The landing page, choice a Visualforce page
  • Inactive Site Home Page: Default is maintenance page, you can customize it.
  • Site Templates: Provide page layout and stylesheet.
  • Site Robots.txt: Help to be searched by Google.
  • Site Favorite Icon:
  • Analytics Tracking Code: Like Google Analytics Code ID
  • URL Rewriter Class: The Apex class used for URL rewriting on this site.
  • Enable Feeds
  • Clickjack Protection Level:
  • Require Secure Connections(HTTPS)
  • Guest Access to the Support API
Step 6.
Save and check the site.
If site is inactive, it will a maintenance page as below.

If license is trial edition, you can't find sites menu and unable to public the site.


How to display Visualforce page as PDF

Add renderAs="pdf" in <apex:page> tag as below.
<apex:page renderAs="pdf">
Add CSS style to set format of page.
@page {
size: letter;
@top-center {content: "PDF Sample";}
@bottom-center {content: "Page " counter(page) " of " counter(pages);}
}
*Most used page size: landscape/8.27in 11.69in (A4 width and height)

Attention:
@page must be inside of <html><head><style>, or include as a static resource.
<apex:page renderAs="pdf">
    <html>
        <head>
            <style>
                @page {...}
            </style>
        </head>
    </html>
</apex:page>

Use page-break to control when is next page. If you didn't set page break, it will only display in next page when out of bound.
<style>
.page-break {display:block; page-break-after:always;}
</style>
<body>
        <div class="page-break">
                <apex:outputText >Page 1</apex:outputText>
        </div>
        <div>Page 2</div>
</body>

2016-08-16

Solve MavensMate LOGIN_MUST_USE_SECURITY_TOKEN error

You may happened to LOGIN_MUST_USE_SECURITY_TOKEN error when you use MavensMate.

It is because the access is out of trusted networks. You can find the solution in warning.

Login to Salesforce, My Settings > Personal > Reset My Security Token > Reset Security Token

2016-08-15

How to develop SFDC project with Sublime Text and MavebsMate

To develop SFDC project with Sublime Text 2/3, you need to make some preparations.

Step 1.
In Mac:
Use Command+Shift+P to open 'Package Control' or Menu bar > Sublime Text > Preferences > Package Control

In Windows:
Menu bar > Preferences > Package Control

Step 2.
Input 'Package Control: Install Package', pull enter key.

Step 3.
Search 'Maven' and install it.

Step 4.
MavensMate > Settings > User
Find '"mm_workspace"' and set your workspace folder like:
"mm_workspace" : [
         "/my/workspace",
         "/my/other/workspace",
         // Input path to your workspace folder
]
Then save.

Step 5.
MavensMate > Project > New Project
Input your organization information and Create Project.

If you happened to 'LOGIN_MUST_USE_SECURITY_TOKEN' error, check here.

2016-08-12

Prevent double submission of forms.

When save customize form data with apex:commandButton, double submission is needed to be attention.

If you use standard control and standard save function, salesforce may help you to prevent double submission. But when you use a customize button action to save data, you will need to do by yourself.

Double submission can be prevented by JavaScript easily and efficiently.

Put code below inside <head></head>
<script type="text/javascript"> 
var isSave = false; 
function check(){ 
if (!isSave) { 
isSave = true; 
return true; 
} 
return false; 
} 
</script> 

Then put <apex:commandbutton> inside of <apex:form></apex:form>.
<apex:commandButton action="{!test}" value="Refresh" onclick="return check();"/>
*value is the button's name; when click this button, function check() will be called and return boolean value.