• Amit Chaudhary 8
  • ALL STAR
  • 41302 Points
  • Member since 2014
  • Salesforce CRM Consultant


  • Chatter
    Feed
  • 1213
    Best Answers
  • 1
    Likes Received
  • 32
    Likes Given
  • 3
    Questions
  • 5845
    Replies
Hi There,

I've created a visualforce page based on a custom object and an extension which enables this to be opened from the account screen. 

Whenever I click "Save", I am redirected back to the account I invoked the visualforce page, however the record I created on the visualforce doesn't appear to be saving. 

 VF page:
<apex:page StandardController="Account" extensions="accountProp" sidebar="false">
    <apex:sectionHeader title="Edit AccountProperty" />
    <apex:form >
        <apex:pageBlock title="Edit AccountProperty" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Property Information" columns="1">
                    
                    <apex:pageBlockSectionItem >                       
                        <apex:outputLabel value="Property_Name__c"/>
                        <apex:outputPanel >                            
                            <apex:inputField value="{!objB.Property_Name__c}">
                                <apex:actionSupport event="onchange" rerender="thePageBlock"
                                                    status="status"/>
                            </apex:inputField>
                            <apex:actionStatus startText="applying value..." id="status"/>
                        </apex:outputPanel>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>
            </apex:actionRegion>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'Sunrise ID'}">
                <apex:inputField value="{!ObjB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.Sunrise_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'SVU Site ID'}">
                <apex:inputField value="{!objB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.SVU_SITE_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:

public with sharing class accountProperty {
    
    ApexPages.StandardController sc;
    public Account_Property__c objB {get; set;}
    
    public accountProperty(ApexPages.StandardController sc)
    {
        this.sc = sc;
        objB = new Account_Property__c();
    }
    
    public ApexPages.PageReference SaveBoth()
    {
        insert objB;
        return sc.Save();
    }

}
I want output or not output some tag in visualforce page.
How can use if else?
ex:
<apex:repeat value="{!MapProducts[ikey]}" var="item">
                              {!if(item.id==0)}
                               <div class="columnnull">
                                   
                                </div> 
                              {!else}
                              <div class="column">                           
                                  <div class="zoomimage"> 
                                 </div>
                              </div>

 
How to write Test Class for dependent picklist methods?
  
 @AuraEnabled
    public static List<String> getDepStates(String objectType, String parentField, String childField,String search){    
        List<String> optionStates = new List<String>();
        PicklistFieldController controller = new PicklistFieldController();
        Map<String,List<String>> valueMap = PicklistFieldController.getDependentOptionsImpl(objectType,parentField,childField);
        for(String contr : valueMap.keySet()){
           // System.debug('CONTROLLING FIELD : ' + contr);
            //System.debug('DEPENDENT VALUES ...  : ' + valueMap.get(contr));
            if(search==contr){
                optionStates=valueMap.get(contr);
            }
        }
        return optionStates;
    }
    @AuraEnabled
    public static List<String> getPickList(String field,String objectName){    
        List<String> lstPickvals=new List<String>();
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
        Sobject Object_name = targetType.newSObject();
        Schema.sObjectType sobject_type = Object_name.getSObjectType(); 
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); 
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); 
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field).getDescribe().getPickListValues(); 
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
            lstPickvals.add(a.getValue());//add the value  to our final list
        }        
        return lstPickvals;
    }
   
}
I am changing one particular  field by checking lastmodifeddate in my code.All works fine but i am struck with test class.I am chnaging multiple records from multiple objects so my batch class looks like below.
 
global class editrecords implements Database.Batchable<string>, Schedulable{
global boolean bool = false;

global Iterable<string> start(Database.BatchableContext ctx) {
    return new list<String> { 'CO__c', 'CO2__c', 'CO3__c','CO4__c'};
}
global void execute(Database.BatchableContext ctx, list<string> listObj) {
    list<sObject> editrecords = new list<sObject>();
    for(string strObjName : listObj) {
        for(sObject objsObject : database.query('Select Id from ' + strObjName + ' where LastModifiedDate < LAST_N_DAYS:36')) {
                editrecords.add(objsObject);
            else {
                b = true;
                break;
            }
        }
    }
    update editrecords;
}
global void finish(Database.BatchableContext ctx) {

}        global void execute(SchedulableContext sc){
         Database.executebatch(new editrecords ());    
    }
}

my test class is as below which get 58% of coverage.How can i get lastmodified date and cover rest of code.please help.
 
@isTest
Public class testeditrecords{

    static testMethod void testMethod1(){

        CO__c CO =new CO__c(Name='testdata');
        insert CO;
        CO2__c co2 =new 
  co2__c(Name='testdata');
        insert co2;
        Co3__c co3 =new Co3__c(Name='test2');
        insert co3;

       for(CO__c c:[Select ID from CO__c where createddate=TODAY]){
        Test.startTest();
       
        editrecords obj = new editrecords();
        Database.executeBatch(obj);
        Test.stopTest();       
        }
   } 
}

 
Hello,

The business requirement is to have a lookup relation ship between a Contract and Opportunity. A field on the opportunity must get the SUM of a custom field on the Contracts which belong to the opportunity. I use the @future annotation to increase the CPU time, however, I get an error "Attempt to de-reference a null object".

Here's the code. I got the error on line 6 where I define the Set<ID>
public class contractRollUpCLASS {
    @future
    public static void calculate() {
  
    //limit the size of list by using Sets which do not contain duplicate elements.
    Set<ID> oppIds = new Set<ID>();

    
    //when adding new or updating existing contracts.
    if(trigger.isInsert || trigger.isUpdate) {
        
        for(Contract con : (List<Contract>)trigger.new) {
        
            if(con.Is_Obsolete__c == false)
            oppIds.add(con.Renewal_Opportunity__c);
        }
    }
    
    
    //when deleting contracts.
    if(trigger.isDelete){
        
        for(Contract con : (List<Contract>)trigger.old ) {
           if(con.Is_Obsolete__c == false)
            oppIds.add(con.Renewal_Opportunity__c);
        }
    } 
    System.debug('***************NUMBER OF IDS ************** : '+ String.ValueOf(oppIds.size()));
    
    //Map will contain one Opportunity Id to one sum value.
    map<Id, Double> OpportunityMap = new Map<Id,Double>();
    
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
    //aggregate result.
    for(AggregateResult q : [SELECT Renewal_Opportunity__c, SUM(Latest_PD_Renewal_Amount__c) sumLatest FROM Contract WHERE Renewal_Opportunity__c IN : oppIds AND Latest_PD_Renewal_Amount__c != null GROUP BY Renewal_Opportunity__c]) {
        OpportunityMap.put((Id)q.get('Renewal_Opportunity__c'),(Double)q.get('sumLatest'));
    }
    
    for(Opportunity opp : [SELECT Id, Annual_Maintenance_Value__c FROM Opportunity WHERE Id IN : oppIds]) {

        Double sumLatestPD = OpportunityMap.get(opp.Id);
        opp.Annual_Maintenance_Value__c = sumLatestPD;
        oppsToUpdate.add(opp);     
    }    
    update oppsToUpdate;   
    
}
}

Any help would be much appreciated.
Angel
 
@RestResource(urlMapping='/Merchandise/*')
global with sharing class MerchandiseResource {

private class Attach {
    String Body;
    String ContentType;
    String Name;
}
private class Merchandise {
    Merchandise__c merchandise;
    list<Attach> attachments;
} 

@HttpPost
global static String doPost() {
    //json will be taken directly from RestContext
    Merchandise container = (Merchandise)System.JSON.deserialize(
        RestContext.request.requestBody.tostring(), 
        Merchandise.class);

    Merchandise__c merch = container.merchandise;
    insert merch;

    list<attachment> attachmentToInsert = new list<attachment>();

    for (Attach att :container.attachments) {
        attachmentToInsert.add(
            new Attachment(parentId = merch.Id, name = att.name, 
                           ContentType = att.ContentType, 
                           Body = EncodingUtil.base64Decode(att.body)));
    }
    insert attachmentToInsert;

    return merch.id;
}}

Can anyone suggest me a test class for this above code.
I send the following json.
 
{
    "merchandise": {
        "Name": "Eraser"
    },
    "attachments": [{
        "Body": "d29ybGQ=",
        "ContentType": "text/plain",
        "Name": "hello.txt"
    }, {
        "Body": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY3growIAAycBLhVrvukAAAAASUVORK5CYII=",
        "ContentType": "image/png",
        "Name": "picture.png"
    }]
}


I also tried the below test class,
 
@isTest
public class TesMerchandiseResource 
 {
    
     private Static testMethod void testFunction()
     {


System.RestContext.request = new RestRequest();
        System.RestContext.response = new RestResponse();
        RestContext.request.requestBody =blob.valueof('{}');

		
		 Account accountDetails = new Account();
        accountDetails.name = 'test name';
        upsert accountDetails;
		
 Attachment attachIt = new Attachment();
        attachIt.Name = 'test_attch';
        attachIt.ParentId = accountDetails.id;
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
      attachIt.body=bodyBlob;
	  
	   RestContext.request.requestBody =blob.valueof('{     "merchandise": {         "Name": "Eraser"     },     "attachments": [{         "Body": "d29ybGQ=",         "ContentType": "text/plain",         "Name": "hello.txt"     }, {         "Body": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY3growIAAycBLhVrvukAAAAASUVORK5CYII=",         "ContentType": "image/png",         "Name": "picture.png"     }] }');
        MerchandiseResource .doPost();

}

}

Still I get error "Attempt to de-reference a null object" in the line ​"for (Attach att :container.attachments) {"

Thanks in Advance,
Leafen.
 
From child-Parent soql
----------------------------
Parent = college
child =student(lookup with parent)
relation =Students

written query as

for(Student__c s:[select Name,college__r.Name,CollegeName__c from student__c])
{
  system.debug('student Name:'+s.Name+'     college Name:'+s.college__r.Name);
}

but error as

Line: 3, Column: 18
select Name,college__r.Name,CollegeName__c from ^ ERROR at Row:1:Column:13 Didn't understand relationship 'college__r'
Hello, 

I created this trigger which set a share type for each new content document link. 
trigger ContentDocumentLinkTrigger on ContentDocumentLink (before insert) {
    
    for(ContentDocumentLink cdl: Trigger.new){
        cdl.shareType = 'I';
    } 
}
I tried to create this test class:
@isTest
public class ContentDocumentLinkTriggerTest {
    
    @isTest static void ContentDocumentLinkTriggerTest() {
        
        // Create a ContentVersion
        ContentVersion ContentDoc = new ContentVersion();
        ContentDoc.Title = 'My Doc';
        ContentDoc.ContentUrl= 'test.com';
        Insert ContentDoc;
        
        // Create a ContentDocumentLink
        ContentDocumentLink ContentDL = new ContentDocumentLink();
        ContentDL.ContentDocumentId = ContentDoc.Id;
        Insert ContentDL;
        
        // Verify the share type is = i
        System.assertEquals(ContentDL.ShareType,'I');
        
        
    }
}

But I receive this error: 
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, ContentDocument ID: id value of incorrect type: 0683E0000003EXVQA2: [ContentDocumentId]

Any idea why ? 
Hi  All,

Am getting code coverage error for my test class? Can anyone help me to get code coverage?

Trigger : 
trigger taskRestriction on task (Before insert,After update,Before Update) {
  
    list<Contact> clist =new list<Contact>();
    
    String userid=UserInfo.getUserId();
    
    String ProfileID=userinfo.getProfileId();
  
  
    
        for (Task t : Trigger.new) {
       
        if (t.WhoId !=Null  && userinfo.getProfileId()=='00e90000000O4VsAAK' )
        {
                
          clist= [select ID, ownerId ,Account_name__C, Account.Lock_record__C from Contact where 
          ID=:t.WhoId and Account.Lock_record__C!=True and  OwnerId !=:UserInfo.getUserId()]; 
                
            }
            
            IF(Clist.size()>0)
            {
            T.adderror('This contact is assigned to other user, Kindly Contact Sir/Madam to Change the Ownership');
            }
            }                   
}

Test Class:

@isTest

public class TaskBlockedTest
{
    @isTest
    public static void testLeadInsert ()
    
    {
             Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
            
            Lead objLead = new Lead (LastName='Test2Dup',E_Mail_Additional__c='test3@duptest.com', Email='test2@duptest.com',LeadSource='Click India',
       MobilePhone='7452638196',Whatsapp_Mobile__c='7452638194' ,Mobile_Additional__c='7452638193' ,Phone='7452638192',
       Phone_Additional__c='7452638191', Status='Open',Customer_Type__c='Shop',Company='Test',Date__c= Date.newInstance(2018, 03, 23));
        
            insert objLead; 
            
            Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
           insert a; 
           
           Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
    
     System.runAs(u) 
        { 
            Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             Insert testTTask;
             
             
        Test.startTest();
        testTTask= new task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
        ownerid=con.ownerid);
        Database.SaveResult result = Database.insert(testTTask, false);
           Test.stopTest();
           }
        
    }
    
    @isTest
    public static void testLeadUpdate ()
    {
        
             Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
            
                Lead objLead = new Lead (LastName='Test2Dup',E_Mail_Additional__c='test3@duptest.com', Email='test2@duptest.com',LeadSource='Click India',
            MobilePhone='7452638196',Whatsapp_Mobile__c='7452638194' ,Mobile_Additional__c='7452638193' ,Phone='7452638192',
           Phone_Additional__c='7452638191', Status='Open',Customer_Type__c='Shop',Company='Test',Date__c= Date.newInstance(2018, 03, 23));
        
            insert objLead; 
            Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
           insert a; 
           
           Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
         
           
           
        System.runAs(u) 
        { 
    
            Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             Insert testTTask;
             
               List<Account> listact=New List<Account>{[select OwnerID from Account Where ownerID=:u.ID ]};
             
         List<task> taskstoupdate = New List<task>{[select Time_New__c, Task.Account.Name from Task where  ownerId =:u.id limit 1]};
             
              Task testTTask2= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             
             Insert testTTask2;
             
             Task tk =[select Subject from Task where ID=:testTTask2.ID];
             
             tk.Subject ='Test';
             
             
             Update tk;
               
       
              
            
   
        
        }
         
        
       
    }
}
 
Hi Everyone, 

I have writen a short apex code to be able display a couple of fields from Salesforce however, I now have to write a test class, 

So it would be great if someone could please assist me :)  

This is my short apex code that I have:
public with sharing class AccountController {
    @AuraEnabled
    public static List<Account> findAll() {
    return [SELECT id, name, Location__Latitude__s, Location__Longitude__s, Industry
            FROM Account
            WHERE Location__Latitude__s != NULL AND Location__Longitude__s != NULL
            LIMIT 50];
    }
    
}

 
I have a vf page with 2 picklists.
I need the second picklist to update when the first one changes. Rather than using selectOption for the second picklist I want to pass through the field name to rerender so that I can update the values without having to update the controller.
 
For this I though about using the following:
<apex:column headerValue="Picklist1">
                <apex:selectList value="{!Picklist1}" multiselect="false" size="1">
                <apex:selectOption itemValue="a" itemLabel="a"/>
                <apex:selectOption itemValue="b" itemLabel="b"/>
                <apex:selectOption itemValue="c" itemLabel="c"/>
                <apex:actionSupport event="onchange" reRender="b"/>
                </apex:selectList>
                </apex:column>

                <apex:column headerValue="Picklist2">
                <apex:inputField value="{!Picklist2}" id="b"></apex:inputField>
                </apex:column>
Public String Picklist1{get;set;}
Public String Picklist2 {get;set;}

  {
        if(Picklist1 == 'a'){
            Picklist2 = 'del.a__c';
        } else if (Picklist1 == 'b'){
            Picklist2 = 'del.b__c';
        }else if (Picklist1 == 'c'){
            Picklist2 = 'del.c__c';
        }else {
            Picklist2 = null;
        }
    }

I have 3 picklist fields (a,b & c) on the custom object (del) but I want picklist1 to select which picklist (a,b or c) depending.

Hope this makes sense.

 
public class Handeller
{
    List<ID> tempAccList = new List<ID>();
     List<Account> aList = new List<Account>();
      List<Customer__c> cList = new List<Customer__c>(); 
      List<Account> aList1 = new List<Account>();
      
      public void getAccountId (List<Account> accList)
      {
          for (Account acc: accList)
          {
              tempAccList.add(acc.Id);
          }    
          if(!tempAccList.isEmpty())
          {
              createCustomer();
          }
       }
       
        public void createCustomer()
        {
          aList =[SELECT Id,Name,Phone,Role_of_the_main_contact__c FROM account WHERE Id IN:tempAcclist];
          for (Account acc1: aList)
          {
              Customer__c cust = new Customer__c();
              cust.Name = acc1.Name;
              cust.Phone__c= acc1.Phone;
              cust.Role_of_the_contact__c=acc1.Role_of_the_main_contact__c;
              cust.Related_Account__c=acc1.ID;
              cList.add(cust);
              
              acc1.Phone=null;
              acc1.Role_of_the_main_contact__c=null;
              aList1.add(acc1);
          }
          
          insert cList;
          update aList1;
          
        } 
}
public class AnimalsCallouts {
    public static HttpResponse makeGetCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
            // Deserializes the JSON string into collections of primitive data types.
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'animals' key as a list
            List<Object> animals = (List<Object>) results.get('animals');
            System.debug('Received the following animals:');
            for (Object animal: animals) {
                System.debug(animal);
            }
        }
        return response;
    }
    public static HttpResponse makePostCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody('{"name":"mighty moose"}');
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
        return response;
    }        
}
HOW TO CREATE A VISUALFORCE PAGE FOR THIS APEX CLASS??? WITH TWO BUTTONS OF POST AND GET????
THANKS >>>
 
trigger AssignToFirstOwnerForDuplicteLeads on Lead (before insert, before update) {
    set <string> newEmaiSet = new set<string>();
    set<string> newPhNumSet = new set<string>();
    for(lead l1: trigger.new) {
        if(l1.Email != null) {
            newEmaiSet.add(l1.Email);
        }
        if(l1.phone != null) {
            newPhNumSet.add(l1.phone);
        }
    }
    List<lead> leadWithMatchingEmail = [select id, email, OwnerId from lead where email in :newEmaiSet];
    List<lead> leadWithMatchingPhone = [select id, phone, OwnerId from lead where email in :newPhNumSet];
    Map<string, id> emailVSId = new Map<string, id>();
    Map<string, id> phoneVSId = new Map<string, id>();
    for(lead l1: leadWithMatchingEmail) {
        emailVSId.put(l1.Email, l1.OwnerId);
    }
    for(lead l1: leadWithMatchingPhone) {
        phoneVSId.put(l1.phone, l1.OwnerId);
    }
    for(lead l1: trigger.new) {
        if(emailVSId.containsKey(l1.Email)) {
            l1.OwnerId = emailVSId.get((l1.Email));
        }
      //  if(phoneVSId.containsKey(l1.phone)) {
      //      l1.OwnerId = phoneVSId.get((l1.phone));
     //   }
        system.debug('l1::@@'+l1);
    }
    
}

Thanks in advance
Hi,
i'm doing trailhead challenge on Automate Simple Business Processes with Process Builder, and i got an error that said "There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Web Site must have an extension of .com, .org, or .net.: [Website]"

do you know how can i fix it ?

this is the step of the challenge =
The process can have any name
The process must have an Update Records action that updates Contact mailing address fields (Street, City, State, Postal Code, Country) when the parent Account shipping address field values are updated
The process must be active

NOTE: To complete this challenge, you may have to deactivate the validation rule for the Contacts object (created from a previous challenge).

and my work =
User-added image
User-added image
Hello guys, 
i created a controller with following methodes. I have 96% code coverage and want to deploy my controller..

- m1 - returns a list of a wrapper class object1
- m2 - returns a list of a wrapper class object2
- m3 - creates records with values releated to m1 & m2 

So, i have created for each methode more test methodes in my test class.

for m1: 
- positive -- the list returns some records
- null - the list doesen't return some recrods
- bulk - the list shows 100 records 

for m2: 
- positive -- the list returns some records
- null - the list doesen't return some recrods
- bulk - the list shows 100 records 

for m3:
- positiv - the methode creates one record
- Null - the methode creates no record
- bulk - the methode creates 100 records

i have checked each methode with system.assertEquals.

Now, my question(s).
- is this a good strategy for my test class ?
- i have created new test data for each test methode --- is this necessary ? 
- my test class has more than 300 lines -- is this too much ? 

thanks for your time. I really want to learn how to write good test classes.


Sandra 



 
I am getting myself confused here - I have built the App and my hotels are displaying on the Google map which is fab, but I now want to transfer it into Production and I appreciate that I need to test the Controller.

Am I testing that I can create a new record in my custom object?

OR

Am I testing that a new visualforce page is created
Kindly let me know, how to write a test class for this Apex class. I wrote a test class but it's not covering code coverage

public class AggregateTasklist{
public List<AggregateResult> Result {get;set;} 
List<Account> ListAct= New List<Account>();
 
public List<AddWrapperField> wraplist{get;set;}
 
    public AggregateTasklist(ApexPages.StandardController controller) {       
        
    }
    
    public void GetRecords(){
    
        String userid=UserInfo.getUserId();
        
        ListAct=[select ID,ownerId from Account where ownerId =:userid];
        
        If(ListAct.size()>0) {
        For(Account act:ListAct) {   
        wraplist=new List<AddWrapperField>();        
        Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task where  ownerId =:userid and Time_New__c!=Null 
        group By Task.Account.Name Having Max(Time_New__c)<LAST_N_DAYS:110]; 
          }
       }      
       for(AggregateResult res:Result){          
       wraplist.add(new AddWrapperField(Res));    
       }   
    }

    public class AddWrapperField{
       public Date LastDueDate{get;set;}
       public String Name {get;set;}
       
       AddWrapperField(AggregateResult res){
         this.LastDueDate=(Date)res.get('LastDueDate');
         this.Name =(String)res.get('Name');
         
       }
     }
     
    }


My Test Class:

@isTest(SeeAllData=false) class AggregateResultTest {
    @isTest static void test() {
    
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
            
             
            Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
           insert a; 
           
           Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
    
     System.runAs(u) 
        { 
            Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             Insert testTTask;
             
             
        Test.startTest();
        testTTask= new task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
        ownerid=con.ownerid);
        Database.SaveResult result = Database.insert(testTTask, false);
           Test.stopTest();
           }
        
    
    
    
     List<Account> listact=New List<Account>{[select OwnerID from Account Where ownerID=:u.ID ]};
    
        AggregateResult[] results = [SELECT Max(Time_New__c), WhatId  FROM Task GROUP BY WhatId ];
        
        }
      
    }
public class LPT_InterestAccrued_TriggerHandler {

    public static void updateIAonLoan(List<loan__Loan_Payment_Transaction__c> lptNewData){
        List<loan__Loan_Account__c> loanList = new List<loan__Loan_Account__c>();
        List<loan__Loan_Payment_Transaction__c> lptList = [select id, loan__Cleared__c,
                                                           loan__Loan_Account__r.loan__Loan_Status__c, 
                                                           loan__Loan_Account__r.loan__Interest_Accrued_Not_Due__c
                                                           from loan__Loan_Payment_Transaction__c where id in:lptNewData];
                                                           
                System.debug('Loan payment trsansactions list:====='+lptList);                                         
        for(loan__Loan_Payment_Transaction__c lpt: lptList){
            System.debug('Loan payment trsansactions list:====='+lpt);  
               

               if(lpt.loan__Loan_Account__r.loan__Loan_Status__c=='Closed- Written Off')
               {
                    loan__Loan_Account__c l = new loan__Loan_Account__c();
                    
                    l.id = lpt.loan__Loan_Account__c;
                    
                    System.debug('Loans:====='+l);  
                    if(lpt.loan__Loan_Account__r.loan__Interest_Accrued_Not_Due__c!=0){
                        l.loan__Interest_Accrued_Not_Due__c=0;
                        loanList.add(l);
                    System.debug('Loans list:====='+loanList);  
                    }            
                }
                
                
            } 
            
        
        try{
            update loanList;
        }
        Catch(Exception e){
            System.debug('Exception Occurred:'+e);
        }
    }
}
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
When i am posting code "" is not printing. And Some code is removing automatically. 

Any idea . It look like some issue ?
External Lookup Relationship could now be setup between external objects and Salesforce object.
External Object - They are same as custom objects but used to map to data located outside Salesforce.
External object take data from External source and External source obviously has its own DB. 
To create external object : From Setup, click Develop | External Objects.
To create external Data source : Develop | External data source
 
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
Hi All,
I've passed step one, and i'm a tad stuck on step 2 as the Apex test execution (BeAwesome) test methods both fail:
User-added image
It does not explain why these failed (as far as I an see) and I cannot seem to find any reason why. Is this a poblem with the test, or is it that I've got something wrong?
I've created the 2 extra contact fields (encrypted text), and I've obviously passed step 1, so I'm quite certain the object sharing, profiles and org-wide rules are set up correctly.
Not really looking for guidance on the answer here, I just don't understand how the Apex tests work, what their function is and the reason for the failures.
Thanks in advance.....
I have build a lightning component to list all the open cases and inserted in a page layout. But I want to hyperlink the case number, if someone clicks on that, it should take the user to the corresponding case for view/edit etc. can you pls let me know how to do this. thanks.
  • August 17, 2018
  • Like
  • 0
Hi All
How can I develop a custom page like bellow page?  Can anybody share some sample code.
User-added image
/**
* @name OrderExtension
* @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {
    
    public Order orderRecord {get;set;}
    public List<OrderItem> orderItemList {get;set;}
    public String selectedFamily {get;set;}
    public List<chartHelper.chartData> pieData {get;set;}
    public Decimal total {get;set;}
    public Map<Id,OrderItem> orderItemMap;
    ApexPages.StandardSetController standardSetController;
    public OrderExtension(ApexPages.StandardController standardController){
        orderRecord = (Order)standardController.getRecord();
        orderItemMap = new Map<id,OrderItem>();
        if ( orderRecord.Id != null ){
            orderRecord = queryOrderRecord(orderRecord.Id);
        }
        resetSsc();
        total = 0;
        for (OrderItem oi : orderRecord.OrderItems) {
            orderItemMap.put(oi.Product2Id, oi);
            if (oi.Quantity > 0) {
                if (null == pieData) {
                    pieData = new List<ChartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                total += oi.UnitPrice * oi.Quantity;
            }
        }
        PopulateOrderItems();
    }
    void resetSsc() {
        String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c'
            + '  FROM PricebookEntry WHERE IsActive = TRUE';
        if (selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
            query += ' AND Product2.Family = \'' + selectedFamily + '\'';
        }
        query += ' ORDER BY Name';
        standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
        standardSetController.setPageSize(Constants.DEFAULT_ROWS);
    }
    //ToDo: Implement your own method to populate orderItemList
    //  that you will call after pagination and/or family selection
    void PopulateOrderItems() {
        orderItemList = new List<OrderItem>();
        for (SObject obj : standardSetController.getRecords()) {
            PricebookEntry pbe = (PricebookEntry)obj;
            
            if (orderItemMap.containsKey(pbe.Product2Id)) {
                orderItemList.add(orderItemMap.get(pbe.Product2Id));
            } else {
                orderItemList.add(new OrderItem(
                    PricebookEntryId=pbe.Id,
                    Product2Id=pbe.Product2Id,
                    UnitPrice=pbe.UnitPrice,
                    Quantity=0,
                    Product2=pbe.Product2
                ));
            }
        }
    }
    /**
* @name OnFieldChange
* @description
**/
    public void OnFieldChange(){
        //ToDo: Implement logic to store the values changed on the page
        for (OrderItem oi : orderItemList) {
            orderItemMap.put(oi.Product2Id, oi);
        }
        //      and populate pieData
        pieData = null;
        total = 0;
        for (OrderItem oi : orderItemMap.values()) {
            if (oi.Quantity > 0) {
                if (null == pieData) {
                    pieData = new List<chartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                //      and populate total
                total += oi.UnitPrice * oi.Quantity;
            }
        }
    }
    /**
* @name SelectFamily
* @description
**/
    public void SelectFamily(){
        //ToDo: Implement logic to filter based on the selected product family
        resetSsc();
        PopulateOrderItems();
    }
    /**
* @name Save
* @description
**/
    public void Save(){
        //ToDo: Implement logic to save the Order and populated OrderItems
        System.Savepoint sp = Database.setSavepoint();
        try {
            if (null == orderRecord.Pricebook2Id) {
                orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
            }
            upsert orderRecord;
            List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
            List<OrderItem> orderItemsToDelete = new List<OrderItem>();
            for (OrderItem oi : orderItemList) {
                if (oi.Quantity > 0) {
                    if (null == oi.OrderId) {
                        oi.OrderId = orderRecord.Id;
                    }
                    orderItemsToUpsert.add(oi);
                } else if (oi.Id != null) {
                    orderItemsToDelete.add(oi);
                }
            }
            upsert orderItemsToUpsert;
            delete orderItemsToDelete;
        } catch (Exception e) {
            Database.rollback(sp);
            apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
        }
    }
    /**
* @name First
* @description
**/
    public void First(){
        standardSetController.first();
        PopulateOrderItems();
    }
    /**
* @name Next
* @description
**/
    public void Next(){
        standardSetController.next();
        PopulateOrderItems();
    }
    
    
    /**
* @name Previous
* @description
**/
    public void Previous(){
        standardSetController.previous();
        PopulateOrderItems();
    }
    /**
* @name Last
* @description
**/
    public void Last(){
        standardSetController.last();
        PopulateOrderItems();
    }
    /**
* @name GetHasPrevious
* @description
**/
    public Boolean GetHasPrevious(){
        return standardSetController.getHasPrevious();
    }
    
    /**
* @name GetHasNext
* @description
**/
    public Boolean GetHasNext(){
        return standardSetController.getHasNext();
    }
    
    /**
* @name GetTotalPages
* @description
**/
    public Integer GetTotalPages(){
        return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
    }
    
    /**
* @name GetPageNumber
* @description
**/
    public Integer GetPageNumber(){
        return standardSetController.getPageNumber();
    }
    
    /**
* @name GetFamilyOptions
* @description
**/
    public List<SelectOption> GetFamilyOptions() {
        List<SelectOption> options = new List<SelectOption>{
            new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)
                };
                    
                    for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
                        options.add(new SelectOption(ple.getValue(), ple.getLabel()));
                    }
        return options;
    }
    
    /**
* @name QueryOrderRecord
* @description
**/
    public static Order QueryOrderRecord(Id orderId){
        return [
            SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
            (
                SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
                Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
                FROM OrderItems
            )
            FROM Order
            WHERE Id = :orderId
        ];
    }
}
Hello Experts,
Need test class for following VF page that display a registeration form with name,roll number,gender fields. all save the result and display form in multiple language.

--------------------------VF PAGE-------------------------------
<apex:page standardController="Student__c" extensions="StudentRegFormExtension" language="{!selectedLang }"
    sidebar="false" 
>
    <apex:form >
        <apex:selectList value="{!selectedLang}" size="1">
            <apex:selectoptions value="{!listOfLang}"/>
            <apex:actionsupport event="onchange" reRender="form"/>
        </apex:selectlist>

        <apex:outputPanel id="pageMessage">
            <apex:pageMessages rendered="true" ></apex:pageMessages>
        </apex:outputPanel>

        <apex:pageblock >
                <apex:pageblocksection id="form">
                    <apex:inputfield value="{! Student__c.Name }"/>
                    <apex:inputfield value="{! Student__c.Roll_Number__c }"/>
                   
                    <apex:inputfield value="{! Student__c.Gender__c }"/>
                    <apex:inputfield value="{! Student__c.Course_Applying_For__c }"/>
                    <apex:inputfield value="{! Student__c.State__c }"/>
                    <apex:inputfield value="{! Student__c.Country__c }"/>
                </apex:pageblocksection>
                <div align="center" draggable="false" >
                       <apex:commandButton value="{!$Label.Record_Inserted}" action="{! save}" reRender="pageMessage"/>
                       </div>
        </apex:pageblock>
    </apex:form>
</apex:page>
-------------------------------------------Controller------------------------------------------


public class StudentRegFormExtension {
    
    public Boolean showMessage{get;set;}
    public String selectedLang{get;set;}
    public List<SelectOption> listOfLang {get;set;}
    public ApexPages.StandardController controller{get;set;}
  
    
    public StudentRegFormExtension(ApexPages.StandardController con) {
       controller = con;
       showMessage = false;
        listOfLang = new List<SelectOption>();
        listOfLang.add(new SelectOption('en','English'));
        listOfLang.add(new SelectOption('es','Spanish'));
        listOfLang.add(new SelectOption('fr','French'));
     if(ApexPages.currentPage().getParameters().get('Success') != null ) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,
            System.Label.Record_Inserted));
       
    }
    }
    
     public PageReference save() {

        Student__c student = (Student__c)controller.getRecord();
        PageReference pr;
        if(student.Name == null) {
             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,
                System.Label.Error_Inserting_Record));

        }else {
            controller.save();
            pr = new PageReference('/apex/StudentRegForm?Success=true');
            pr.setRedirect(true);
        }
        return pr;
    }
    
}
Hello Experts,
Need test class for following VF page that display a dependent picklist which is a customSetting. Consider all positive negative test cases

--------------------------VF PAGE-----------------------------
<apex:page controller="CountryDependentController" showHeader="true" sidebar="false">    
    <apex:pageBlock >
        <apex:form >
        <!-- actionFunction -->
            <apex:actionFunction action="{!getCountrylist}" name="rerenderCities" rerender="Cities" >
                <apex:param name="firstParam" assignTo="{!country}" value="" />
            </apex:actionFunction>
            
            <!-- SelectList-->
            Country :   <apex:selectList value="{!country}" size="1" onchange="rerenderCities(this.value)">
                            <apex:selectOptions value="{!CountryList}"></apex:selectOptions>
                        </apex:selectList> <br/> <br/>
            City :      <apex:selectList id="Cities" value="{! cities}" size="1">
                            <apex:selectOptions value="{!CityList}"></apex:selectOptions>
                        </apex:selectList>
        </apex:form>
    </apex:pageBlock>
</apex:page>

------------------------------------CONtroller--------------------------------------------------
 public class CountryDependentController {
        Map<String, Country__c> countryMap = Country__c.getall();
        public String cities{ get; set; }
        public String country{ get; set;}
    
    public List<SelectOption> getCountrylist() {
    
    /* Method will give list of countries   
     * @param: NA
     * @return: selectoption: The country which will be selected by user will be returned
     */ 
        List<SelectOption> selectoptionList = new List<SelectOption>();
        for(String country : countryMap.keySet()){
        selectoptionList.add(new selectoption(country,country));
        }
        return selectoptionList;
        }
    
    /* Method will give list of cities   
     * @param: NA
     * @return: selectoptionList: Based on selected country user can select any city related to that country.
     */     
    public List<SelectOption> getCityList() {      
    List<SelectOption> selectoptionList = new List<SelectOption>();
        if( country == null ) {
            return selectoptionList;
        } else {
    List<City__c> cityList = City__c.getAll().values();
            for(City__c city : cityList) {
                if(city.Country__c == country ) {
                    selectoptionList.add(new selectoption(city.Name, city.Name));
                } 
            }
        }
        return selectoptionList;
        }
    } 

Im having an error with my code. Not really familiar with reverse method. Need help with checking this and creating a simple test class.

this is the code that I got so far:

public class Example {
    public static void reverseWordInMyString(String str){
        List<String> str = new List<String>{''};
            List<String> reversedString = new List<String>();
        if(!str.isEmpty()){
            for (String s : str){
                reversedString.add(s.reverse());
            }
        }
        System.debug(str);
        System.debug(reversedString);        
    }    
}

Thanks in advance

Need test class for following trigger to create clone of account record after insert.

-------------trigger---------------
trigger CloneAccountTrigger on Account (after insert) {
    
    if(Trigger.isAfter){
        if(Trigger.isInsert){
        CloneAccountTriggerHandler.cloneAccountRecord(Trigger.New);
        System.debug('Trigger');
    }
    }
    
}
--------------handler-------------------
public class CloneAccountTriggerHandler {

    public static Boolean cloneRecord = true;
    public static void cloneAccountRecord(Account[] newAccount){ 
        if(cloneRecord) {
            System.debug(newAccount);
            cloneRecord = false;
            List<Account> listAccount = new List<Account>();
            for(Account account : newAccount)
            {
                Account newCloneAccount = account.clone(false);
                listAccount.add(newCloneAccount);
            }
            Database.insert(listAccount,false);
        }
    }
}
I have written apex class like this.
try 
        {
            String userId = UserInfo.getUserId();
            User userRecord = [SELECT Id, Name FROM User WHERE Id = : userId];
            String userName = userRecord.Name;
            String ttsDialog = dialog;
            Id requestId = reqId;
            String sObjName = requestId.getSObjectType().getDescribe().getName();
            
            List<tts__Message__b> ttsMessageList = new List<tts__Message__b> ();
            
            tts__Message__b ttsMessageObj = new tts__Message__b();
            ttsMessageObj.tts__To__c = toReceivers;
            ttsMessageObj.tts__From__c = fromSender;
            ttsMessageObj.tts__CreatedBy__c = userName;
            ttsMessageObj.tts__CreatedDate__c = System.now();
            ttsMessageObj.tts__Message_Body__c = ttsDialog;
            ttsMessageObj.tts__Message_ID__c = Utilities.GenerateGUID();
            ttsMessageObj.tts__ParentId__c = requestId;
            ttsMessageObj.tts__ParentObjectAPIName__c = sObjName;
            ttsMessageObj.tts__Message_Direction__c = chatType;
            ttsMessageList.add(ttsMessageObj);
            
            database.insertImmediate(ttsMessageList);
            
            
            
        }catch (Exception e) {
            system.debug('@@Exception in the insertBigObjectDialog method::'+e);
        }
Hi There,

I've created a visualforce page based on a custom object and an extension which enables this to be opened from the account screen. 

Whenever I click "Save", I am redirected back to the account I invoked the visualforce page, however the record I created on the visualforce doesn't appear to be saving. 

 VF page:
<apex:page StandardController="Account" extensions="accountProp" sidebar="false">
    <apex:sectionHeader title="Edit AccountProperty" />
    <apex:form >
        <apex:pageBlock title="Edit AccountProperty" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Property Information" columns="1">
                    
                    <apex:pageBlockSectionItem >                       
                        <apex:outputLabel value="Property_Name__c"/>
                        <apex:outputPanel >                            
                            <apex:inputField value="{!objB.Property_Name__c}">
                                <apex:actionSupport event="onchange" rerender="thePageBlock"
                                                    status="status"/>
                            </apex:inputField>
                            <apex:actionStatus startText="applying value..." id="status"/>
                        </apex:outputPanel>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>
            </apex:actionRegion>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'Sunrise ID'}">
                <apex:inputField value="{!ObjB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.Sunrise_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'SVU Site ID'}">
                <apex:inputField value="{!objB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.SVU_SITE_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:

public with sharing class accountProperty {
    
    ApexPages.StandardController sc;
    public Account_Property__c objB {get; set;}
    
    public accountProperty(ApexPages.StandardController sc)
    {
        this.sc = sc;
        objB = new Account_Property__c();
    }
    
    public ApexPages.PageReference SaveBoth()
    {
        insert objB;
        return sc.Save();
    }

}
I'm trying to write a test class for a controller with an extension, but I'm not really sure where to start. I've looked at the SF documentation, but I'm not understanding. Can anyone help me with this? Thanks!
 
public class selectWarehouse {
    private final Purchase_Requisition__c pr;
    
    public string selectedWarehouse{get;set;}
    
    public selectWarehouse(ApexPages.StandardController stdController) {
        this.pr = (Purchase_Requisition__c)stdController.getRecord();
    }
    
    public list<SelectOption> getWarehousenames() {
        List<SelectOption> options = new List<SelectOption>();
        for (Warehouse__c w : [select name from Warehouse__c order by name desc limit 100])
        {
            options.add(new SelectOption(w.name, w.name));
        }
        return options;
    } 
    
    public PageReference saveWarehouse(){
        pr.Warehouse_Text__c = selectedWarehouse;
        update pr;
        return new PageReference('/'+pr.Id);
    }
}

 
How to write Test Class for dependent picklist methods?
  
 @AuraEnabled
    public static List<String> getDepStates(String objectType, String parentField, String childField,String search){    
        List<String> optionStates = new List<String>();
        PicklistFieldController controller = new PicklistFieldController();
        Map<String,List<String>> valueMap = PicklistFieldController.getDependentOptionsImpl(objectType,parentField,childField);
        for(String contr : valueMap.keySet()){
           // System.debug('CONTROLLING FIELD : ' + contr);
            //System.debug('DEPENDENT VALUES ...  : ' + valueMap.get(contr));
            if(search==contr){
                optionStates=valueMap.get(contr);
            }
        }
        return optionStates;
    }
    @AuraEnabled
    public static List<String> getPickList(String field,String objectName){    
        List<String> lstPickvals=new List<String>();
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
        Sobject Object_name = targetType.newSObject();
        Schema.sObjectType sobject_type = Object_name.getSObjectType(); 
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); 
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); 
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field).getDescribe().getPickListValues(); 
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
            lstPickvals.add(a.getValue());//add the value  to our final list
        }        
        return lstPickvals;
    }
   
}
I was working on the Customize Your Login Process with My Domain module and I accidentally changed my domain of my Hands-On Org. Is it possible to change it back to what it was? I get an error message now when I try to launch my hands-on org. L

My former Hands On Org. URL is as follows: curious-badger-397879-dev-ed.my.salesforce.com

The domain I changed it to is: mylightsaber.dom-dev-ed.my.salesforce.com
 
NOT (ISPICKVAL( Transfer_ID__r.Transfer_Type__c , 'Store to WHS') AND (Shipping_Quantity__c > Serial_No__r.Quantity_available__c ))

I am getting ) missing in thie validation rule, Can someone help?

System.QueryException: List has more than 1 row for assignment to SObject
Class.AccountSearchUI.<init>: line 13, column 1

My VF Page

<apex:page standardController="Account" extensions="AccountSearchUI">
<head>
<title>Account Search UI</title>
<style type="text/css"> </style>
</head>

<body>
<table width="99%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
      </tr>
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
    <td bgcolor="#FFFFFF" valign="top">
        <table width="100%" border="0" align="center" cellpadding="1" cellspacing="0" class="tablemain">
            <tr><td height="1"></td></tr>
            <tr><td height="50" class="headingmain">&nbsp;Account Search UI</td></tr>
            <tr>
                <td align="center">
                  <table width="100%" border="0" cellspacing="0" cellpadding="1" class="tablemain">
                    <tr>
                      <td width="10%" height="23" class="headingsub1">Group Org Acc</td>
                      <td width="10%" height="23" class="headingsub1">Vertical</td>
                      <td width="10%" height="23" class="headingsub1">Account Name</td>
                      <td width="10%" height="23" class="headingsub1">Type</td>
                      <td width="10%" height="23" class="headingsub1">Owner Last Name</td>
                      <td width="10%" height="23" class="headingsub1">Client Rank</td>
                      <td width="10%" height="23" class="headingsub1">Account Plan</td>
                      <td width="10%" height="23" class="headingsub1">Last Modified</td>
                      <td width="10%" height="23" class="headingsub1">View Latest PDF</td>
                      <td width="10%" height="23" class="headingsub1">PDF Upload Date</td>
                    </tr>
                    <apex:repeat value="{!accPList}" var="cp">
                    <tr>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                    </tr>
                    </apex:repeat>
          </table>
        </td>
        
      </tr>
    </table></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
  </tr>
  
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>

</table>

</body>

</apex:page>

APEX Class
public with sharing class AccountSearchUI{    

    public ApexPages.StandardController stdController {get; set;}
    public Account acc {get; set;}
    public Account accPList {get; set;}
    
    public String accountName ='';
    public AccountSearchUI(ApexPages.StandardController stdController){
    this.stdController = stdController;

 accPList = [select Group_Org__c, Vertical__c, Name, Type, Client_Rank__c from Account where Top_25_Client__c = true and Client_Rank__c < 26 order by Client_Rank__c ASC limit 5];
    }
}
Can anyone help with the issue.
 
This is my code
=============
global class BatchApex implements Database.Batchable<sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id from Opportunity');
        
    }
    global void execute(Database.BatchableContext bc,List<Opportunity>scope){
        for(Opportunity o:scope){
            o.Name='sandhya';
        }
    update scope;
}
    global void finish(Database.BatchableContext bc){
            
   Messaging.SingleEmailMessage[] mail=new Messaging.SingleEmailMessage();
        String[] toAddresses=new String[] {'forcesfdcloud@gmail.com'};
            mail.setToAddresses(toAddresses);
        mail.setSubject('sending mail ');
        mail.setPlainTextBody('process completed success fully');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
      
    }
    }
I want to update my opportunities. After updating the opportunities i want to send a mail to the above mentioned address, but it shows error like" Illegal assignment from Messaging.SingleEmailMessage to List<Messaging.SingleEmailMessage>" can any one tell me how to solve this issue.
trigger CheckValidationonCaseClose on Case (after update) {     
for(Case e:Trigger.New){          
Case d=Trigger.oldMap.get(e.Id);         
if(d.Signature_Required__c==true && d.Customer_Signature_Status__c!='Completed' && e.IsClosed==true)
{  
e.adderror('Cannot Close Case');
}

its urgent
}  
Hi,

I have a rquirement to format a time which is given in HH:MM format (24-hour clock) into the user's locale. I assumed that there would be a fromat() method as the DateTime class does, but it does not exist.

Any ideas how I can do this?

Thanks
I have a Salesforce App which passed security review for the first time in the last year. This App also includes integration with external web application, due to this I also submitted a BURP scan report of the external web application. I am not sure about how Salesforce conducts periodic security review and have some queries.

As you may know, Salesforce provides periodic, point-in-time review at an interval determined by salesforce.com (typically anywhere between 6 months to 2 years).

• As per Salesforce documentation for already passed Apps, around the expiry date, Salesforce contacts partners to arrange another review. Can you guide me on how much time Salesforce gives us to prepare for Security Review?

• BURP scan and fixing the issues reported by it can take time. If I could not submit a clean BURP scan report within the time frame provided by Salesforce, Does Salesforce remove package from AppExchange?

• Salesforce charges for Security Review process for paid Apps, as one-time upfront fee, and a small subsequent annual fee. Can you guide me on how much subsequent annual fee Salesforce charges to partners? Salesforce also charges annual listing fee of $150 USD. Is that correct?

Kindly help me with this. Thanks in advance.
Hi All,

I want to disable the global search for particular users,i have disabled the chatter in chatte section,please give me suggestion how to disable the global search.
see the below screen shot where i have disabled
User-added image

see the below screen shot for what i want to disable 

User-added image

Thanks,
Surya
I'm stuck on only one unit for this module; the controlling access to fields unit:

"Two team members need to view and update Accounts, but only one should be able to see and edit the Rating field. Create one profile and one permission set with field level security to solve for this use case.The profile must be named 'Basic Account User' and result in an API name of 'Basic_Account_User'. It should use the 'Salesforce' user license type.
The permission set must be named ‘Account Rating’ and result in an API name of 'Account_Rating'."

"Challenge Not yet complete... here's what's wrong:
The 'Basic Account User' profile did not have the appropriate object and field-level security for the Account object "
  • February 02, 2016
  • Like
  • 1
Hi Jacob,

I have already completed 5 badges, but still no email for obtaining the Cloak of Adventure sweatshirt. Does it take username or email address for sending emails, as my email address and user name are different.

User-added image
Hi,

I want to send an email alert to task owner if they have any open task which due date is already passed.
I want to send it 1 day after due date and 1 week after due date.
Please suggest how I can achieve it because through workflow it is not achievable.

Regards
Emily
 view state and need a steps how can we reduce view state without help of transient
Hi,

I have executed "Run all test" to get code coverage of all apex classes. Is there way to get all apex classes code coverage with percentage copy to excel sheet. I am able to see all classes with percentage in Developer console. But not able to copy all those. Please provide some suggestion.
We are using Apex Data Loader 19.0 and cliq_process.  Using Apex Data Loader & Cliq_process, we are exporting the data into salesforce custom object. The process was working fine past 2 years and till last week. Last few days we are getting the below error.


2015-08-17 06:12:31,218 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:104) - Logging in to: https://www.salesforce.com/services/Soap/u/19.0
2015-08-17 06:12:31,233 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:989) - Beginning Partner Salesforce login ....
2015-08-17 06:12:31,249 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:998) - Salesforce login to https://www.salesforce.com/services/Soap/u/19.0/services/Soap/u/19.0 as user forceuser@<company>.com
2015-08-17 06:12:31,655 INFO  [ExportRevenue] dao.DataAccessObjectFactory getDaoInstance (DataAccessObjectFactory.java:51) - Instantiating data access object: C:\Program Files\salesforce.com\Apex Data Loader 19.0\cliq_process\ExportRevenue\write\ExportRevenue.csv of type: csvWrite
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:109) - Checking the data access object connection
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:114) - Setting field types
2015-08-17 06:12:31,766 ERROR [ExportRevenue] client.PartnerClient describeSObject (PartnerClient.java:1249) - Error while calling web service operation: describeSObject, error was: Failed to send request to https://ncst.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
    at sun.security.validator.Validator.validate(Validator.java:203)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:840)
    ... 19 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
    ... 24 more
2015-08-17 06:12:31,766 FATAL [main] process.ProcessRunner topLevelError (ProcessRunner.java:214) - Unable to run process ExportRevenue
java.lang.RuntimeException: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:139)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    ... 1 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
Exact replication steps:
1. Create a connected app
2. Add the callback URL to that connected app as the URL of a VF page. For Eg - 'https://c.eu2.visual.force.com/apex/mypage'.
3. Connect to another salesforce org of the same instance.Énter the login details ie username and password
4. Allow permission to the connected app create on your source org to access info about target org by clicking on Állow Button'
5. Instead of redirecting back to source org it redirects me to the target org and tries to open up the page mentioned in the callback url.
6. This issue is coming when my source and target org are on same instance. It works fine when source and target instances are different.
Hello,
I have some queries on release versioning and listing subsequent versions on AppExchange:
  1. Can I release and maintain 2 versions on AppExchange? In other words, if there a v1.0 that is listed on AppExchange, and we release a new version v1.1 that has passed Security Review and ready to be listed on AppExchange, does it automatically replace the v1.0 that was listed earlier? 
  2. Do the existing customer orgs get any notification of a new released version? If yes, does it automatically contain the install link? If not, what is the most preferred practice?
  3. If I deprecate an earlier version, do the customer orgs using this version get a notification to upgrade? Are they forced to upgrade?
  4. If a patch is created for a particular released version, do I have to manually inform all customer orgs using it? Or do they get automatic notifications of the same and can choose to apply the patch as needed?
Thanks in advance!
Hi,

I want to develop an "Open CTI Adapter", where can I find the documentation(API/Library) for the same?

Regards,
Rohan
Hi ,
  
 I'm trying to parse Account records to JSON string. But I'm getting unnecessary data like attributes(type,url) that is not required in String.

Can any one pls help me in how to parse the string to required format.
List<Account> accnts=[Select Name,Phone From Account];
String s=JSON.serialize(accnts);
The resulting output is in below fromat..
{
  "attributes" : {
    "type" : "Account",
    "url" : "/services/data/v34.0/sobjects/Account/00128000002trGGAAY"
  },
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}


My requirement is to generate resulting String as below JSON string format.
 
{
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}

So that I can minimize the data to to be sent the the client system.

Any help is really appreciated. Thanks in advance.

Regards,
Naveen.
I need to download Contacts Near By component for the trailhead - field sales app project but I am not able to find it on appexchange. Any idea where can I get it from?