Friday, 6 July 2018

                            PermissionSetAssignment:



  • Use the PermissionSetAssignment object to query permission set assignments to find out which permission sets are assigned to which users.
  • Each user may be assigned to many permission sets and each permission set may be assigned to many users.
  • Each PermissionSetAssignment ID represents the association of a single user and single permission set.

For example, to search for all of the permission sets assigned to a particular user:

SELECT Id, PermissionSetId
FROM PermissionSetAssignment
WHERE AssigneeId = '005600000017cKt'

To search for all users assigned to a particular permission set:

SELECT Id, AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSetId = '0PS30000000000e'

Note:

You can also create a new permission set assignment, or use delete to remove a permission set that's assigned to a user. To update an assignment, delete an existing assignment and insert a new one.

Possible Errors:



Solution:

When assigning a permission set, if the PermissionSet ​ has a UserLicenseId, its UserLicenseId and the Profile ​UserLicenseId must match.


If Permission set is already present for user.Following Error will occur.




Wednesday, 23 May 2018

   DML Statement in 'after trigger' and not in 'before trigger'?


According to document, first Before trigger fire and then after trigger fire.In between of these events all the records saved to database but doesn't committed yet
  • Before insert event
  • Data committed to database
  • After insert event

Means when you use before insert operation records are not committed to database so If we change the trigger context record's value then we don't need perform DML (This is Id is not generated because it is not committed to database)

  • Once it is committed to database means the record Id is generated and your trigger records in read only mode you can't update the values now(because it is committed to database).That's why we need to perform extra DML for updating records.


Note: If in after event if any error occurs then complete DML operation rollback.

Best way if you want to update the same record in trigger then always go with before event. This way you can skip the extra DML.

Wednesday, 14 March 2018

       System.ListException: Duplicate id in list: 001XXXXXXXXXXXX

Lists can hold duplicate values, but if it contains duplicate sobject IDs and you try to update you'll get the error.

Solution:

1. Create a map of  <id,sobject>
2. Convert the list to Map so that the duplicate IDs are removed.
3. Update the values part of the Map.

Sample code :

// pick up any id from your salesforce org, in this sample it is account id.
id aid = '0017F000002WkkdQAC';

list <account> al = new list <account>();

for(account a : [select id from account where id ='0017F000002WkkdQAC']){
account acc = new account(id = aid);
    al.add(a);
    al.add(acc);
}
//create a map that will hold the values of the list
map<id,account> accmap = new map<id,account>();

//put all the values from the list to map.
accmap.putall(al);
if(accmap.size()>0){
update accmap.values();
}

Saturday, 24 February 2018

             Using JSON in Visualforce page in Salesforce




JSON stands for “Java Script Object Notation“.

JSON.serialize() is used to generate JSON. It is a lightweight data-interchange format.

JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
---------------------------------------------------------------------------------------------------------

<apex:page controller="sample1" action="{!parseJson}">
    <p>
       <b> displaying json format in visulaforce page</b>
    </p>
    {!text1}
 
    <apex:pageblock >
         <p>
        <b> Displaying Json data in PageBloack Table</b>
    </p>
        <apex:pageblockTable value="{!jsonList}" var="json">
            <apex:column headerValue="id" value="{!json.id}"/>
            <apex:column headerValue="name" value="{!json.name}"/>
        </apex:pageblockTable>
    </apex:pageblock>
</apex:page>


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


public class sample1 {
 public String text1 {get;set;}
    public list<JsonWrapper> jsonList{get;set;}
    public sample1()
    {
         jsonList=new list<JsonWrapper>();
    } 
    public void parseJson()
    {
        String soql = 'SELECT Name FROM Account LIMIT 5';
        List<Account> acct = Database.Query(soql);
        text1 = JSON.serialize(acct);
        jsonList=(List<JsonWrapper>) System.JSON.deserialize(text1,List<JsonWrapper>.class);
    }
 
 
    public class JsonWrapper{
        public string id{get;set;}
        public string name{get;set;}
    }
}

Image:


Wednesday, 17 January 2018

Create a modal or popup box in salesforce Lightning


I am going to demonstrate salesforce lightning popup model. This model is very simple here I used aura: if condition to show and hide the model.


LightningPopup.cmp

<aura:component >
    <aura:attribute name="openmodel" type="boolean" default="false"/>
    <div class="slds-m-around--xx-large">
        <button class="slds-button slds-button--brand" onclick="{!c.openModel}">Pop up Model</button>  
        <aura:if isTrue="{!v.openmodel}">
            <div role="dialog" tabindex="-1" aria-labelledby="header99" class="slds-modal slds-fade-in-open ">
                <div class="slds-modal__container">
                    <div class="slds-modal__header">
                        <button class="slds-button slds-modal__close slds-button--icon-inverse" title="Close" onclick="{!c.closeModel}">
                            X
                            <span class="slds-assistive-text">Close</span>
                        </button>
                        <h2 id="header99" class="slds-text-heading--medium">Some Inspiration never dies</h2>
                    </div>
                    
                    <div class="slds-modal__content slds-p-around--medium">
                        <p><b>Stay true to yourself, yet always be open to learn. Work hard, and never give up on your dreams, even when nobody else believes they can come true but you. These are not cliches but real tools you need no matter what you do in life to stay focused on your path.
                            
                            </b>
                        </p>
                    </div>
                    
                    <div class="slds-modal__footer">
                        <button class="slds-button slds-button--neutral" onclick="{!c.closeModel}" >Cancel</button>
                        
                    </div>
                </div>
            </div>
            <div class="slds-backdrop slds-backdrop--open"></div>
            
        </aura:if>
    </div>
</aura:component>
---------------------------------------------------------------------------------------------
LightningPopup.controller
({
    openModel: function(component, event, helper) {
        
        component.set("v.openmodel", true);
    },
    
    closeModel: function(component, event, helper) {
        
        component.set("v.openmodel", false);
    }
})
------------------------------------------------------------------------------
Preview it using salesforce Lightning App:

<aura:application extends="force:slds">
    <c:LightningPopup />
</aura:application>

Saturday, 13 January 2018

Simple SOSL scenario:

Create a visual force page:

<apex:page controller="SOSLController">
    <apex:form >
        <apex:inputText value="{!searchStr}"/>
        <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!soslDemo_method}" reRender="acct,error,oppt,cont" status="actStatusId"/>
        <apex:actionStatus id="actStatusId">
            <apex:facet name="start" >
                <img src="/img/loading.gif"/>                    
            </apex:facet>
        </apex:actionStatus>
    </apex:form>
    
    <apex:outputPanel title="" id="error">
        <apex:pageMessages ></apex:pageMessages>
    </apex:outputPanel>
    
    <apex:pageBlock title="Accounts" id="acct">
        <apex:pageblockTable value="{!accList }" var="acc">
            <apex:column value="{!acc.name}"/>
            <apex:column value="{!acc.Type}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
    
    <apex:pageBlock title="Contacts" id="cont">
        <apex:pageblockTable value="{!conList}" var="con">
            <apex:column value="{!con.name}"/>
            <apex:column value="{!con.email}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
    
    <apex:pageBlock title="Opportunities" id="oppt">
        <apex:pageblockTable value="{!optyList}" var="opty">
            <apex:column value="{!opty.name}"/>
            <apex:column value="{!opty.StageName}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
    
</apex:page>
--------------------------------------------------------------------------------------

Public with sharing class SOSLController{
    Public List<Opportunity> optyList {get;set;}
    Public List<contact> conList{get;set;}
    Public List<account> accList{get;set;}
    
    Public String searchStr{get;set;}
    Public SOSLController(){
    }
    
    Public void soslDemo_method(){
        optyList = New List<Opportunity>();
        conList = New List<contact>();
        accList = New List<account>();
        if(searchStr.length() > 1){
            String searchStr1 = '*'+searchStr+'*';
            String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
            List<List <sObject>> searchList = search.query(searchQuery);
            accList = ((List<Account>)searchList[0]);
            conList  = ((List<contact>)searchList[1]);
            optyList = ((List<Opportunity>)searchList[2]);
            if(accList.size() == 0 && conList.size() == 0 && optyList.size() == 0){
                apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
                return;
            }
        }
        else{
            apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please enter at least two characters..'));
            return;
        }
    }
}
--------------------------------------------------------------------------------------------




                           SOSL Queries:

  • Salesforce Object Search Language (SOSL) is a Salesforce search language that is used to perform text searches in records. 
  • Use SOSL to search fields across multiple standard and custom object records in Salesforce.

This is an example of a SOSL query that searches for accounts and contacts that have any fields with the word 'SFDC'.

List<List<SObject>> searchList = [FIND 'SFDC' IN ALL FIELDS
                                      RETURNING Account(Name), Contact(FirstName,LastName)];
 
Differences and Similarities Between SOQL and SOSL

Like SOQL, SOSL allows you to search your organization’s records for specific information. Unlike SOQL, which can only query one standard or custom object at a time, a single SOSL query can search all objects.

Another difference is that SOSL matches fields based on a word match while SOQL performs an exact match by default (when not using wildcards). For example, searching for 'Digital' in SOSL returns records whose field values are 'Digital' or 'The Digital Company', but SOQL returns only records with field values of 'Digital'.

Steps:
In the Developer Console, open the Execute Anonymous window from the Debug menu.
Insert the below snippet in the window and click Execute.

// Add account and related contact
Account acct = new Account(
    Name='SFDC Computing',
    Phone='(415)555-1212',
    NumberOfEmployees=50,
    BillingCity='San Francisco');
insert acct;

// Once the account is inserted, the sObject will be
// populated with an ID.
// Get this ID.
ID acctID = acct.ID;

// Add a contact to this account.
Contact con = new Contact(
    FirstName='Carol',
    LastName='Ruiz',
    Phone='(415)555-1212',
    Department='Wingo',
    AccountId=acctID);
insert con;

// Add account with no contact
Account acct2 = new Account(
    Name='The SFDC Query Man',
    Phone='(310)555-1213',
    NumberOfEmployees=50,
    BillingCity='Los Angeles',
    Description='Expert in wing technologies.');
insert acct2;


Let’s try running the following SOSL example:

In the Developer Console, click the Query Editor tab.
Copy and paste the following into the first box under Query Editor, and then click Execute.

FIND {Wingo} IN ALL FIELDS RETURNING Account(Name), Contact(FirstName,LastName,Department)


The search query in the Query Editor and the API must be enclosed within curly brackets ({Wingo}). In contrast, in Apex the search query is enclosed within single quotes ('Wingo').


Basic SOSL Syntax
SOSL allows you to specify the following search criteria:
Text expression (single word or a phrase) to search for
Scope of fields to search
List of objects and fields to retrieve
Conditions for selecting rows in the source objects


Execute this snippet in the Execute Anonymous window of the Developer Console. Next, inspect the debug log to verify that all records are returned.

List<List<sObject>> searchList = [FIND 'Wingo OR SFDC' IN ALL FIELDS
                   RETURNING Account(Name),Contact(FirstName,LastName,Department)];
Account[] searchAccounts = (Account[])searchList[0];
Contact[] searchContacts = (Contact[])searchList[1];

System.debug('Found the following accounts.');
for (Account a : searchAccounts) {
    System.debug(a.Name);
}

System.debug('Found the following contacts.');
for (Contact c : searchContacts) {
    System.debug(c.LastName + ', ' + c.FirstName);
}