New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Wednesday, 29 August 2012

Upcoming Posts

  • Annotations (Yes)
  • Static Resources
  • Visualforce Order of Execution (getRequest and postbackRequest)
  • External Id
  • Aprrovals

Friday, 24 August 2012

After deleting a record in master object what will happen for the records of junction object

If I delete a record in master object what will happen for the records of junction object?
Solution:
* Suppose A and B are master objects and C is the child object
Few important points :
  1. One Object can have only two Master-Detail relationships.
  2. If we delete record A (First Master detail relationship is always primary) – then child record c will be deleted.
  3. If we delete record B then in this case also child record C will be deleted.
  4. If we delete record c then only C will be deleted , master record will not be deleted.
  5. If child C has two Master record A and B, Where A is primary relation then Child record C will inherit the look and feel of Parent object A.

Moving data from sandbox to production

How can I move Data from SandBox to Production?                                                                  
Solution:                                                                                                                                           
* We can't move your data from sandbox to production.
* We can only move components,applications and profile settings using changesets.
* FYI (For Your Information): We can move data from production to sandbox.
* Use export and import option for moving data into production.

Note: Indirectly, We can use Data Loader to move data from Sandbox to a csv file, and the import the data from csv file into Production.

Difference between Sales Cloud and Service Cloud

Sales Cloud
* "Sales Cloud" refers to the "sales" module in salesforce.com.
* It includes Leads, Accounts, Contacts, Contracts, Opportunities, Products, Pricebooks, Quotes, and Campaigns (limits apply).
* It includes features such as Web-to-lead to support online lead capture, with auto-response rules.
* It is designed to be a start-to-end setup for the entire sales process; you use this to help generate revenue.

Service Cloud
*"Service Cloud" refers to the "service" (as in "customer service") module in salesforce.com.
* It includes Accounts, Contacts, Cases, and Solutions.
* It also encompasses features such as the Public Knowledge Base, Web-to-case, Call Center, and the Self-Service Portal, as well as customer service automation (e.g. escalation rules, assignment rules).
* It is designed to allow you to support past, current, and future clients' requests for assistance with a product, service, billing, etc; you use this to help make people happy.

* The differences between Sales Cloud and Service Cloud are the same across each "edition" ("professional", "enterprise" and "unlimited"), mainly outlined above.
* The differences, as you can gather from the prior paragraphs, is that each cloud is designed to support a specific set of features that you would use to sell services and products, and support those services and products (respectively).

The main differences you will find are the limits between each edition. Professional Edition provides basic functionality; you can create limited customized UI pages (Visualforce), and you can use standard automation (e.g. assignment, escalation, and auto-response rules). Enterprise Edition provides additional features, including custom automation (e.g. workflow rules, Apex Code), improved Visualforce functionality, integration (API) access, generally increased limits, and additional customization features (e.g. more fields per object). Unlimited Edition is an extension of Enterprise Edition, and includes more storage space, premier support, more objects, increased API limits, and so on.

I would look here: http://www.salesforce.com/crm/editions-pricing.jsp, as well as the "Full Comparison Chart" located at the bottom of this page (PDF format), for additional information between each edition. Make sure you check each "tab" on that page for details about features for each cloud/app. You might also be interested in speaking to a sales representative with these types of questions.

Review Points

* We can only use runAs {System.runas()} in a test method. It is not possible to use it in Apex Classes.
* Developer Console by default works in User Mode. 
* For before mode in case of update for an event (if the update is for the same object on which we are writing the trigger) no need to use 'UPDATE' DML Statement.
* Data Loader time zone and sandbox or production time zone should be same while working with date fields. 
 * If we convert the lead record then that lead record won't exists in lead object but when running the reports it will display the converted leads.







Please see the below Comments

Friday, 17 August 2012

apex:component

How to disply custom client-side error messages on VF pge

Custom Error Messages on VF page

How to dipaly client side error messages like above?
Solution:
 By using jquery you can diplay error messages as you mentioned in the above image
1. First download the jquery file here.
2. If it is not downloading copy the code and paste it in notepad and save it with jquery.js like that.
3. Then upload that file into static resources.
4. In your vf page use the following code
<apex:page standardcontroller="Account" showHeader="false" standardStylesheets="false">
    
    <apex:includeScript value="{!$Resource.jquery}"/>
    <apex:includeScript value="http://ajax.microsoft.com/ajax/jquery.validate/1.6/jquery.validate.min.js"/>
    
    <script type="text/javascript"> 
        $(document).ready(function() {
             
            $('[id$=commentForm]').validate();             
             
            $('[id$=name]').rules("add",{
                required: true,
                minlength: 5
            });     
            
            $('[id$=email]').rules("add",{
                required: true,
                email: true
            });      
            
            $('[id$=url]').rules("add",{
                url: true
            });
            
            $('[id$=comment]').rules("add",{
                required: true
            });
            
            $('[id$=pwd]').rules("add",{
                required: true,
                minlength: 5
            });
            
            $('[id$=cpwd]').rules("add",{
                required: true,
                minlength: 5,
                equalTo: '[id$=pwd]'
            });      
            
            /* Customised the messages */
            jQuery.validator.messages.required = "You better have entered a value.. or else!"; 
            jQuery.validator.messages.equalTo = "No silly, you're supposed to type the same set of characters AGAIN.";                                                
        });
        
    </script>   
    
    <!-- Ignore my template -->
    <apex:composition template="Template">
        <apex:define name="title">
            <a href="http://thesilverlining-developer-edition.na7.force.com/jqueryvalidatedemo/">jQuery Forms Validation Demo</a>
        </apex:define>
        
        <apex:define name="blurb">
            <p>
                Fiddle with the form entering combinations of correct and incorrect values to see the validation rules in action. Hitting the sumbit button will also trigger form checking.
            </p>
        </apex:define>


        <apex:define name="content">    
            <apex:outputPanel layout="block" style="text-align:center; font-size:12px;padding: 4px">
                <apex:form id="commentForm" > 

                        <apex:outputlabel for="name">Name <span class="star">*</span></apex:outputlabel> 
                        <apex:inputtext id="name" value="{!account.name}"/>
                        <br/>
                        <apex:outputlabel for="email">E-Mail <span class="star">*</span></apex:outputlabel> 
                        <apex:inputtext id="email"  value="{!account.name}"/> 
                        <br/>
                        <apex:outputlabel for="url">URL (optional)</apex:outputlabel> 
                        <apex:inputtext id="url"  value="{!account.name}" /> 
                        <br/>
                        <apex:outputlabel for="comment">Your comment <span class="star">*</span></apex:outputlabel> 
                        <apex:inputtextarea id="comment" value="{!account.name}" style="width: 30%"/>
                        <br/>
                        <apex:outputLabel for="pwd">Password <span class="star">*</span></apex:outputLabel>
                        <apex:inputSecret id="pwd" value="{!account.name}"/>
                        <br/>
                        <apex:outputLabel for="cpwd">Confirm Password <span class="star">*</span></apex:outputLabel>
                        <apex:inputSecret id="cpwd" value="{!account.name}"/>                        
                        <br/>
                        <input type="submit" />
            
                </apex:form>
            
            </apex:outputPanel>
            
        </apex:define>
        
    </apex:composition>
     
</apex:page>
5. make changes according to your vfpage.
6. Then you will get the desired output
Refer Here:
 http://th3silverlining.com/2010/03/02/visualforce-form-validation-enhanced/#more-543

Thursday, 16 August 2012

Invoking Callouts Using Apex - 2

SOAP Services: Defining a Class from a WSDL Document
* Classes can be automatically generated from a WSDL document that is stored on a local hard drive or network.
* Creating a class by consuming a WSDL document allows developers to make callouts to the external Web service in their Apex scripts.
Note:
- Use Outbound Messaging to handle integration solutions when possible.
- Use callouts to third-party Web services only when necessary.
To generate an Apex class from a WSDL:
1. In the application, click Your Name ➤ Setup ➤ Develop ➤ Apex Classes.
2. Click Generate from WSDL.
3. Click Browse to navigate to a WSDL document on your local hard drive or network, or type in the full path. This WSDL document is the basis for the Apex class you are creating.
Note:
- The WSDL document that you specify might contain a SOAP endpoint location that references an outbound port.
- For security reasons, Salesforce restricts the outbound ports you may specify to one of the following:
- 80: This port only accepts HTTP connections.
- 443: This port only accepts HTTPS connections.
- 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.
4. Click Parse WSDL to verify the WSDL document contents.
- The application generates a default class name for each namespace in the WSDL document and reports any errors.
- Parsing will fail if the WSDL contains schema types or schema constructs that are not supported by Apex classes, or if the resulting classes exceed 1 million character limit on Apex classes.
- For example, the Salesforce SOAP API WSDL cannot be parsed.
5. Modify the class names as desired.
- While you can save more than one WSDL namespace into a single class by using the same class name for each namespace, Apex classes can be no more than 1 million characters total.
6. Click Generate Apex.
- The final page of the wizard shows which classes were successfully generated, along with any errors from other classes.
- The page also provides a link to view successfully-generated code.
* The successfully-generated Apex class includes stub and type classes for calling the third-party Web service represented by the WSDL document.
* These classes allow you to call the external Web service from Apex.
Note the following about the generated Apex:
* If a WSDL document contains an Apex reserved word, the word is appended with _x when the Apex class is generated.
* For example, limit in a WSDL document converts to limit_x in the generated Apex class.
* If an operation in the WSDL has an output message with more than one element, the generated Apex wraps the elements in an inner class.
* The Apex method that represents the WSDL operation returns the inner class instead of the individual elements.
* After you have generated a class from the WSDL, you can invoke the external service referenced by the WSDL.
How to run generated class from WSDL
BookrWs.BookWs stub = new BookrWs.BookWs();//Top level class name.Inner level class name

stub.sessionHeader = new BookrWs.sessionHeader_Element();

stub.sessionHeader.sessionID = userInfo.getSessionID();

stub.insertBook('SOAP19','VASU',1000);

Refer Here
* Salesforce API Integration Using SOAP-based Web Services

                   Previous                                                                                              Next

Invoking Callouts Using Apex

Invoking Callouts Using Apex
* An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web service or sending a HTTP request from an Apex script and then receiving the response.
 Tightly Couple Architecture

* Apex provides integration with Web services that utilize SOAP and WSDL, or HTTP services (RESTful services).
Note:
* Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the callout fails.
* Salesforce prevents calls to unauthorized network addresses.
* Callouts enable Apex to invoke external web or HTTP services.
*Apex Web services allow an external application to invoke Apex methods through Web services.
Adding Remote Site Settings
To add a remote site setting:
1. Click Your Name ➤ Setup ➤ Security Controls ➤ Remote Site Settings.
2. Click New Remote Site.
3. Enter a descriptive term for the Remote Site Name.
4. Enter the URL for the remote site.
5. Optionally, enter a description of the site.
6. Click Save.
Types of WSDL's
1. Enterprise WSDL
    * It is a big WSDL which contains information about schema of organization.
    * Strictly Typed: For Integer if we give 3.19 like that then it will not accept and throw error.
    * When schema is modified then we have to recreate new enterprise WSDL.
2. Partner WSDL
    * Loosly Typed: For Integer if we give 3.19 like that then it will accept and not throw error.
    * When schema is modified then it will automatically updated.

                   Previous                                                                                              Next

Web Services - 2

Considerations for Using the WebService Keyword
* You cannot use the webService keyword when defining a class.
* However, you can use it to define top-level, outer class methods, and methods of an inner class.
* You cannot use the webService keyword to define an interface, or to define an interface's methods and variables.
* System-defined enums cannot be used in Web service methods.
* You cannot use the webService keyword in a trigger because you cannot define a method in a trigger.
* All classes that contain methods defined with the webService keyword must be declared as global.
* If a method or inner class is declared as global, the outer, top-level class must also be defined as global.
* Methods defined with the webService keyword are inherently global.
* These methods can be used by any Apex script that has access to the class.
* You can consider the webService keyword as a type of access modifier that enables more access than global.
* You must define any method that uses the webService keyword as static.
* You cannot deprecate webService methods or variables in managed package code.
* Because there are no SOAP analogs for certain Apex elements, methods defined with the webService keyword cannot take the following elements as parameters.While these elements can be used within the method, they also cannot be marked as return values.
- Maps
- Sets
- Pattern objects
- Matcher objects
- Exception objects
* You must use the webService keyword with any member variables that you want to expose as part of a Web service. You should not mark these member variables as static.
* Salesforce denies access to Web service and executeanonymous requests from an AppExchange package that has Restricted access.
* Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String value that is too long for the field.
 *The following example shows a class with Web service member variables as well as a Web service method:
global class SpecialAccounts {
global class AccountInfo {
WebService String AcctName;
WebService Integer AcctNumber;
}
WebService static Account createAccount(AccountInfo info) {
Account acct = new Account();
acct.Name = info.AcctName;
acct.AccountNumber = String.valueOf(info.AcctNumber);
insert acct;
return acct;
}
WebService static Id [] createAccounts(Account parent,
Account child, Account grandChild) {
insert parent;
child.parentId = parent.Id;
insert child;
grandChild.parentId = child.Id;
insert grandChild;
Id [] results = new Id[3];
results[0] = parent.Id;
results[1] = child.Id;
results[2] = grandChild.Id;
return results;
}
TestMethod static void testAccountCreate() {
AccountInfo info = new AccountInfo();
info.AcctName = 'Manoj Cheenath';
info.AcctNumber = 12345;
Account acct = SpecialAccounts.createAccount(info);
System.assert(acct != null);
}
}
Overloading Web Service Methods
* SOAP and WSDL do not provide good support for overloading methods.
* Consequently, Apex does not allow two methods marked with the webService keyword to have the same name.
*Web service methods that have the same name in the same class generate a compile-time error.
                   Previous                                                                                              Next

To retrieve the records of the custom/standard object of the current user

I want to retrieve the records of the custom/standard object of the current user, How?
Solution:
Id aid = Userinfo.getUserId();
account ac = [Select Id, Name from Account Where CreatedById = : aid limit 1];
System.debug(' ---- ' + ac );
Id aid = Userinfo.getUserId();
List<Account> ac = [Select Id, Name From Account Where CreatedById = : aid Limit 10000]; 

VisulaForceError-System.QueryException: List has no rows for assignment to SObject

This error usually occurs when you are not passing an id in the URL

Question:
System.QueryException: List has no rows for assignment to SObject Class.practiseOneController.getAccount: line 5, column 1
VF Page:
<apex:page controller="practiseOneController" tabStyle="Account">
<apex:pageBlock title="Hello {!$User.FirstName}!!!">
You belong to {!account.name} Account.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:dataTable value="{!account.contacts}" var="contacts" cellpadding="4" border="1">
<apex:column value="{!contacts.FirstName}" headerValue="FirstName"/>
<apex:column value="{!contacts.LastName}" headerValue="LastName"/>
</apex:dataTable>
</apex:pageBlock> 
</apex:page>
Apex Class:
public class practiseOneController
 {
    public Account getAccount()
    {
        return [select id,Name,(select id,firstname,lastname from Contacts limit 5) from Account where id=
                 :System.currentPageReference().getParameters().get

('id')]; } } 
 Solution:
Use following code for Apex Class

public class practiseOneController
 {
    public Account getAccount()
    {
        Account[] acc = [select id,Name,(select id,firstname,lastname from Contacts limit 5) from Account where id=:System.currentPageReference().getParameters().

get('id')]; if(acc.size() > 0) { return acc[0]; } else { return null } } } 
Refer:
System.QueryException

Wednesday, 15 August 2012

Validation Rules

Validation Rules:
" To filter the data i.e to avoid the inappropriate data to reflect into the model" we use validation rules

Validation Rules step by step Screen Shots:
* Enter the Rule Name.
* Set the formula for the validation.
* If the formula is True then record won't be saved into the Model.
* If the formula is not True then only record will be saved into the Model.
* For this validation rule formula field, we have options like  VLOOKUP,  ISCHANGED, REGEX(Text, RegEx_Text) will be available which are not available for the formula data type and workflow rule formula fields.
* Formula field works on single record.
* Enter Error Message here which we want to display on page.
* Choose Top of Page to display the error message at top of page.
* Choose Field to display error message below a specific field on the page.


I have 1000 records, how can I execute 200 records each time in Trigger?

By default triggers will run in a batch of 200 records. For 200 record one trigger invocation, even in case of Bulk API.

Consider a scenario where you're inserting 1100 records then it will be run in 6 batches

200 * 5  + 100 * 1 = 6 (Invocations)

-------------------------------------------

* Use SOQL for loops to operate on records in batches of 200.
* SOQL for loop, which iterates over the returned results in batches of 200 records.
* This reduces the size of the ml list variable which now holds 200 items instead of all items in the query results, and gets recreated for every batch.

for (List<Merchandise__c> ml : [SELECT Id,Name FROM Merchandise__c])
{
// Do something.
}

* You can also use batch apex class to process large number of records.

Organization Wide Defaults, Role hierarchy

Organization Wide Defaults, Role hierarchy
* We can specify either private or public for custom objects.
* For Public: public read/write, public read only available for custom objects.
* Standard Objects have many other options
* We can enable or disable role hierarchy for custom objects.

Sharing Rules

Sharing Rules Screenshots (Step by Step)
* Go to 'Sharing Settings', which contain both OWD and Sharing Rules.

* Sharing Rules Screen Page
* If we choose 'Based on the record owner' below options will display.
* If we choose 'Based on criteria' below options will display.

 * From above marked in green specifies that we can provide either Read Only or Read/Write permission to the users.

Record level security

How to provide security for the records?
we actually have four ways of setting record-level access rules:
1. Organization-wide defaults
    * OWD allow us to specify the baseline level of access that a user has in our organization.
    * OWD provides default accessibility for the owners and other users of the organization.
    * Either we can set public or private.
    * For public again we can set like below:
       - public READ/WRITE
       - public READ ONLY
       - public READ/WRITE/TRANSFER (only for standard objects)
       -many more options for the standard objects
2. Role hierarchies
    * It allow us to make sure that a manager will always have access to the same records as his or her subordinates.
3. Sharing rules
     * It allow us to make automatic exceptions to OWD for particular groups of users.
4. Manual sharing
     *IT allows record owners to give read and edit permissions to folks who might not have access to the record any other way.

divisions in sfdc

DIVISION
* A logical segment of your organization's data.
* if your company is organized into different business units, you could create a division for each business unit, such as “North America,” “Healthcare,” or “Consulting.”  

REFER:
login.salesforce.com/help/doc/en/getting_started_with_divisions.htm
http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_division.htm

Permission Sets


Q. There are 8 Fields and I want to assign 4 fields to be visible by one user and another 4 fields to another user, How can we do that?
Q. How can I hide field apart from field level security and page layouts?
(For the above both questions)

A. Using Permission Sets, We can increase the permissions to the user without creating new profile for a single user. Profiles also contain all the options which are in Permission Sets.

Important Points:
* To override the profile permissions, we use permission sets.

Creating Permission Sets - Screen Shots (Step by Step)
* Find Permission Sets option here.

 * Click 'New' here to create new permission set
* Fill these options and select user license type
*Click on the created Permission Set
* Click on 'Assigned Users' to view or assign more users.
* After clicking on the 'Object Settings' below screen will come.

* Click on any object then below screen will display
Assigning Permission Sets - Screen Shots (Step by Step)
* Click on 'Users' at 'Manage Users'.

*Go to 'Permission Set Assignments related list' below user detail
* Click on 'Edit Assignments' and Enable Permission Sets for the user.


Refer:
http://login.salesforce.com/help/doc/en/perm_sets_overview.htm
http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_permissionset.htm

Workflows

Workflow:
"Automating set of manual steps"

* Whenever an event occur based on the criteria an action will takes place.
* Three phases in workflow:
   1. Evaluation Criteria
       In this we have three events
       i.   Create a record or Edit a record but previously did not meet the criteria.      
Rule                     
Create
Edit
met
Yes (Action takes place)
No
met
No
Yes(Action takes place)
met
Yes (Action takes place)
Yes
not met
No Action
No Action
       ii.  Only when a record is created.
Rule                     
Create
Edit
met
Yes (Action takes place)
No
met
No
Yes
met
Yes (Action takes place)
Yes
not met
No Action
No Action
       iii. Every time when a record is created or edited
Rule                     
Create
Edit
met
Yes (Action takes place)
No
met
No
Yes(Action takes place)
met
Yes (Action takes place)
Yes(Action takes place)
not met
No Action
No Action

   2. Rule Criteria
       We have two types of conditions
       i.  Criteria met
       ii. Formula based
   3. Workflow Action
       In this we have two types of workflow actions
       a. Immediate Workflow Action
       b. Time dependent workflow action
       Note: *for Every time when a record is created or edited this is disabled.
                 *Before 999 days only we can schedule
       In this we can perform four actions
       i.   New Email Alert
       ii.  New Task
       iii. New Field Update
       iv. New Outbound Message

Sunday, 12 August 2012

To disable other checkboxes in a section if one is selected.

To disable other checkboxes in a section if one is selected.
<apex:page>
<apex:form>
<script>
function confirmDisbaled(ifchecked, id1 ,id2,id3) {


document.getElementById(id1).disabled = ifchecked;
document.getElementById(id2).disabled = ifchecked;
document.getElementById(id3).disabled = ifchecked;


}
</script>
<apex:pageBlock>
<apex:actionRegion >
<apex:outputPanel id="panel1">
<apex:pageBlockSection title="PST" id="PST">
<apex:inputCheckbox label="Global" id="gbl" onchange="return confirmDisbaled(this.checked, '{!$Component.lcl}','{!$Component.cntry}');"/>

<apex:inputCheckbox label="Local" id="lcl" onchange="return confirmDisbaled(this.checked, '{!$Component.gbl}','{!$Component.cntry}');"/>

<apex:inputCheckbox label="Country" id="cntry" onchange="return confirmDisbaled(this.checked, '{!$Component.lcl}','{!$Component.gbl}');"/>

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

Define & Insert Queues in Apex Triggers & Test Classes?

It's a two step process:

            Group g1 = new Group(Name='group name', type='Queue');
            insert g1;
            QueuesObject q1 = new QueueSObject(QueueID = g1.id, SobjectType = 'Lead');
            insert q1;

Strange Concepts

Please see the below Comments

(under this particular post only)

Saturday, 11 August 2012

Managing the Heap in Salesforce.com

How to show visual force error?

<apex:page standardController="Account">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!Save}"/>
<apex:commandButton value="Cancel" action="{!Cancel}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Student Info">
<apex:inputField value="{!Account.Name}"/>
<apex:inputField value="{!Account.AccountNumber}" required="True"/>
<apex:inputField value="{!Account.AnnualRevenue}" required="True"/>
<apex:inputField value="{!Account.Description}" required="True"/>
<apex:inputField value="{!Account.Site}" required="True"/>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>

copy field values of one object to another object

Normal Logic:
trigger insertMember2 on Member__c (after insert) {
 Set<Id> Ids= new Set<Id>();
    for (Member__c member : Trigger.new)
    {
        Ids.add(member.Id);        
    }
 List<Member__c> memberList = new List<Member__c>([Select Id,FirstName__c,LastName__c  From Member__c e where Id in :Ids]);

 for(Member__c temp : memberList )
 {
  Member2__c member2 = new Member2();
  member2.FirstName__c = temp.FirstName__c;
  member2.LastName__c = temp.LastName__c;
  insert member2;

 }
 }
Good Logic:
* Trigger should be like this and will work for bulk data as well as insert statement is used out side the for loop

 List<Member2__c> listMember2ObjToInsert = new List<Member2__c>();
 for (Member__c memberObj : Trigger.new)
    {
        Member2__c member2Obj = new Member2();
 member2Obj.FirstName__c = memberObj.FirstName__c;
 member2Obj.LastName__c = memberObj.LastName__c;
        // If you have any refernce of member in member2 you should fill that as well
 listMember2ObjToInsert.add(member2Obj);
    }
insert listMember2ObjToInsert;
}

Javascript with Visualforce pages

Displaying pop-up summaries on hover in visualforce

VF:
<apex:page controller="PopupTest19">  
    <apex:form >  
        <apex:repeat value="{!accounts}" var="acc">                              
                
      <a href="{!acc.Id}" id="{!acc.Id}" onblur="LookupHoverDetail.getHover('{!acc.Id}').hide();" onfocus="LookupHoverDetail.getHover('{!acc.Id}', '/{!acc.Id}/m?retURL=%2F{!acc.Id}&isAjaxRequest=1').show();" onmouseout="LookupHoverDetail.getHover('{!acc.Id}').hide();" onmouseover="LookupHoverDetail.getHover('{!acc.Id}', '/{!acc.Id}/m?retURL=%2F{!acc.Id}&isAjaxRequest=1').show();">{!acc.Name}</a><br/> 
        </apex:repeat>  
    </apex:form>  
    </apex:page>
APEX:
public with sharing class PopupTest19 { 
List<Schema.account> accounttList = new List<Schema.account>();     
    public List<Schema.account> getAccounts()      {  
        
        accounttList = [Select Id, Name from Account LIMIT 10];  
        return accounttList ;  
    }  
  
}
//List<Schema.account> if apex class has same name as standard object to avoid that confusion we have to use Schema before standard Object name otherwise an error will occur 'Illegal assignment from LIST<Account> to LIST<Account>'
Refer:
Displaying pop-up summaries on hover in visualforce

Illegal assignment from LIST to LIST

* If there is any apex class with the same name of the standard or global sObjects while creating List, map,set the above error will reflect.
*We can solve this problem in two ways:
1. We have to rename our Apex Class to some other name.
2. Use 'Schema' before sObject while creating List, Set, Map (Don't use 'schema' before sObject in SOQL Query)
- List<Schema.Account> aclist = new List<Schema.Account>();
- return type should be also like List<Schema.Account>
-Click here to see the example here!

Refer:
 Illegal assignment from LIST<Account> to LIST<Account>

Friday, 10 August 2012

Generate PDF with apex trigger

Question:
I am currently trying to have a PDF created based on a field update.
The issue is that it seems that getContent() and getContentAsPDF() don't work when called within a trigger.

Solution:
Tried separating this logic into a class with @future, and then calling it to do your logic asynchronously.
global class pdfCreator
{
    @future (callout=true)
    public static void createPDF(ID Id)
     {
        PageReference pdf = Page.AccountsPDF;
        pdf.getParameters().put('id', String.valueOf(Id));

        Attachment attach = new Attachment();
        attach.ParentId = Id;
        attach.name = 'name.pdf';
        attach.body = pdf.getContentAsPDF();
        insert attach;
     }
}
trigger CreatePDF on Contract_Custom__c (after update) {

    for(Contract_Custom__c a : Trigger.New)
    {
    	Id id = a.id;
    	pdfCreator.createPDF(Id);
    }
}

How to disable/enable all validation rules for data loading

How to publish sites using siteforce?

Trigger to update a field in parent record once a task is created

Question:
I need to create a trigger that does the following:

Whenever a new task with a subject of "Email: CO1 Feedback" is created on a contact record, a field on that contact record called "CO1_followup_email_date__c" should be updated to match the date that the task was created.

The code that I used is below. I am not getting any error messages, but when I create the task with the proper subject line, the CO1 Follow-up email date is not updated. Any ideas?? Thanks for your help!

trigger Contactbirthdayupdate on Task (after insert) 
{
List<Contact> ContactsToUpdate = new List<Contact>();
for (Task t: Trigger.new)
{
if (t.subject=='Email: CO1 Feedback')
{
Contact c = new Contact(Id=t.WhatId);

c.CO1_Followup_email_date__c = t.ActivityDate;
ContactsToUpdate.add(c);
}
}
   try {
        update ContactsToUpdate; 
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
}


Solution:

Its whoId not WhatId... update to..

Contact c = new Contact(Id=t.WhoId);

Callout Integration and Apex

Question:
I have to call to an external webservice everytime a new account is created. My question is, what is the best way to do so?

I thougt about creating an after create trigger that will invoke the method in the class that was generated from the WSDL import. Would that make sense?

If so, how can I import a class into a trigger to use its methods?
Is it the same with Http request or can i make the http request directly from the trigger?

Solution:
Currently in salesforce we can not make callout from trigger directly , You need to write a future class that will invoke the callout using wsdl generated classes. So in fact this call will be asynchronous call rather than realtime callout.

For example-  you have a wsdl genarated class named "WSDlGeneratedClass" , And you will have to write a future method like -
public class future class
{
 @future(callout=true)
 public static void calloutMethod()
 {
  // write code to invoke "WSDlGeneratedClass" class methods to make callout
 }
}

Now this method you will need to call from trigger.

Yes its also with HTTP callout  (cannot make any kind of callout from trigger directly).

How to pull values of records modified 7 days ago?

Question:
I want to create a list of sObjects that were modified 7 days ago.

I am using code similar to this, but when I get to the SOQL query it appears that something is not quite working.
Date myDate = date.today()-7;
List<Recruitment_Cycle__c> RCs = [Select ID, Name, LastModifiedDate from Recruitment_Cycle__c where LastModifiedDate =: myDate ]; 
 In this case I am getting 0 rows, however there are a number of records that I would expect to meet the criteria when looking at the data. I suspect something is wrong with my comparison etc...

When I check the debug for myDate it is assigning what looks like the proper date.

Solution: 
One thing is that you should use date.today().addDays(-7)

And also you are using exact match "=" sign. And LastModifiedDate field also contains time, whereas you are just using today function which will return you Date part. So i do not think there will be a match. Please verify if you need Date or Date and Time. I would think you want that day. So you may have to use something like this:

Date myDateStart = date.today().addDays(-7);
Date myDateEnd = date.today().addDays(-6);
List<Recruitment_Cycle__c>
 RCs = [Select ID, Name, LastModifiedDate from Recruitment_Cycle__c 
where LastModifiedDate >=: myDateStart AND LastModifiedDate <=: 
myDateEnd];

how to remove a value from list without using its index

Question:

"list<string>options=new list<string>{'a','b','c','d','e','f','g','h'};"

from this list i want to remove "e" (lets assume that 'i have dont know its index')

Solution:

* Just add all list values to a SET.
* We can directly remove values from set using remove() method.
* After that add this set to a particular list.

Field sets

*Field set is nothing but set of fields like(First Name, Last Name, Username).
*If we use field sets on VF page without modifying VF code Admin can rearrange, delete, add fields to the field set.
*We can use field set on VF page using $ObjectType global variable.

<apex:page standardController="Contact">

<apex:repeat value="{!$ObjectType.Contact.Fieldsets.propernames}" var="f">

<apex:outputText value="{!Contact[f]}"/>

</apex:repeat>

</apex:page>

Thursday, 9 August 2012

Dynamic Visualforce Naming

Question:
I've been doing some work creating content in Visualforce that is rendered/opened in different formats (PDF, csv, excel etc). The few ways I have found to force rendering or download of the Visualforce page onload is to renderAs="PDF" or setting contenttype="text/csv" etc. The issue is during the load of the page, the page itself is saved using the naming convention of the Visualforce page, meaning you cannot specify the necessary extension. 

I was wondering if anyone had a workaround or any ideas to force the save of the page to a dynamic name and specify a file extension (for instance force a Visualforce page named Report with contenttype="application/csv" save as {dynamicname}.csv). 

My temporary work-around is having the file emailed as an attachment, as you can specify name of attachment and file extension dynamically in Visualforce templates. I would prefer the option to directly download rather then use this work-around. Anyone have any ideas?

Solution:
contentType="text/csv#{!dynamicname).csv"

Using Regular Expressions in SFDC

Q. How to make the input field to accept only email format of data?
A. 

String InputString = 'email@email.com';
String emailRegex = '([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}
\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})';
Pattern MyPattern = Pattern.compile(emailRegex);

// Then instantiate a new Matcher object "MyMatcher"
Matcher MyMatcher = MyPattern.matcher(InputString);

if (!MyMatcher.matches()) {
// invalid, do something
}
Refer:
Using Regular Expressions in SFDC

Labels