• Raj V
  • 6053 Points
  • Member since 2016

  • Chatter
  • 201
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
  • 1634
Hi Guys,

How to achive this:  Fetch the Email template and show in dropdown in Lightning Component

I am a beginner in salesforce lightning and trying to create few components.
Can someone explain to me
1) what is the difference between 'id' and 'aura:id' attribute?
2) when to use component.get() and component.find() ?
I´m trying to make the test class of this, but I having problems, I have an error......System.StringException: Invalid id: Colaborador__c:{Id=a0Of4000003bHFxEAM}

this is my apex class
public class ActionColocarCls {
    public static Colaborador__c getAccountData (Id accountId){        
        Colaborador__c searchAcc = new Colaborador__c();
        searchAcc = [SELECT Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__C WHERE Id =: accountId];
        system.debug('Account: ' + searchAcc);
        return searchAcc;

This is the test class that I´m doing 
global class ActionColocarClsTest {
    static void setup()	{
        Profile profileAdmin = [SELECT Id FROM Profile WHERE name = 'System Administrator'];
        UserRole roleAdmin=[SELECT Id FROM UserRole WHERE PortalType = 'None' Limit 1];
        User user_test=new User(UserRoleId = roleAdmin.Id, ProfileId = profileAdmin.Id,
                                Alias='Admin', Email = 'contactAdmin@deloitte.com',
                                EmailEncodingKey = 'UTF-8', Firstname = 'test',
                                Lastname = 'user', languagelocalekey= 'en_US',
                                LocaleSidKey = 'en_Us', TimeZoneSidKey = 'America/Chicago');
        insert user_test;
        User userAdmin=[SELECT id FROM User WHERE email = 'contactAdmin@deloitte.com' LIMIT 1];
            Colaborador__c con = new Colaborador__c();               
            insert con;                                                    
            Colaborador__c objCol =[SELECT id,Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__C];                 
     static testmethod void tesActionColocar(){
         Colaborador__c objCol2 = [SELECT id FROM Colaborador__C LIMIT 1];         
         String accountId=String.valueOf(objCol2) ;              
         system.debug('resumen' + objCol2);
         Colaborador__c objColaborador = [SELECT Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__c WHERE Id =:accountId];                                              
         system.debug('Taer records de colaboradores' +objColaborador);                                       

Hello All,
I have a Class that performs a call out;
Global class CallTrexWebServiceAccountUpdate{
    public static Account accounts {get;set;}
    public static String myresponse{get;set;}

    webservice static string ABCWebServiceAccountUpdate(String id) {
        return myresponse;        

      static void ABCWebServiceAccountUpdateAsync(String id)  
           accounts = [SELECT id,Partner_Type__c FROM Account WHERE id =:id];
             if(id != null )
                   HttpRequest req = new HttpRequest();
                   Http http = new Http();
                   String url = 'https://blabla/Services.asmx/UpdateAccount?accountId='+id;
                   HTTPResponse resp = http.send(req);
                   myresponse = resp.getBody();

Have a test Class and this works fine.

I now have additional Apex triggers to deploy and now  its failing on the above Class.  The trigger I am deploying is related to the Cases.

The fatal error is on line :   HTTPResponse resp = http.send(req);
Methods defined as TestMethod do not support Web service callouts

And this code did deploy to production originally but I deployed with just the Class and test Class.

If anyone can spot the issue or has any suggestions I would greatly appreciate it.

Hi Experts,

I have created an Apex Class, some one please help me on creating Test Class. Thanks in Advance.

Note: In Same Class (end of the class) I have tried test class, but no luck.

public class UserRoleHelper {

    /********************* Properties used by getRootNodeOfUserTree function - starts **********************/
    // map to hold roles with Id as the key
    private static Map <Id, UserRole> roleUsersMap;

    // map to hold child roles with parentRoleId as the key
    private static Map <Id, List<UserRole>> parentChildRoleMap;

    // List holds all subordinates
    private static List<User> allSubordinates {get; set;}
    // Global JSON generator
    private static JSONGenerator gen {get; set;}

    /********************* Properties used by getRootNodeOfUserTree function - ends **********************/
    /********************* Properties used by getSObjectTypeById function - starts ********************* */
    // map to hold global describe data
    private static Map<String,Schema.SObjectType> gd;
    // map to store objects and their prefixes
    private static Map<String, String> keyPrefixMap;

    // to hold set of all sObject prefixes
    private static Set<String> keyPrefixSet;
    /********************* Properties used by getSObjectTypeById function - ends **********************/
    /* // initialize helper data */ 
    static {
        // initialize helper data for getSObjectTypeById function
        // initialize helper data for getRootNodeOfUserTree function
    /* // init1 starts <to initialise helper data> */
    private static void init1() {
        // get all objects from the org
        gd = Schema.getGlobalDescribe();
        // to store objects and their prefixes
        keyPrefixMap = new Map<String, String>{};
        //get the object prefix in IDs
        keyPrefixSet = gd.keySet();
        // fill up the prefixes map
        for(String sObj : keyPrefixSet) {
            Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
            String tempName = r.getName();
            String tempPrefix = r.getKeyPrefix();
            keyPrefixMap.put(tempPrefix, tempName);
    /* // init1 ends */

    /* // init2 starts <to initialise helper data> */
    private static void init2() {
        // Create a blank list
        allSubordinates = new List<User>();
        // Get role to users mapping in a map with key as role id
        roleUsersMap = new Map<Id, UserRole>([select Id, Name, parentRoleId, (select id, name from users) from UserRole order by parentRoleId]);
        // populate parent role - child roles map
        parentChildRoleMap = new Map <Id, List<UserRole>>();        
        for (UserRole r : roleUsersMap.values()) {
            List<UserRole> tempList;
            if (!parentChildRoleMap.containsKey(r.parentRoleId)){
                tempList = new List<UserRole>();
                parentChildRoleMap.put(r.parentRoleId, tempList);
            else {
                tempList = (List<UserRole>)parentChildRoleMap.get(r.parentRoleId);
                parentChildRoleMap.put(r.parentRoleId, tempList);
    /* // init2 ends */

    /* // public method to get the starting node of the RoleTree along with user list */
    public static RoleNodeWrapper getRootNodeOfUserTree (Id userOrRoleId) {
        return createNode(userOrRoleId);
    /* // createNode starts */
    private static RoleNodeWrapper createNode(Id objId) {
        RoleNodeWrapper n = new RoleNodeWrapper();
        Id roleId;
        if (isRole(objId)) {
            roleId = objId;
            if (!roleUsersMap.get(roleId).Users.isEmpty()) {
                n.myUsers = roleUsersMap.get(roleId).Users;
                n.hasUsers = true;
        else {
            List<User> tempUsrList = new List<User>();
            User tempUser = [Select Id, Name, UserRoleId from User where Id =: objId];
            n.myUsers = tempUsrList;
            roleId = tempUser.UserRoleId;
        n.myRoleId = roleId;
        n.myRoleName = roleUsersMap.get(roleId).Name;
        n.myParentRoleId = roleUsersMap.get(roleId).ParentRoleId;

        if (parentChildRoleMap.containsKey(roleId)){
            n.hasChildren = true;
            n.isLeafNode = false;
            List<RoleNodeWrapper> lst = new List<RoleNodeWrapper>();
            for (UserRole r : parentChildRoleMap.get(roleId)) {
            n.myChildNodes = lst;
        else {
            n.isLeafNode = true;
            n.hasChildren = false;
        return n;
    public static List<User> getAllSubordinates(Id userId){
        return allSubordinates;
    public static String getTreeJSON(Id userOrRoleId) {
        gen = JSON.createGenerator(true);
        RoleNodeWrapper node = createNode(userOrRoleId);
        return gen.getAsString();
    private static void convertNodeToJSON(RoleNodeWrapper objRNW){
            gen.writeStringField('title', objRNW.myRoleName);
            gen.writeStringField('key', objRNW.myRoleId);
            gen.writeBooleanField('unselectable', false);
            gen.writeBooleanField('expand', true);
            gen.writeBooleanField('isFolder', true);
            if (objRNW.hasUsers || objRNW.hasChildren)
                    if (objRNW.hasUsers)
                        for (User u : objRNW.myUsers)
                                gen.writeStringField('title', u.Name);
                                gen.writeStringField('key', u.Id);
                    if (objRNW.hasChildren)
                        for (RoleNodeWrapper r : objRNW.myChildNodes)
    /* // general utility function to get the SObjectType of the Id passed as the argument, to be used in conjunction with */ 
    public static String getSObjectTypeById(Id objectId) {
        String tPrefix = objectId;
        tPrefix = tPrefix.subString(0,3);
        //get the object type now
        String objectType = keyPrefixMap.get(tPrefix);
        return objectType;
    /* // utility function getSObjectTypeById ends */
    /* // check the object type of objId using the utility function getSObjectTypeById and return 'true' if it's of Role type */
    public static Boolean isRole (Id objId) {
        if (getSObjectTypeById(objId) == String.valueOf(UserRole.sObjectType)) {
            return true;
        else if (getSObjectTypeById(objId) == String.valueOf(User.sObjectType)) {
            return false;
        return false;
    /* // isRole ends */
    public class RoleNodeWrapper {
        // Role info properties - begin
        public String myRoleName {get; set;}
        public Id myRoleId {get; set;}
        public String myParentRoleId {get; set;}
        // Role info properties - end
        // Node children identifier properties - begin
        public Boolean hasChildren {get; set;}
        public Boolean isLeafNode {get; set;}
        public Boolean hasUsers {get; set;}
        // Node children identifier properties - end
        // Node children properties - begin
        public List<User> myUsers {get; set;}
        public List<RoleNodeWrapper> myChildNodes {get; set;}
        // Node children properties - end   
        public RoleNodeWrapper(){
            hasUsers = false;
            hasChildren = false;

//    @isTest
//    static void testUserRoleHelper() {
        // test the output in system debug with role Id
        Id roleId = '00E90000000pMaP';
        RoleNodeWrapper startNodeWithRoleId = UserRoleHelper.getRootNodeOfUserTree(roleId);
        String strJsonWithRoleId = JSON.serialize(startNodeWithRoleId);

        // now test the output in system debug with userId
//        Id userId = UserInfo.getUserId() ;
        RoleNodeWrapper startNodeWithUserId = UserRoleHelper.getRootNodeOfUserTree(userId);
        String strJsonWithUserId = JSON.serialize(startNodeWithUserId);
        // test whether all subordinates get added
        //Id userId = '005900000011xZv';
//        String str = UserRoleHelper.getTreeJSON(userId);
        //List<User> tmpUsrList = UserRoleHelper.getAllSubordinates('00E90000000pMaP');
        //system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%tmpUsrList:' + tmpUsrList);
//   }
I am trying to add a field from the account when creating a task on an opportunity or account, or contact. I should be able to access the AccountId field on the task record to pull this,.

trigger AccountRecordType on Task (before insert, before update) {
for (Task T : trigger.New){
Account a = [select id,recordtypeid from Account where id =: trigger.new[0].AccountId];    
if(a.recordtypeid == '012i0000000Ou0CAAS'){
        t.Account_record_Type__c = 'Customer Account';        
        if(a.recordtypeid == '012i0000000Ou0EAAS'){
        t.Account_record_Type__c = 'Prospect Account';        
        if(a.recordtypeid == '012i0000000Ou0DAAS'){
        t.Account_record_Type__c = 'Partner Account Account';        

Hi All. I am positive I am missing something simple. I would like to throw an error on a standard page - at the top of the page - when a boolean has been set on the record. This effectively locks the reord from being adited any further. Code follows:

You can see the error I would like to throw. Problem is that the error thrown looks like this:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger SalesorderTrigger caused an unexpected exception, contact your administrator: SalesorderTrigger: execution of BeforeUpdate caused by: System.FinalException: SObject row does not allow errors: Class.SOTriggerHelper.validateSOCanBeSubmitted: line 10, column 1


What am I missing?

public class myException extends Exception {}
	public static void validateSOCanBeSubmitted(List<Netsuite_Sales_Order__c> newTrigger, List<Netsuite_Sales_Order__c> oldTrigger, Map<Id, Netsuite_Sales_Order__c> oldMap){
		for(Netsuite_Sales_Order__c so :oldTrigger){
			if(so.Netsuite_SO_Entered__c == true){

					so.addError( new myException('This SO has been locked because it has already been submitted'));

I am trying to write a test class for a trigger that copies a list of Permission Sets from an existing to a new user. My thought was to have my test class compare the new user and the mirror user Permission Set Assignments to pass my code coverage. However, when I query either the mirror user or the new user I am getting an "Attempt to de-reference a null object" every time.

When I check the logs the trigger works (it fires after insert), but when I get to mirrorPerm.addAll I get the de-refernce error. 

If it matters, when I create a new user outside of the debugger the Permission Sets assign correctly, so I assume the trigger is working. 

private class UserPermSetTest {
	public static List<PermissionSetAssignment> userPerm;
    public static List<PermissionSetAssignment> mirrorPerm;
    public static List<User> newUserList;
    /* Test creating a new user */
    static testMethod void testNewUserCreated(){
        Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        UserRole r = [SELECT Id FROM UserRole WHERE Name = 'System Administrator'];
        User mirror = [SELECT Id FROM User WHERE Name = 'Tyler Ditto'];
        user newUser = new User(FirstName = 'Johnny',
                                 LastName = 'Quest',
                                 Alias = 'JQuest',
                                 Email = 'JQuest@ptest.com',
                                 UserName = 'JQuest@ptest.com.kevink',
                                 CommunityNickname = 'JQuest',
                                 UserRoleId = r.Id,
                                 ProfileId = p.Id,                                 
                                 Hire_Date__c = date.today(),
                                 Mirror_User__c = mirror.Id,
                                 ManagerId = mirror.Id,
                                 TimeZoneSidKey = 'America/New_York',
                                 LocaleSidKey = 'en_US',
                                 emailencodingkey = 'UTF-8',
                                 LanguageLocaleKey = 'en_US');
        insert newUser;
        System.debug('******************************* USER ID ' + newUser.Id);
        System.debug('******************************* MIRROR ID ' + mirror.Id);
        mirrorPerm.addAll([SELECT Id FROM PermissionSetAssignment WHERE AssigneeId =: mirror.Id AND PermissionSet.IsOwnedByProfile = false]);
        System.debug('******************************* MIRROR PERMISSION SET ' + mirrorPerm);
        userPerm.addAll([SELECT Id FROM PermissionSetAssignment WHERE AssigneeId =: newUser.Id AND PermissionSet.IsOwnedByProfile = false]);
        System.debug('******************************* USER PERMISSION SET ' + userPerm);
        System.assertEquals(userPerm.equals(mirrorPerm), true);

I new to Apex, and failing miserably.  Time and time again and I cannot come up with anything beyond 0% code coverage.  I have the following trigger:
trigger leadDuplicatePreventer on opportunity(before insert) {
   set<string> settgs = new set<string>();
   list<opportunity> opps = [select id,Trigger_Help__c  from opportunity WHERE CreatedDate = LAST_N_DAYS:90];
   Profile p=[SELECT ID, Name FROM Profile WHERE Id=:userinfo.getProfileId() Limit 1];
   for(opportunity opp : opps){
     if(opp.Trigger_Help__c != null && p.Name <> 'System Administrator'){
   for(opportunity op : trigger.new){
	     op.adderror('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.');


The Trigger_Help__c is a formula field that combines Oppty_Type__c+Account Id.  These 9 lines are all I have to figure out and I cannot get this for the life of me.  My current test class is as follows:

private class TestleadDuplicatePreventer {
    @isTest static void TestleadDuplicatePreventerwithOneOpp() {
    Account acct = new Account(Name='Test Account');
    insert acct;
    Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
                                     StageName='Open Opportunity',
                                     Facility__c='Tacoma WA',
                                     Oppty_Type__c='UCO Service',
    insert opp;
    opp= new Opportunity(Name='Opportunity Test',
                        StageName='Open Opportunity',
                        Facility__c='Tacoma WA',
                        Oppty_Type__c='UCO Service',
        insert opp;
    catch(Exception duplicate)
       System.assertEquals('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.', duplicate.getMessage());
    //this should probably be in a separate test method
    Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
  User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com',
     EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
     LocaleSidKey='en_US', ProfileId = p.Id,
     TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com');

  System.runAs(u2) {
      insert opp;
But I have also been trying and failing with the following test class:
public class TestleadDuplicatePreventer {
    static testMethod Void TestleadDuplicatePreventerwithOneOpp() {
        User u1 = [SELECT Id FROM User WHERE Alias='jmilt'];
        Account acct = new Account(Name='Test Account');
        insert acct;
        Opportunity opp1 = new Opportunity(Name=acct.Name + ' Opportunity',
                                         StageName='Open Opportunity',
                                         Facility__c='Tacoma WA',
                                         Oppty_Type__c='UCO Service',
        Opportunity opp2 = new Opportunity(Name=acct.Name + ' Opportunity1',
                                          StageName='Open Opportunity',
                                          Facility__c='Tacoma WA',
                                          Oppty_Type__c='UCO Service & Indoor Equipment',
        Opportunity opp3 =  new Opportunity(Name=acct.Name + ' Opportunity2',
                                           StageName='Open Opportunity',
                                           Facility__c='Tacoma WA',
                                           Oppty_Type__c='Trap Service',
            Opportunity[] opps = new Opportunity [] {opp1, opp2, opp3};
            insert opps;
        Opportunity dup1 = new Opportunity(Name='Check',
                                          StageName='Open Opportunity',
                                          Facility__c='Tacoma WA',
                                          Oppty_Type__c='UCO Service',
            insert dup1;
        catch(Exception duplicate)
            System.assertEquals('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.', duplicate.getMessage());

   Test.stopTest(); }


If anyone is out there who can help it would be greatly appreciated!
I am using the sfdx force:source:pull command to bing scratch organization updates into my project.  I get the error, "ERROR:  Entity type 'NetworkBranding' is not available in this api version."

Do I need to change an API version somewhere or does sfdx not support that entity type yet?
My code is:-
Controller extension:
public class wrapController {
    public String typeValue{get;set;}
    public List<SelectOption> typeOptions{get;set;}
    public List<wrapAccount> wrapaccts{get;set;}
    public wrapController(ApexPages.StandardController stdController){
        typeOptions = new List<SelectOption>();
        typeOptions.add(new SelectOption('None','--None--'));
        Schema.DescribeFieldResult fieldResult = Account.Type.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistvalues();
        for(Schema.PicklistEntry p : ple){
            typeOptions.add(new SelectOption(p.getvalue(), p.getvalue()));
        wrapaccts=new List<wrapAccount>();
        List<Account> accList = new List<Account>([SELECT Name, Phone, AccountNumber, Type FROM Account WHERE Type = :typeValue]);
        for(Account acc :accList){
            wrapaccts.add(new wrapAccount(acc));
    public class wrapAccount{
        public Boolean checkbox{get;set;}
        public Account ac{get;set;}
        public wrapAccount(Account a){

<apex:page standardController="Account" extensions="wrapController" id="pg">
    <apex:form id="fm">
        <apex:pageBlock title="Account Info" id="Account_List">
            <apex:pageBlockSection title="Accounts" id="pbs">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Account Type:"/>
                    <apex:selectList value="{!typeValue}" size="1">
                        <apex:selectOptions value="{!typeOptions}"/>
                        <apex:actionSupport event="onchange" reRender="fm"/>
            <apex:pageBlockTable value="{!wrapaccts}" var="wr" id="pbt">
                <apex:column headerValue="Select" > <apex:inputCheckbox id="cb"/> </apex:column>
                <apex:column value="{!wr.ac.Name}" headerValue="Account Name"/>
                <apex:column value="{!wr.ac.Phone}" headerValue="Phone Number"/>
                <apex:column value="{!wr.ac.AccountNumber}" headerValue="Account Number"/>                
                <apex:column value="{!wr.ac.Type}" headerValue="Account Type"/>                                
i want to use tabset-element (sample code from salesforce), but doesnt seem to have a default style. How can i add styling to this?

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <lightning:tabset variant="scoped">
        <lightning:tab label="Item One">
            Sample Content One
        <lightning:tab label="Item Two">
            Sample Content Two


User-added image
I have à scheduled batch and i want to create test_class.
I have this error: 
Constructor not defined: [BA01_SynchronizeImmofisUpdated_Schedul].<Constructor>(Set<Id>)*

Batch Sechdul:
global class BA01_SynchronizeImmofisUpdated_Schedul implements Schedulable {
List<Immofi__c> Immofis = new List<Immofi__c>();
    Set<Id> setOfImmoFi = new Set<Id>();
       global void execute(SchedulableContext SC) { 
           BA01_SynchronizeImmofisUpdated myBatch = new BA01_SynchronizeImmofisUpdated(setOfImmoFi);
        Id batchinstanceid = database.executeBatch(myBatch); 


public class BA01_SynchronizeImmofisUpdatedSchTest {
     static testMethod void BA01_SynchronizeImmofisUpdatedSchTest()
      List<Immofi__c> Immofis = new List<Immofi__c>();
        Set<Id> setOfImmoFi = new Set<Id>();
        for(Integer i = 0; i < 5; i++)
        Immofi__c a = new Immofi__c(Tech_created__c = true,Tech_To_Synchronize_All__c = true,Name = 'Test Immofi ' + i);

        insert Immofis;
        for(Immofi__c immo : Immofis )
        System.schedule('BA01_SynchronizeImmofisUpdated_Schedul', '0 0 3 * * ?', new BA01_SynchronizeImmofisUpdated_Schedul(setOfImmoFi));
  • May 21, 2018
  • Like
  • 0
Hi i am unable to write test classs for SOSL searchText ...below is my apex class
public class case_exn {
   public Case id{get;set;}
   public String searchText{get;set;}
   List<Case> results = new List<Case>();
   public Boolean IsOwnerSpecific {get;set;}  
   private ApexPages.StandardController ctrl
 public case_exn(ApexPages.StandardController controller)
     id = (Case)controller.getRecord();
    public List<SelectOption> getItems() {

        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Admin mailbox','Admin Mailbox'));
        options.add(new SelectOption('Support Mailbox','Support  Mailbox'));
public String getSearchText() 
      return searchText;
   public void setSearchText(String s) {
      searchText = s;
   public List<Case> getResults() 
      return results;
public pageReference search() {
results = (List<Case>)[FIND :searchText RETURNING Case(CaseNumber,Type, Subject, Priority,Status,CreatedDate,SLA_Flag__c,Owner.Name ];

my Test clas:
public class TestsearchCaseVFPage {
 private static testMethod void testSoslFixedResults()
  Case obj=new Case(Type='test',Subject='selfService',Priority='medium',Status='Inprogress');
  insert obj;  
  ApexPages.StandardController sc = new ApexPages.StandardController(obj);
  case_exn testAccPlan = new case_exn(sc); 
Id [] fixedSearchResults= new Id[testAccPlan.Id];
      //test for searching account in list
        results = SoslService.search(obj.searchText);
  System.assertEquals(testAccPlan.Id, results[0][0].Id, 'Account Ids should match');

But test class Code not working  and coverage also very low....can u pls check and help on this

How to calculate the Odd sum in collection in apex ? can some help me with sample code
hi, i was trying to display a nested json response in visualforce page via pageblocktable

public class JSON2Apex{
    public String request_tracking_id;    //12
    public cls_customers[] customers {get;set;}
    public cls_metadata metadata;
    public class cls_customers {
        public String id    {get;set;}//000131417543005
        public String status {get;set;}    //CANCELLED
        public String category {get;set;}    //OPEN MARKET
        public String line_of_business {get;set;}    //COMMERCIAL
        public String account_type {get;set;}    //master
        public String is_national_account;    //False
        public String is_central_billed;    //False
        public cls_contacts[] contacts {get;set;}
        public cls_wm_metadata wm_metadata;
    public class cls_contacts {
        public String type {get;set;}    //service
        public String organization_name {get;set;}    //SAWRIDGE HOTEL
        public String name {get;set;}    //VIPUL
        public String home_phone {get;set;}    //7807997417
        public String email {get;set;}    //tboutilier@sawridge.com
        public String fax {get;set;}    //7804283335
        public cls_address address {get;set;}
        public cls_cleansed_address cleansed_address;
    public class cls_address {
        public String street {get;set;}    //530 MACKENZIE BLVD
        public String street2 {get;set;}    //VIPUL
        public String city {get;set;}    //FORT MCMURRAY
        public String state {get;set;}    //AB
        public String postal_code {get;set;}    //T9H 4C8
        public String country {get;set;}    //CA
    public class cls_cleansed_address {
        public String street;    //530 MACKENZIE BLVD
        public String street2;    //VIPUL
        public String city;    //FORT MCMURRAY
        public String state;    //AB
        public String postal_code;    //T9H 4C8- 
        public String country;    //CA
    public class cls_wm_metadata{
        public String library;    //202A
        public String company_code;    //949
        public String mas_account_number;    //949-663
        public String mas_status;    //WRTOFFCAN
        public String business_unit;    //B00269
        public String is_canadian_billed;    //True
    public class cls_metadata {
        public String totalCount;    //1
    public static JSON2Apex parse(String json){
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
This is the visualforce page
<apex:pageBlockTable value="{!res.customers}" var="r" >
                    <apex:column headerValue="Type" value="{!r.line_of_business}"></apex:column>  
                    <apex:column headerValue="Name" value="{!r.Name}"/>
                    <apex:column headerValue="Phone" value="{!r.home_phone}"/>
                    <apex:column headerValue="Email" value="{!r.email}"/> 
                    <apex:column headerValue="ShippingAddress"/>  
Class -
public with sharing class CaseContractPageController {

       public string selectedRecordType {get;set;}
    public CaseContractPageController(ApexPages.StandardController controller) {

   public pagereference newPage(){
   recordType rec = [select id from RecordType where developerName=: selectedRecordType AND sObjectType ='Case'] ;
   PageReference pageRef = new PageReference('/500/e?retURL=%2F500%2Fo&RecordType='+rec.id+'&ent=Case');
    return pageRef;
    public pagereference cancelPage(){
   PageReference pageRef = new PageReference('https://ctsfullcrm.comcastctsfull.shnpoc.net');
    return pageRef;

Test Class-

    static testMethod void newPageTestMethod() {
    Account recAccount = new Account(Name='TestAccount');
    Insert recAccount;
    Case recCase = new Case(AccountId=recAccount.Id, RecordTypeId ='012q00000009TUM');
    insert recCase;

    Apexpages.standardcontroller sc = new Apexpages.standardcontroller(recCase);
    CaseContractPageController cseController = new CaseContractPageController (sc);
         Id  recordTypeId = [select id from RecordType where Name='LR - NDA'].id;
    cseController.selectedRecordType  = 'LR - NDA';
    pagereference pagecase = Page.CaseContract;

    system.debug('recordTypeIdTest'+recordTypeId );

    pagecase.getParameters().put('rec.id',recordTypeId );

    }catch(Exception e){}

trigger GetTerritoryIfStateSaved on Lead (before insert,before update) 
    List<Lead> lead1=new List<Lead>();
    public string stateget;
    for(Lead leadc:Trigger.new)
           for (Countries_List__c cl: Countries_List__c.getAll().values()) 


    }   }
      for(Lead AllLeads:trigger.new)


         //AllLeads.adderror('Oops!!! All routing numbers must go to real banks');


My requirement is whenever a field on Lead called State(Picklist field) has any value, if it gets saved then a Territory field should be auto populated(Value should be saved automatically for example State=Gujrat then Territory=India). I have a custom settings called Country_List and there is a field called Country__c. Inside Country I have defined States and it's country. How can i achieve this, Please help me.Thanks in advance
Here is the apex and VF code:
//Apex Code

 public class sendEmailbuttonApex
    public Account accounts            {set;get;}
    public String subject { get; set; }
    public String body { get; set; }
    public sendEmailbuttonApex(Apexpages.StandardController controller)
    public PageReference sendEmail()
        List<Contact> conList=[Select Id, Email from contact where Email='abhishekk.twopirconsulting@gmail.com'];
        List<String> mail=new List<String>();
        for(Contact c:conList)
        Messaging.SingleEmailMessage msg1=new Messaging.SingleEmailMessage();
        Messaging.Email[] emails=new Messaging.Email[]{msg1};
        PageReference p=new PageReference('/'+accounts.id);
        return p;

//VF code

<apex:page docType="HTML-5.0" standardController="Account" extensions="sendEmailbuttonApex">
      <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
        $(document).ready(function() {
            $("#word_count").on('keydown', function(e) {
            //j$('[id$=word_count]').on('keydown', function(e) {
        var words = $.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
        if (words <= 200) {
            if (e.which !== 8) e.preventDefault();
		<br /><br />
			<apex:outputLabel value="Subject" for="Subject"/>:<br />     
			<apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
			<br /><br />
			<apex:outputLabel value="Body" for="word_count"/>:<br />     
             <apex:inputTextarea id="word_count" cols="30" rows="10" value="{!body}"/>
        <br />
Total word Count : <span id="display_count">0</span> words. Words left : <span id="word_left">200</span>

			<br /><br /><br />
        <apex:commandButton value="Send Email" action="{!sendEmail}" /> 

Public Class Customer_Controller{
    ApexPages.StandardController controller;
     @TestVisible private final Case thisCase;

    public Customer_Controller(ApexPages.StandardController controller) {
        this.controller = controller;
        this.thisCase = (Case)controller.getRecord();
    public Boolean isTScase {
        get {
            return (((String)thisCase.RecordTypeId).left(15) == Label.Caseod_RecordType);
    public Boolean isCScase {
        get {
            return (((String)thisCase.RecordTypeId).left(15) == Label.Casenew_recordtype);

error : Compile Error: Variable is not visible:
Hi Guys,

How to achive this:  Fetch the Email template and show in dropdown in Lightning Component

I am a beginner in salesforce lightning and trying to create few components.
Can someone explain to me
1) what is the difference between 'id' and 'aura:id' attribute?
2) when to use component.get() and component.find() ?

User-added image
Hi All, 
on click of the checkbox by the user need the total to be displayed like below DYNAMICALLY. if i unselect the checkbox the sum needs to get reduced from the actual. for example: if i select two checkboxes above the sum of cost_price__c = 30 . if user select one more need to add to the total , if user unselect the checkbox it should reduce to the total.

I need to display the values below . Any help is highly appreciated
Total cost_price__c = 
Total market_price__c = 
Can you please let me know if Notes and Attachments be customized , out of the box ?
I am the beginner in salesforce.
Please help me.
What is trigger execution?
I try to use overlayLibrary for popover action.
Get the error message below, can anyone help?
"Cannot read property 'la' of undefined"
<aura:component >    
    <lightning:overlayLibrary aura:id="overlayLib"/>
    <lightning:button name="popover" label="Show Popover" onclick="{!c.handleShowPopover}"/>    
    <div class="mypopover" onmouseover="{!c.handleShowPopover}">Popover should display if you hover over here.</div>

// Controller
    handleShowPopover : function(component, event, helper) {
            body: "Popovers are positioned relative to a reference element",
            referenceSelector: ".mypopover",
            cssClass: "popoverclass"
        }).then(function (overlay) {
                //close the popover after 3 seconds
            }, 3000);

// app
<aura:application >
    <c:Popover_OneStop />



I've got a lightning component that is being used in a Community.
This is meant to be a public facing community/component, where anonymous users essentially fill out a form.

Part of the flow includes uploading files.
Currently the files are being uploaded using <lightning:fileUpload/> and are being associated with an Account object.

When used by a person who already has a logged in session (such as through the builder) it works fine. However a guest user isn't able to upload files.

Is there any way to set the auto generated guest user or guest profile to be able to upload files?
I've tried doing some research on this already, and it seems like its more pointing towards no, but I was hoping if anyone else could provide insight.


 - is there something I have not activated perhaps? In this case I do not see "Get more contacts button" as outlined in the module 'Use Accounts and Contacts' 
Salesforce will be ending support for Legacy SOAP API version 6 and lower.  I'm trying to confirm what SOAP version our app is using for the Outbound messages.  I tried to following the instructions given by the email by going into Workbench, exporting the EventLogFile and looking for API_Type.  However, I don't see that field. 

When I export via the Data Loader or the Salesforce Event Log File Browser, I don't see that field but do see something called API version.  Is that what I'm looking for?
I want to send an email to the persons whoever is selected in the picklist .
Ex: if ABC is selected in the picklist field ,the mail should go to ABC...@....com.
    if XYZ  is selected in the picklist field ,the mail should go to XYZ...@....com, they are not the Users
How can i do that using workflow or Process Builder?
I have a requirement that ananymous user who doesn't requre login to access a page, fills the details, saves to an object (custom, and it has lookup field  to contact) . For this I have done the below steps
  • Added Domain
  • Created new Site
  • Assigned the created VF page in to the list 'Site Visualforce Pages'
  • Activated the site
  • Gave perrmissions (RWA) to the custom object
But when I click on the page I got the following error
Authorization Required

You must first log in or register before accessing this page.
If you have forgotten your password, click Forgot Password to reset it.
We should directly access to the page without authorize, how can we do this?