Test Attachments records in Apex Test Class

@isTest(SeeAllData=true)
private class TestAttachment{
    static testmethod void testattach(){
   
        Account a = new Account(Name='newAcct');
        Test.startTest();
        insert a;
        Test.stopTest();
        System.debug('Account created: ' + a.Id);
       
        Attachment attach=new Attachment();
        attach.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        attach.body=bodyBlob;
        attach.parentId=a.Id;
        attach.ContentType = 'application/msword';
        attach.IsPrivate = false;
        attach.Description = 'Test';
        insert attach;
       
        System.debug('Inserted: '+ attach.Id);
       
        List<Account> acct = [SELECT id, Name,
        (SELECT Id FROM CombinedAttachments)
        FROM Account where id = :a.Id];
       
        System.debug('Account Query : '+acct);
       
        for(Account a1 : acct){
            System.debug('Id: '+a1.Id + ' Name: '+a1.Name + ' CombAttach: '+ a1.CombinedAttachments);   
            System.assert(a1.CombinedAttachments.size()>0);       
        }       
    }
}

cheers! 

How to Select All Fields with SOQL in Apex




How to query all fields from an object by exploiting the metadata available from the DescribeSObjectResult class.

Code

DescribeSObjectResult describeResult = Account.getSObjectType().getDescribe();

List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );


String query = ' SELECT ' + String.join( fieldNames, ',' ) +' FROM '+ describeResult.getName();
List<SObject> records = Database.query( query ); System.debug( records );
Debug

22:42:58:132 USER_DEBUG [13]|DEBUG|(Account:{Id=0012800000nY6VqAAK, IsDeleted=false, Name=sForceTest1, BillingStreet=The Landmark @ One Market, BillingCity=SanFrancisco, BillingState=CA, BillingPostalCode=94105, BillingCountry=US, BillingAddress=API address [ The Landmark @ One Market, SanFrancisco, CA, 94105, US, null, null, null, null, null], ShippingAddress=null, Phone=(415) 901-7000, Website=http://www.sforcetest1.com, PhotoUrl=/services/images/photo/0012800000nY6VqAAK, OwnerId=00528000001Dmp3AAC, CreatedDate=2016-08-12 13:34:29, CreatedById=00528000001Dmp3AAC, LastModifiedDate=2016-08-12 13:34:29, LastModifiedById=00528000001Dmp3AAC, SystemModstamp=2016-08-12 22:24:30, IsPartner=false, IsCustomerPortal=false, CleanStatus=Pending, Potential_Value__c=0.00, Allowed_Support__c=false, Match_Billing_Address__c=false}, ,.....

Cheers!

Generate Random Password on Button Click in Salesforce



On Click Button Generate Password

Button Code

//Connection
{!REQUIRESCRIPT("/soap/ajax/37.0/connection.js")} 
var p = new sforce.SObject("Contact"); 
p.id = "{!Contact.Id}"; 

if(confirm('Are you sure you want to generate a new password for this Contact?')==true){ 
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; 
var string_length = 8; 
var randomstring = ''; 

//random password generate logic
for(var i=0; i<string_length; i++){ 
var rnum = Math.floor(Math.random() * chars.length); 
randomstring += chars.substring(rnum,rnum+1); 

//assign random generated password
p.Password__c = randomstring; 
//Update contact
result = sforce.connection.update([p]); 
//reload page
location.reload(true);

Thanks Cheers! Lets Share your feedback.

Sorting Table By Java Script


Visualforce Page

<apex:page controller="tableCls" showheader="false" id="thePage" sidebar="false"

    docType="html-5.0">
    <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
        lang="en">
    <apex:pageMessages id="msg" />
    <apex:form id="theform">
        <meta charset="utf-8" />
        <meta http-eqv="x-ua-campatible" content="ie-edge" />
        <meta name="viewport" content="width=device-width, intial-scale=1" />
        <apex:stylesheet value="{!URLFOR($Resource.SLDS232,'assets/styles/salesforce-lightning-design-system.min.css')}"/>
        <apex:stylesheet value="{!URLFOR($Resource.SLDS232,'assets/styles/salesforce-lightning-design-system.css')}"/>
        
         <apex:includeScript value="https://code.jquery.com/jquery-1.11.1.min.js"/>
         <apex:includeScript value="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"/>
         <apex:includeScript value="https://www.datatables.net/release-datatables/extensions/FixedColumns/js/dataTables.fixedColumns.js"/>
         <apex:stylesheet value="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.css"/>
         <apex:stylesheet value="https://www.datatables.net/release-datatables/extensions/FixedColumns/css/dataTables.fixedColumns.css"/>
          
         <apex:outputPanel id="tbb1">
         <script>
                j$ = jQuery.noConflict();
                j$(document).ready(function() {
        
                   j$('[id$="OppTable"]').DataTable({
                        "searching": true,
                        "paging":true,
                        "destroy" : true, 
                        "autoWidth" : true,
                        "order": [[ 3, "desc" ]],   
                    });    
                });
            
            </script>
        </apex:outputPanel>
        <Br/><Br/>
        
        
<table class="slds-table slds-table--bordered" id="OppTable">
<thead>
                                           
      <tr class="slds-text-heading--label">
        <th class="slds-is-sortable" scope="col">
         <div class="slds-truncate">#</div>
        </th>
        <th class="slds-is-sortable" scope="col">
          <div class="slds-truncate">Name</div>
        </th>
        <th class="slds-is-sortable" scope="col">
          <div class="slds-truncate">Stage</div>
        </th>
        <th class="slds-is-sortable" scope="col">
          <div class="slds-truncate">Amount</div>
        </th>
        <th class="slds-is-sortable" scope="col">
          <div class="slds-truncate">Account Name</div>
        </th>
        <th class="slds-is-sortable" scope="col">
          <div class="slds-truncate">Phone</div>
        </th>
      </tr>
   </thead>

     <tbody>
       <apex:variable var="indexTL" value="{!1}" />
         <Apex:repeat value="{!opportunityList}" var="opp">
          <tr class="slds-hint-parent">
     <td class="" data-label="RCNumber">
        <apex:outputtext value="{!indexTL}"/>
        <apex:variable var="indexTL" value="{!indexTL+1}" />
     </td>
     <td class="" data-label="OppName">
    <apex:outputtext styleclass="slds-output" value="{!opp.Name}"/>
    </td>
    <td class="" data-label="opportunityStage"> 
<apex:outputtext styleclass="slds-output" value="{!opp.StageName}"/>
   </td>
   <td class="" data-label="OpportunityAmount">
<apex:outputtext styleclass="slds-output" value="{!opp.Amount}" />
  </td>
  <td class="" data-label="AccountName">
<apex:outputtext styleclass="slds-output" value="{!opp.Account.Name}"/>
  </td>
  <td class="" data-label="phone">
<apex:outputtext styleclass="slds-output" value="{!opp.Account.Phone}"/>
 </td>
 </tr>
</apex:repeat>
 </tbody>
</table>
  </apex:form>
  </html>

</apex:page>


apex class

public class tableCls {
    public List<Opportunity> opportunityList{get;set;}
    
    public tableCls(){
        try{
            opportunityList=[SELECT Id, Name, StageName, Amount, 
                Account.Name, Account.BillingAddress, Account.Phone 
                                FROM Opportunity];
        }Catch(Exception e){
            opportunityList=new List<Opportunity>();
        }   
    }

}


Thanks Cheers! Lets share your feedback.

How to show User Login link in Salesforce


Manually enable 'Organization Admins Can Login as Any User'
If you are on EnterprisePerformanceUnlimited or Developer Editions and your org was NOT upgraded from Professional to Enterprise: 
1. Click Setup
2. Under 'Administer' select Security Controls | Login Access Policies.
3. Select Administrators Can Log in as Any User.
4. Click Save.


Request feature enablement from Salesforce Support

If your org was upgraded from Professional Edition to Enterprise Edition, use the following steps:
1. Have a System Administrator create a case with Salesforce Customer Support.
2. In the case details, include:
  • Your business case or justification.
  • The organization ID for which you want the feature enabled.
  • The text: Feature requested: Enable Org Admins to log in as any user without having access granted by the Users.​

How to Find Salesforce Object Id (Custom / Standard)



In salesforce every object has unique Id. first three digit called Object Id.

Example :
Account - 001, Contact -003, Opportunity -006

Note :Custom Object Id change in production so don't  hardcode Object Id in code.

how you get through code

// At place Objectname__c use- object API Name
system.debug('ObjectId ==>'+ Objectname__c.sobjecttype.getDescribe().getKeyPrefix());


open developer console and debug





Thanks Cheers!


Call Apex Class from Custom Button (JAVASCRIPT) in Salesforce


Step 1  :  Lets first create the Apex class



Things to Remember: 
  • Class needs to be a Global class 
  • and the method you intend to call from the javascript must be a WebService Method
e.g.

Global Class RG_LeadConversionCls {    


webservice static void LeadConvert(Id Leadid)

{       

}



Step 2 : Now to setup the custom Button.

  • Goto --> Setup --> Object --> Buttons, links and Actions section
  • Click New Button or Link
  • Enter the Name of the button
  • Behaviour : Execute Javascript
  • Content source : On-Click Javascript


{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}


sforce.apex.execute("RG_LeadConversionCls","LeadConvertId",{Leadid:"{!Lead.Id}"});