Friday 22 December 2017

Lightning Basics Part 3: How Enable Custom Domain

Arpit Sharma
In Previous Part, we see Why Need of custom domain. Now We will see how we can configure a custom domain in salesforce for lightning. So Let's Begin with one by one step.

Step 1: Click on Setup.



Step 2: Domain Managment - > My Domain


Step 3: Enter Unique Domain name here which show your company brand, It can be 40 characters, Include numbers and hyphens, but can't be start or end with a hyphen


Step 4: Click on Check Availablity button to check whether or not your entered domain not used by others.

Step 5: Then Click on Register Domain


Step 6: In Few Minutes you will receive domain ready for testing email on your email id.

Step 7: Now Again go to Domain Managment - > My Domain Then clicks on the login button to test your domain Internally.


Step 8: Then Click on deploy to user button to redirect all URL to your new domain.


So We have successfully set up our custom domain. Let me know If you face any issue.

Thursday 21 December 2017

Lightning Basics Part 2: Enable Custom Domain

Arpit Sharma
Why My Domain?



Salesforce comes with lightning but when I try to run my lightning app then salesforce ask me "Lightning component require custom domain Please contact the System administrator for more information", So the first question that comes to my mind, why I need to an enabled custom domain?

So I try to investigate and come with some points here.

There are a number of reasons that we need a custom domain for lightning.

1. A domain is unique, It shows your brand.

2. It is more secure means you can block all the URL that not contains this domain.

3. If you installed the third-party lightning component and you are also developing a lightning component in your org both have their namespace and own custom domain, So It helps salesforce to differentiate your component code and third-party code.

These are the points that I have found out and if found some more then I will update this post.



Tuesday 19 December 2017

Lightning Basics Part 1: Introduction

Arpit Sharma
Lightning Basics Part 1

Introduction




As per developer perspective, Initially, When our requirement not completed by using existing salesforce point and click automation than we fulfill our requirement by using visual force pages and Apex programming language. Now Salesforce has something new for the developers.

Facebook, Twitter, Google all have their javascript framework. Now Salesforce has its own framework with a named lightning framework.

The lightning framework is basically a javascript component-based framework. It makes easy to develop a responsive app that works well both in lightning as well as salesforce 1.

Component-Based

Lightning framework use component to develop requirement and components are off shelf component, means once a component is developed we can attach that component to any other lightning component, lightning app, on a lightning home page and on other places as well. So code reusability of code can be increased with the help of component. we can use component by using a single line of code in our code or by using drag and drop on salesforce pages. 

Event-Driven 

Lighting framework is event-driven, means if we want to perform an action on user activity then we need to register and define that events. Some events are inbuilt and some events are built by a developer.






Saturday 18 November 2017

Vue JS In Salesforce

Arpit Sharma

Now MIT Developer come up with new Javascript framework under MIT License i.e Vue.js. It is cross platform framework and written in javascript. Vue.js is a progressive framwork means Reliable, Fast, Engaging. It can be easily integrated with existing projects. It can also used to create single page application with Support Libraries and Modern Tooling.

Prerequisite

To Learn Vue.Js Developer need to intermediate knowledge of Javascript, CSS, HTML.

How to Use in Vue.js in Salesforce - 

1. Download Vue.js from here.
2. Upload into static Resource.
3. Create new Page Named VueJsExample add following code 
  • First we give id to element in HTML.
  • Then in JS set that element to be app using Id with help of Vue.js capabality.
  • Then set properties of app.

<apex:page>
   <apex:includeScript value="{!$Resource.vuejs}"/>
   <div id="app">
      <p>{{ message }}</p>
   </div>
   <script>
      var app = new Vue({
          el: '#app',
          data: {
          message: 'Salesforce With View.js'
          }
      })
   </script>
</apex:page>


Now we have created first vue app In this example if change value of app.message dynamically then message value automatically change in html same as angular.





Saturday 30 September 2017

VisualForce - loadOnReady attribute on apex:includeScript

Arpit Sharma


Salesforce provide us apex:includeScript tag to include script on visual force page.


In this post we will discuss about loadOnReady attribute of apex:includeScript tag.

Role of loadOnReady attribute in apex:includeScript - 

1. loadOnReady attribute have two value i.e false and true.

2. Default value of this attribute is false.

3. If value of this attribute is false then script load immediately.

4. If value of this attribute is true then script will load when page is ready.


Let us take an example to understand loadOnReady attribute

1. When loadOnReady attribute is false then we get angular at both place outside of onload and inside the on onload.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<apex:page >
  <!-- External Scripts -->
      <apex:includeScript loadOnReady="false" value="{!$Resource.angular_js_script}" />
  <!-- External Scripts -->
  <script>
      alert(typeof angular);//we will get angular here.
      window.onload = function(){
          alert(typeof angular);// we will get angular here.
      }
  </script>
  
</apex:page>

2. When loadOnReady attribute is true then we get angular only in inside the on load.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<apex:page >
  <!-- External Scripts -->
      <apex:includeScript loadOnReady="false" value="{!$Resource.angular_js_script}" />
  <!-- External Scripts -->
  <script>
      alert(typeof angular);//we will get undefined here means angular is not loaded here.
      window.onload = function(){
          alert(typeof angular);// we will get angular here.
      }
  </script>
  
</apex:page>

ReferencesSalesforce docs

Saturday 23 September 2017

A useful String method : normalizeSpace

Arpit Sharma


Salesforce release a very good method of string which is required in string manipulation during development i.e normalizeSpace().

Functionality of normalizeSpace Method - This method normalizes the following white space characters: space, tab, new line, carriage return, and form feed.

Remove leading white space characters, trailing white space characters, and repeating white space characters from string.

Example of normalizeSpace Method -

1
2
String unnormalizeString = ' Salesforce       \t  \n   \r  \f Normalize Example ';
System.assertEquals('Salesforce Normalize Example',unnormalizeString.normalizeSpace());//return true

Explanation of normalizeSpace Example 

1. In above example unnormalizeString string variable contains space on starting, space on end, multiple spaces in between and spacial character (tab (\t), new line (\n), carriage return (\r), and form feed (\f)).

2. In second line we have applied normalizeSpace() method on unnormalizeString string to remove all spaces and special character, so over statment will successfully passed without failing assert statement.It means string is normalized completely

So this is all about string normalization method.

Let me know if you have any suggestion, doubt, question.




Tuesday 19 September 2017

Can We Set The Owner Of Record To User Who Does Not Have Object Permission?

Arpit Sharma


In this tutorial we will see, can we set the owner of a record to a user who does not have object permission?

Salesforce provide us a feature to change owner of record but one question come in my mind, can we change owner if user does not have object permission?

So I try below example

1. Created two user u1 and u2.
2. Created one object TestOwner.
3. Given all permission to profile of u1 for TestOwner object.
4. Removed all permission from profile of u2 for TestOwner object.
5. Login to user u1 and created record of TestOwner.
6. Now try to set owner of record to u2.
7. Salesforce stop me change the owner of record to u2 and display message i.e new owner of the record must have at least “Read” permission on TestOwner.

So to change owner of record, new user must have at least read permission on profile for object of that record.

Sunday 10 September 2017

How To Stop Deletion Of Parent Record If Child Record Exist In Salesforce Using Triggers.

Arpit Sharma
In this tutorial we will see how we can stop deletion of parent record basis on condition. As we have already learn Simple Example i.e Stop deletion of parent record using configuration.

Now let's come on this, Suppose we have a scenario in which we need to stop deletion of parent record when child record exist basis on condition either on parent or child, we can handle this scenario by using trigger.


Now Let's take on example 

Suppose we have Account Object and Contact object and if we want to stop deletion of parent account record if any child contact record name starts with "Test".

We can handle this scenario using trigger having before delete event

Below is sample code snippet of above scenario.

trigger AccountTrigger on Account (before delete) {
    //reterieve all contacts releated account that is currently deleting
    Map<Id,Account> accountWithContacts = new Map<Id,Account>([SELECT 
            ID,(SELECT ID,Name FROM Contacts) 
            FROM Account 
            WHERE ID IN:Trigger.old]);
    //iterate over trigger.old context variable record        
    for(Account accRecord : Trigger.old){
       //reterive contact records associate with account
       for(Contact accContact :accountWithContacts.get(accRecord.ID).contacts){
           //if contact start with Test then stop deletion of account record
           if(accContact.Name.StartsWith('Test')){
               accRecord.addError('You cannot delete this account because contact associate with this account have name test.');
           }
       }
    }  
}

Guys share this tutorial if you like it.

Friday 8 September 2017

System.FinalException: SObject row does not allow errors

Arpit Sharma
During Development various type of exception occurred, One of the exception that I have faced is System.FinalException: SObject row does not allow errors. In this tutorial we will discuss reason of this exception.

Points that need to be considered

Where Occurs - This exception occurs during execution of trigger.

Reason of Occurrence - Salesforce provide addError method to mark a record with custom message and prevent any DML operation from occurring.

But this method is applicable only on records that is part of trigger context variable means Trigger.old and Trigger.new. It means We can use this method only in triggers and only on Trigger.old and Trigger.new context variable.

So Let's take an example if we have trigger on account object and we want to stop processing of particular record on particular condition then we can use addError method.

Here is example 

Correct Example
trigger AccountTrigger on Account(before update) {
    for(Account acc : Trigger.new){
        if(acc.Name == 'Working Code'){
            acc.addError('This add error working fine.');
        }
    }
}

Incorrect Example
trigger AccountTrigger on Account(before update) {
    List<Account> accList = [SELECT Id,Name 
                             FROM Account 
                             WHERE Id IN :Trigger.old];
    for(Account acc : accList){
         if(acc.Name == 'Non Working Code'){
             acc.addError('This add error statment will not execute trigger will throw exception i.e.System.FinalException: SObject row does not allow errors');
         }  
    }
}

In First Example we are using addError method on record of trigger context variable but in second case we first reterive record from database then add error on database record which is not allowed in salesforce and salesforce throws error System.FinalException:SObject row does not allow errors.


Tuesday 5 September 2017

How To Stop Deletion Of Parent Record If Child Record Is Exist in salesforce Using Configuration

Arpit Sharma
In Salesforce if we want to create one to many relationship(one parent record have many child) then one way is to we can use lookup relationship feature of salesforce.

In case of lookup relationship If we want to stop deletion of parent record then we don't need to worry about it, We can configure it from look relationship configuration page.

We can configure it during lookup field creation and edit.

Salesforce provide us two option during lookup field configuration, we need to select second option to stop deletion of parent.

1. During parent record deletion set child lookup field value to blank.
2. During parent deletion stop deletion of parent.

But we can't select first option if we set lookup field to required on child object
because in that case we can't set field to blank because field is required on child record. You can see option in screenshot.



   
If we try to delete parent record then salesforce gives following error. 

Your attempt to delete Parent Record could not be completed because it is associated with the following Child Records. If the following table is empty, it is because you do not have access to the records restricting the delete.

So for deletion of parent record we need to delete all child record first.




Wednesday 16 August 2017

Identify Current User Access To Record Using UserRecordAccess Object

Arpit Sharma
Salesforce provide UserRecordAccess object to identify access of user on set of records. We can query on this object based on user ID.

Key Points of UserRecordAccess
    1. This object is read only.
    2. It is available in API Version 24.0 and later.

Fields of UserRecordAccess 
    • RecordId - Id of record in which we need to check access, It is available in SELECT clause and WHERE clause. 
    • UserId - It is available in WHERE clause.
    • User Record Access Id - It is available in WHERE clause.
    • Maximum Access Level - It is used to identify maximum access of record having user(Picklist type). Value available in picklist.
        • None
        • Read
        • Edit
        • Delete
        • Transfer
        • All
    • HasTransferAccess(Boolean Type)
    • HasEditAccess(Boolean Type)
    • HasDeleteAccess(Boolean Type)
    • HasAllAccess(Boolean Type)

Sample Query
SELECT RecordId, HasEditAccess,HasReadAccess, HasTransferAccess, MaxAccessLevel,HasDeleteAccess
     ,HasAllAccess FROM UserRecordAccess
     WHERE UserId = UserInfo.getUserId()
     AND RecordId = :recordId     

References
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_userrecordaccess.htm
https://help.salesforce.com/articleView?id=000181207&type=1



  

Friday 11 August 2017

Reports In Salesforce

Arpit Sharma
Why Report


Report is usually used to represent data in presentable form, Creating a report manually required lot of effort which included many question in mind i.e which type of data you required, what is the best way to represent data in report.

If you need data based on some criteria then there may be chances some unwanted data visible in report or some important data is not visible because of some human error. Report generated become more complicated when you work on large data. This is point where you need some automatic process to generate report for you business.

We will discuss here, about reports in Salesforce

Reports in Salesforce

Various tools are available in market to generate reports but if you are working in Salesforce then either you need to write custom code for represent that data or Salesforce itself provide most advance way to generate report by using just some point and click that does not require knowledge of code and reduce efforts and time

What Salesforce provide 
  1. We can set schedule time of report generation.
  2. Salesforce display data to user in report according to security model means user can't see data if user does not have permission of that data.
  3. In salesforce we can generate four type of reports
    • Tabular Reports
    • Summary Reports
    • Matrix Reports
    • Joined Reports 
Guys all above is basic idea about what is report, how it is useful for us and what Salesforce provide to us.

We will discuss above report types in details in upcoming tutorials

Feel free to comment if you have any question and suggestions in this tutorial.






Friday 14 April 2017

apex:slds - Include lightning design system by using apex tag

Arpit Sharma


To use lightning design system we don't need to upload library  to static resource and reference them in visual force page. We can include them by using apex tag i.e <apex:slds/>. here is example of include of slds in visual force page.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<apex:page standardStylesheets="false" sidebar="false" showHeader="false">
  <apex:slds/>
  <apex:form>
      <!-- Without lightning designing CSS-->    
      <div >
          <label for="inputLabel">Input Label</label>
          <div>
             <input type="text" id="inputLabel"  placeholder="Without lightning designing CSS"/>  
          </div>
      </div>
      <!-- With lightning designing CSS-->
      <div class="slds-form-element">
          <label class="slds-form-element__label" for="inputLabel">Input Label</label>
          <div class="slds-form-element__control">
             <input type="text" id="inputLabel" class="slds-input" placeholder="With lightning designing CSS"/>  
          </div>
      </div>    
  </apex:form>
</apex:page>



Thursday 13 April 2017

How to get object name from ID of record

Arpit Sharma




In Salesforce some time we have requirement to retrieve object name from record ID. So We can done this by two approach.

First approach
  • Get SObject type from record ID by using getSObjectType() method.
  • Convert Sobject type into string value.


1
2
3
4
Contact contactRecord = new Contact(FirstName = 'Test', LastName = 'Contact');
insert contactRecord;
// contactRecord.Id.getSObjectType() return Sobject Type of record then we convert them into String
String objectName = String.valueOf(contactRecord.Id.getSObjectType());

Second approach

  • Get Sobject type from record id by using getSObjectType() method.
  • Describe Sobject type by using getDescribe() method.
  • Then get name of object from object describe by using getName() method .


1
2
3
4
5
6
7
8
Contact contactRecord = new Contact(FirstName = 'Test', LastName = 'Contact');
insert contactRecord;
/*
   - first we get Sobject type by using statement contactRecord.Id.getSObjectType()
   - we describe Sobject type by using getDescribe() method.
   - then from object describe by using getName() we can get name of that object 
*/
String objectName = contactRecord.Id.getSObjectType().getDescribe().getName();

Friday 24 March 2017

How upload large file in salesforce

Arpit Sharma


In Salesforce when we upload file using remote action then we are not able upload file more then 4.3 MB because above 4,3 MB we getting input too long error.so I found one solution in which we are able to upload file upto 25 MB In this approach we are using sforce api on visual force page to upload file on salesforce.below is code of uploading file upto 25 MB.

  1. <apex:page>
  2. <script type="text/javascript">
  3. var __sfdcSessionId = '{!GETSESSIONID()}';
  4. </script>
  5. <script src="/soap/ajax/34.0/connection.js" type="text/javascript"></script>
  6. <script>
  7. function uploadAttachmentFromVisualForcePage() {
  8. var reader = new FileReader();
  9. var attachFile = document.getElementById('idOfUploadInputFileElement').files[0];
  10. if (attachFile == undefined) {
  11. alert('Please select a file');
  12. return;
  13. }
  14. if (attachFile.size > 26214400) { //Where 26214400 is byte equivalent of 25MB
  15. alert('Attachment size not supported');
  16. }
  17. reader.onload = function(e) {
  18. var attachment = new sforce.SObject('Attachment');
  19. attachment.Name = attachFile.name;
  20. attachment.IsPrivate = false;
  21. attachment.ContentType = attachFile.type;
  22. attachment.Body = (new sforce.Base64Binary(e.target.result)).toString();;
  23. attachment.Description = attachFile.name;
  24. attachment.ParentId = 'recordID'; //Where recordID is the ID of record to which you want to add your attachment
  25. var result = sforce.connection.create([attachment]);
  26. if (result[0].getBoolean("success")) {
  27. alert('file uploaded successfully');
  28. } else {
  29. alert('something went wrong.');
  30. }
  31. };
  32. reader.readAsBinaryString(attachFile);
  33. }
  34. </script>
  35. <input type="file" id="idOfUploadInputFileElement" /><input type="button" value="Upload" onClick="uploadAttachmentFromVisualForcePage();" />
  36. </apex:page>

How to get list view id in apex class

Arpit Sharma
salesforce
Get list view id  using apex class in salesforce first we need to describe organization sobject by using below function

Step 1 - 

Schema.getGlobalDescribe() - This map contains organization object. map populate during run time based on permission. Key of map is sobject name and value is Sobject tokens.token is serializeable reference to sobject. 

Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe();

Step 2-

Suppose if we want to describe Standard object account then we need to retrieve account token from map,If your org have namespace then you need to add namespace to custom object name because map contains object name with namespace as key.

Schema.SObjectType accInfo =  Schema.getGlobalDescribe().get( 'Account' );

Step 3-

Now we will describe Account object using getDescribe(), Return result is not serializeble, result contains all describe property of object or fields 

DescribeSObjectResult accDesc = accInfo.getDescribe();

Step 4-

Now we need to reterive object List view id  from descrbie sobject result.

String listViewId = accDesc.getKeyPrefix();