• Shashikant Sharma
  • ALL STAR
  • 10665 Points
  • Member since 2011
  • ForceSchool ( forceschool.blogspot.in )


  • Chatter
    Feed
  • 399
    Best Answers
  • 0
    Likes Received
  • 7
    Likes Given
  • 1
    Questions
  • 2476
    Replies
This is not a how to question, but a best practice/opinion question. I have a request to update a calculation on specific child records when a field on a parent record is updated. I am hesitant to do this since then the children records will go through the entire save procedure (including a good amount of Apex code), so it would add a bit more processing to the Apex transaction. My question is, when would you go ahead with this request vs pushing back and trying to find another solution (i.e. batch update of the child records every hour/night, new business process-- after updating the parent, go and check this checkbox on the children, . . . )? In general there shouldn't be more than 5 child records per parent that need to be updated.
I have a record that currently has Status__c='Draft'
When I click the Start button, i want status to change to 'In Progress'
I have used following JS code to achieve this
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 

var p = new sforce.SObject('Product_Order__c'); 
p.id = "{!Product_Order__c.Id}"; 
p.Status__c = "In Progress"; 
result = sforce.connection.update([p]); 
location.reload(true);

But, in Apex Trigger, I want to do some complex stuff when status changes from Draft to In Progress.
In my afterUpdate event, I am hooking on 

        Product_Order__c newPO = (Product_Order__c)o;
        Product_Order__c oldPO = (Product_Order__c)o;
        system.debug(newPO.Status__c);
        system.debug(oldPO.Status__c);
        if (newPO.Status__c.equals('In Progress') && newPO.Status__c != oldPO.Status__c)
            newInProgressPO.put (newPO.Id, newPO.RecordType.Name);

However, these two User Debugs show that both old and new statuses are 'In Progress' so my Map is always empty.

Does anybody have any ideas?
When adding products to an Opportunity the list is not sorted alphabetically.  How can I update this list view to display all my product alphabetically rather than randomly as the appear below?

User-added image

This is my Apex code where it brings in the product list.

<apex:outputLabel value="Product Name" for="productName"/> <apex:selectList id="productName" value="{!PricebookEntrys}" size="1" required="true"> <apex:selectOptions value="{!items}"/> </apex:selectList>

Can anyone help sort the products alphabetically?

Thanks in advance for any assistance
I have a class that does some work but at the end it needs to call the batch apex and pass a query the problem I am having is I want the query to be only where id in MyMap. For example 
Database.executeBatch(new JsonMassImportBatch('Select id, Name from Contract where id in : ' (Map in the batch class with the ids keyset should be here),'Contract',new JsonMassImportBatch.CustomObj(holdLease,new List<String>{'Current_Rental_Rate__c','Renewal_Date__c'},holdDate)));
The end is me passing in the map for the batch call to use ie holdlease

How should i format the batch side to make this work?  
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query + LeaseMap.keySet());
    }
 
I keep getting the following error when I test the code below:
System.ListException: List index out of bounds: 0

This error occurs on lines 13, 34, 64, and 93.  It looks like the list is pulling no records and I cannot figure out why.  I have confirmed that all required fields are captured.  I referenced another article that said to use @isTest (seeAllData=true) and it is still not working.

Help would be greatly appreciated - thank you in advance!!



@isTest (seeAllData=true)
private class leadsTaskHandlerTest {

    @isTest static void testLeadsWorkflow() {

        Lead newLead = new Lead(
                        Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
                        LeadSource = 'Web', Country = 'Canada',  Email = 'something@gmail.com',
                        Status = 'Open', Lead_Type__c = 'New Car Franchise');
        insert newLead;

        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Evaluate and Assign Web Lead'];
        tasks[0].Status = 'Completed';
        update tasks[0];

        System.assert(taskCreatedForLead('Email Introduction of TradeRev to main contact person', newLead.Id));
        System.assert(taskCreatedForLead('Phone call to follow up from email of introduction', newLead.Id));
        System.assert(taskCreatedForLead('Schedule an appointment with lead; no voicemail if you don\'t connect', newLead.Id));
        System.assert(taskCreatedForLead('Attempt to contact lead to set appointment second time in the week', newLead.Id));
        System.assert(taskCreatedForLead('Any interest in TradeRev?; let\'s schedule a demo', newLead.Id));
        System.assert(taskCreatedForLead('Touch base to let them know about growth/updates of TradeRev', newLead.Id));
        System.assert(taskCreatedForLead('Are they ready to talk about TradeRev?', newLead.Id));

    }


  @isTest static void testContractWorkflow() {
        Lead newLead = new Lead(
                        Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
                        LeadSource = 'Web', Country = 'Canada',  
                        Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
        insert newLead;
        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Any questions on the Registration Forms?'];
        tasks[0].Status = 'Completed';
        update tasks[0];

        System.assert(taskCreatedForLead('Are the Registration Forms complete?', newLead.Id));
    }

    @isTest static void testDueDateEmail() {
        Lead newLead = new Lead(
                        Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
                        LeadSource = 'Web', Country = 'Canada', Email = 'something@gmail.com', 
                        Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
        insert newLead;
        Task newTask = new Task(    Priority = 'Normal', 
                                        Status = 'Not Started',
                                        ActivityDate = Date.today(), 
                                        WhoId = newLead.Id); 
        insert newTask;
        update newTask;
    }


    @isTest static void testFranchiseDealerWorkflow() {

        Account newAccount = new Account(
                        Name = 'Test Franchise Dealer',
                        AccountSource = 'Web',
                        Account_Type__c = 'New Car Franchise');
        insert newAccount;

        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training Franchise'];
        tasks[0].Status = 'Completed';
        update tasks[0];


        System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
        System.assert(taskCreatedForAccount('Launch Cars; Walk back lot and try identify more cars they can load', newAccount.Id));        
        System.assert(taskCreatedForAccount('Has buyer been in touch to make arrangements for payment/pickup?', newAccount.Id));
        System.assert(taskCreatedForAccount('Has buyer taken car? Mark car delivered', newAccount.Id));
        System.assert(taskCreatedForAccount('Use TradeRev for the Live Appraisals', newAccount.Id));    
        System.assert(taskCreatedForAccount('Any other cars to launch?', newAccount.Id));
        System.assert(taskCreatedForAccount('Reminder to buy cars on TradeRev', newAccount.Id));

        System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
        System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
        //System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));
        //System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
        //System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));

    }

    @isTest static void testIndepedentDealerWorkflow() {

        Account newAccount = new Account(
                        Name = 'Test Independent Dealer',
                        AccountSource = 'Web',
                        Account_Type__c = 'Independent Dealer');
        insert newAccount;

        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training'];
        tasks[0].Status = 'Completed';
        update tasks[0];


        System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
        System.assert(taskCreatedForAccount('Any questions on bidding?', newAccount.Id));        
        System.assert(taskCreatedForAccount('Have they been bidding? Any cars in pending?', newAccount.Id));
        System.assert(taskCreatedForAccount('Won any cars? Discuss timing expectations for payment and pickup', newAccount.Id));
        System.assert(taskCreatedForAccount('If a car has been won; have they paid and picked up car yet?', newAccount.Id));    
        System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
        System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));
        System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));

    }



    static boolean taskCreatedForLead(String subject, Id id) {
        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :id AND Subject = :subject];
        if (tasks.size() > 0) {
            tasks[0].Status = 'Completed';
            update tasks[0];
            return true;
        }
        else {
            return false;
        }
    }

    static boolean taskCreatedForAccount(String subject, Id id) {
        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :id AND Subject = :subject];
        if (tasks.size() > 0) {
            tasks[0].Status = 'Completed';
            update tasks[0];
            return true;
        }
        else {
            return false;
        }
    }
    
    
}
Hi Expert,

I am using a test class for coverage 75% code, but few things are not covered. Can any one suggest what is going wrong.

this my test Class: --
@isTest
public class TestProfessorSelectCourse {
    @isTest static void ProfessorCourse(){
       
        
        Professor__c prof = new Professor__c(Name ='JP',Email__c='jp@gmail.com');
        insert prof;
        
        Class__c cls = new Class__c(name='12G', Class_Teacher__c = prof.id);
        insert cls;
        
        Course__c cors = new Course__c(Professor__c=prof.id,Class__c =cls.id, name='Ruby', Start_Date__c= Date.today() , End_date__c= Date.newInstance(2017,03,20));
       	//Professor__c prof = new Professor__c(Name ='JP');
        //cors.Professor__c = prof.Name;
        insert cors;
    }
}

and below is my main class


User-added image

Thanks 
Mukesh
I am trying to build a simple page to display the Opportunity and associated Line Items. I am getting this error which doesn't make sense because I am including OpportunityId in the OLI query. 

My extension:
public class PrintContract {
    
    private final Opportunity opp;

    public PrintContract(ApexPages.StandardController stdController) {
            stdController.addFields(new String[]{
            'Id',
            'LinkContacttoOpportunity__c',
            'Name',
            'CloseDate',
            'Contract__c',
            'Type',
            'Age__c',
            'Amount',
            'EXW_Expiration_Date__c',
            'EXW_Effective_Date__c'
        });    
        
        //    get current opportunity record
        this.opp = (Opportunity)stdController.getRecord();
    }
        public List<OpportunityLineItem> oli {get;set;}

        public void olis(){
        oli = new List<OpportunityLineItem>([SELECT Id, TotalPrice, Class__c, ServiceDate, OpportunityId, Quantity, Contract__c, Is_Accessory__c, Serial_Number__c
                    FROM OpportunityLineItem 
                       WHERE OpportunityId = :opp.ID]);
           }
}

My Page:
<apex:page standardController="Opportunity" extensions="PrintContract" action="{!olis}">
    <apex:pageBlock rendered="{!Opportunity.HasOpportunityLineItem = TRUE}">
        <apex:pageBlockTable value="{!oli}" var="ol">
            <apex:column headerValue="Plan Number" value="{!ol.Contract__c}" />
            <apex:column headerValue="Serial Number" value="{!ol.Serial_Number__c}" />
            <apex:column headerValue="Purchase Date" value="{!ol.ServiceDate}" />
            <apex:column headerValue="Plan Type" value="{!ol.Opportunity.Type}" />
            <apex:column headerValue="Plan Effective Date" value="{!ol.Opportunity.EXW_Effective_Date__c}" />
            <apex:column headerValue="Plan Expiration Date" value="{!ol.Opportunity.EXW_Expiration_Date__c}" />
            <apex:column headerValue="Plan Cost" value="{!ol.TotalPrice}" />

        </apex:pageBlockTable>
    
    </apex:pageBlock>
</apex:page>
We use a custom Sales Order object where sales orders can be created directly from Accounts or from Opportunities on the Accounts. I need to place a validation rule on our Opportunity object based on whether or not a sales order has been created. When I try to create a roll-up summary custom field, the Sales Order (related list object) is not an option to select in the Summarized Object picklist. How can I make the sales order display in the picklist? Or, is there another way to determine if a sales order has been created from the opportunity?
Hello there,

I'm still pretty new to code development and I am using the following trigger and class.

Trigger:
trigger AccountTerritoryTag on Account (before insert, before update)
{
    Set<String> setName =  new Set<String>();
    for (Account account : Trigger.new)
    {       
        if (account.RunAssignment__c == TRUE)
        {
            setName.add(account.RoutingKey__c);
        }   
    }   
    
    if(setName.size() > 0 )
    {
        List<RoutingKey__c> routingkey = [select Name,Territory__c from RoutingKey__c  where Name in :setName ];
        Map<String, RoutingKey__c> mapNameWiseR = new  Map<String, RoutingKey__c> ();
        for(RoutingKey__c  RK : routingkey )
        {
            mapNameWiseR.put(RK.Name , RK);
        }

        for (Account account : Trigger.new)
        {    
          if (account.RunAssignment__c == TRUE)
          {
              if (mapNameWiseR.containsKey(account.RoutingKey__c) )
              {   
                    RoutingKey__c rk = mapNameWiseR.get(account.RoutingKey__c);
                  //assign the territory 
                    account.Territory__c = rk.Territory__c;
                    account.RunAssignment__c = FALSE;
             
              }
           }
        }
        
    }
        
}


Test Class:
@isTest

private class AccountTerritoryTest
{
    static testMethod void AccountTerritoryTest()
    { 
       Territory__c t = new Territory__c();
       t.Name = 'TerritoryTest';
       insert t;
       
       RoutingKey__c k = new RoutingKey__c();
       k.Name = 'NAM|SMB|FL';
       k.Territory__c = t.id;
       insert k;
       
       Account a = new Account();
       a.Name  = 'Test';
       a.OverrideCountry__c = 'US';
       a.OverrideEmployees__c = 'A) 1-100';
       a.OverrideState__c = 'FL';
       a.RunAssignment__c = TRUE;
       insert a;
       
       a.RunAssignment__c  =  FALSE;
       a.Territory__c = t.id;
       update a;
       
    }
    
}

I'm stuck at 72% coverage and would like to increase as much as possible. I looked at my dev console and lines 17, 18, and 27-30 are uncovered by my class. I'm not certain how to write the class to cover these lines and the account update doesn't cover it. Can someone help/explain what I can do to fix this? Thank you in advance for the help!
 
I want to deploy a package that has an apex class, test class and a process builder that calls the apex class. On the sandbox where I developed the class, the code coverage is 100%. When I tried to deploy it to another sandbox/production, it failed because it showed the code coverage to be 65%.

I believe the issue is because the process builder is inactive when it is deployed and the entire code is not covered as a result. How should I proceed with this?

I have already tried to do the following :
  • Deploy the process builder first to activate it before deploying the classes. Deploying the process builder failed.
  • Deploy the classes without the process builder; code coverage was 65%.
  • Change the test class to accommodate more cases. This was not possible as I changed the code to work with process builder and I cannot find a way to test it.
  • I ran the test code when the process builder was activated and deactivated. It showed 65% coverage when it was deactivated, and 100% coverage when it was activated, as the process builder is called when a record is inserted in the test class.
My code takes the customer email and converts it to a hash using CryptoUtil.generateHashDigest method and then saves it in the hashed email field.
 
Public static void newRecord(List<Account> listAccounts) {
    for(Account a : listAccounts) {
        Account updacc=[select id from account where id = :a.id];
        String message = String.valueof(a.get('Customer_Email__pc'));
        String hashDigest = CryptoUtil.generateHashDigest(message);
        updacc.Hashed_email__pc = HashDigest;
        update updacc;
    }
}

I had to create a clone of the account record inserted/updated in order to use process builder. Using this method, the changes are only made in the clone. If process builder is not used, the test class gets a Null value instead of the actual hash value in the Hashed_email__pc field which leads to the test failing. When process builder is used, the changes made in the clone are reflected in the actual record, and the test passes. Even if I do not have a test method calling this section of code, the test passes as the process builder covers it.

I cannot figure out a way of creating a test class where the correct values are returned when the process builder is deactivated. I have to use DML to insert the record, so that it can be cloned.

How should I test the apex class in this case?
 
Hello,

What is the difference between Created by and Owner ?
 
User-added image

Hi guyz,

In account object Master detail field is not available. Could you guyz tell me why is that? Thanks in advance
I am getting date from related object Opportunities - need to keep it in a table format (this is a large table), snipit
<td bgcolor="#BDD7E7"><strong>Close Date</strong></td>
<td bgcolor="#C9D2E2">{!CO__c.Opportunity__r.CloseDate}</td>
And it displays Tue Mar 02 00:00:00 GMT 2021
Can I make it display Mar 02 2021 ?

Similarly
<td bgcolor="#BDD7E7"><strong> Value</strong></td>
      <td colspan="3" bgcolor="#C9D2E2">${!(ROUND(CO__c.Opportunity__r.Amount,0))}</td>
displays $4502
Can I make it display $4,502 ?
(Add "," every 3 digits, no decimal)

Thanks!

 
  • April 11, 2016
  • Like
  • 0
Hi, I have created a VF page for my custom object with a search field included. The search field works fine but when I enters a null character or 1 character, I expects it to show me an error message in the VF page, ideally in .INFO style but it is showing me an expression error on another page.

User-added image

I am very new to VisualForce and Apex and would appreciate some help. I know I am miissing something out but can't seem to figure it out.

Apex Class:
public class QFSearchController {

    String searchText;
    List<Quality_Feedback__c> results;
    

    public String getSearchText() {
        return searchText;
    }

    public void setSearchText(String s) {
        searchText = s;
    }
    
    public List<Quality_Feedback__c> getResults() {
        return results;
    }

    public PageReference doSearch() {
    

if(searchText==null || searchText=='')
 { 
 Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.INFO, 'Search term must be longer than one character:')); 
 }
 
 else if (searchText.length()<2)
 {
 Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.INFO, 'Input box must contain at least two characters')); 
 }
 results = (List<Quality_Feedback__c>)[FIND :searchText RETURNING Quality_Feedback__c(Name, Type_of_Feedback__c,    
Feedback_For__c,   Reviewed_By__c, Review_Status__c, Incident__c)][0];
        return null;
    }
}

VisualForce Page:
<apex:page controller="QFSearchController"> 
 <apex:ListViews type="Quality_Feedback__c" />
   <apex:form >   
      <apex:pageBlock mode="edit" id="block">
         <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
               <apex:outputLabel for="searchText">Search Text</apex:outputLabel>
               <apex:panelGroup >
                  <apex:inputText id="searchText" value="{!searchText}"/>
                  <apex:commandButton value="Go!" action="{!doSearch}" 
                                      rerender="block" status="status"/>
               </apex:panelGroup>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
        <apex:actionStatus id="status" startText="requesting..."/>
        <apex:pageBlockSection title="Results" id="results" columns="1">
           <apex:pageBlockTable value="{!results}" var="l" 
                               rendered="{!NOT(ISNULL(results))}">
              <apex:column value="{!l.name}"/>
              <apex:column value="{!l.Type_of_Feedback__c}"/>
              <apex:column value="{!l.Feedback_For__c}"/>
              <apex:column value="{!l.Reviewed_By__c}"/>
              <apex:column value="{!l.Review_Status__c}"/>
              <apex:column value="{!l.Incident__c}"/>
           </apex:pageBlockTable>
        </apex:pageBlockSection>
      </apex:pageBlock>
       <apex:pageMessages />
   </apex:form>
 
</apex:page>

Thanks in advance.
The fromula seems to be working, but its displaying
"<img src="/servlet/servlet.FileDownload?file=0151600000QNE8V" alt=" " border="0"/>"
Instead of the image. Seems like a need URL reference?

This is the code on VF page to display picklist
<apex:outputField value="{!customo__c.Flag__c}" >    
    <apex:inlineEditSupport showOnEdit="saveButton, cancelButton" 
    hideOnEdit="editButton" event="ondblclick" 
    changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/>
</apex:outputField>
and field Flag__c is picklist "Green" , "Red"

This is the code on VF page to display image
{!customo__c.Flag_formula__c}
This is the fromula (text) for field "Flag_formula__c"
IMAGE(
CASE(Flag__c,
"Green","/servlet/servlet.FileDownload?file=0151600000QNE8V",
"Red","/servlet/servlet.FileDownload?file=0151600000QNE8f",
""),"")
The images URL work
https://c.na23.content.force.com/servlet/servlet.FileDownload?file=0151600000QNE8V
https://c.na23.content.force.com/servlet/servlet.FileDownload?file=0151600000QNE8f


 
  • April 09, 2016
  • Like
  • 0
Hey Guys,

Can anyone help me how to hide the stage filed in the opportunites object which is a required standard field.

Thanks in advance.
Virinchi.
One of the field in my custom object (Program__c) is a contact lookup field (Client__c).  How do I insert a new custom object with an existing contact without getting the this exception:

com.sforce.ws.SoapFaultException: A duplicate value was specified for field 'Id' in object 'Contact'

Thanks,
 
SObject[] records = new SObject[1];

	try {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT Id, FirstName, LastName, AccountId, Account.Name ");
		sb.append("FROM Contact ");
		sb.append("WHERE AccountId != NULL ");
		sb.append("  AND Id = '003d000002w3njaAAA' ");
		QueryResult queryResults = connection.query(sb.toString());
		SObject contact = null;
		if (queryResults.getSize() > 0) {
			contact = (SObject)queryResults.getRecords()[0];
		}

		SObject so = new SObject();
		so.setType("Program__c");
		so.setField("RecordTypeId", "012d0000000hQlHAAU");
		so.setField("Client__r", contact);
		so.setField("Marital_Status__c", "Separated");
		so.setField("Level_of_Care__c", "Inpatient");
		so.setField("Caller_Caregiver_Name__c", "Caregiver Name");
		so.setField("Patient_Type__c", "Impatient Discharge");
		so.setField("Admission_Date__c", new Date());
		so.setField("Projected_Discharge_Date__c", new Date());
		so.setField("Facility__c", "Grossmont");
		so.setField("Notes__c", "Test record added by Minh...");
		records[0] = so;

		// create the records in Salesforce.com
		SaveResult[] saveResults = connection.create(records);

		// check the returned results for any errors
		for (int i = 0; i < saveResults.length; i++) {
			if (saveResults[i].isSuccess()) {
				System.out.println(i+". Successfully created record - Id: " + saveResults[i].getId());
			}
			else {
				Error[] errors = saveResults[i].getErrors();
				for (int j = 0; j < errors.length; j++) {
					System.out.println("Error creating record: " + errors[j].getMessage());
				}
			}
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}

 
I have a VisualForce page using only the standard apex markup  <Knowledge:ArticleList>.

How can you know how many articles will be displayed?

How can you know if it returned no articles at all?

Visualforce Page:
<apex:page >
    <!-- User Guides Content section-->
User Guides
<knowledge:articleList articleVar="article" categories="Knowledge_Categories:AccuDate_9700" keyword="warranty" articleTypes="KB_Article__kav" pageSize="10">
<li>
<apex:outputLink target="_self" value="{!URLFOR($Action.KnowledgeArticle.View, article.id, ['popup' = 'true'])}">{!article.title}</apex:outputLink>
</li>
</knowledge:articleList> 
<!-- User Guides Content section-->    
    
</apex:page>

 
Challenge Not yet complete... here's what's wrong: 
Executing the 'getAnimalNameById' method on 'AnimalLocator' failed. Make sure the method exists with the name 'getAnimalNameById', is public and static, accepts an Integer and returns a String.

My Class Code is here :
 
global class AnimalLocator {
    
    public static String getAnimalNameById(Integer num) 
    {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/:'+num);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        
        String answer='VenMal';
        
        
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) 
        {
            System.debug('response.getBody() ========'+response.getBody());
            answer = 'NEW ANIMAL'; 
        }
        return answer;
    }      

}

And the TEST Class is as below:
 
@isTest
global class AnimalLocatorTest 
{
 static testMethod void testCallOut() 
{
    // Set mock callout class 
    Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock()); 
    // This causes a fake response to be sent
    // from the class that implements HttpCalloutMock. 
    string response = AnimalLocator.getAnimalNameById(1);
    // Verify that the response received contains fake values
       System.debug('response === '+response);
    
}

}

Test Mock Class is as below:
 
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) 
    {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal":{"id":0,"name":"VenMal","eats":"MeaTT","says":"ThanKYoU"}}');
        response.setStatusCode(200);
        return response; 
    }
}

When I queried the ApexClass Object, I could see all 3-classes 

Apex REST Callouts TrailHead Classes


Am I missing something or what should I do to succesfully validate this Unit ?
 
Hi,

I am getting below error while uploading managed package:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

An internal server error has occurred
An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 203819700-4327 (-1569916658)

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

Is there a way around?

Thank you,

Sylvio

 I need to fetch history of user record in Apex Class. Is there any way to enable history tracking on User Obejct. I do not see "Set History Tracking" button above User Fields like we see in Account object.

Hi, all. I am getting the following error when trying to complete this challenge: 
Challenge Not yet complete... here's what's wrong:
A process called 'Opportunity Management' doesn't exist. Check the process’s label and API name. Make sure that the process starts when a record changes.​


I have built this process, copying/pasting the name directly from the challenge, into 3 different orgs and using 2 different browser windows. I even got a brand new "trailhead playground" and that didn't work either. Anyone know what might be going on? 
I have a parent case on which three files are uploaded; now while creating the sub case from the related case section, these attachment should automatically visible in the subcase as well.

One solution: I did by re-inserting the same parent files in the sub case as well. with these the same file is created multiple times.
User-added image
Is their any way I can use the same file in multiple cases without re-inserting the same?
As a non-advanced Service Cloud user (only just set up, and set up Email-To-Case), but also a developer trying to accommodate more advanced Service Cloud users, I'm trying to understand how customers interact with Cases; in the dashboard, as well as how it gets stored in the API objects.

I know a customer can Email an address (like mysupport@mycompany.com) and that will create a Case, a CaseFeed of type 'EmailMessageEvent', and an associated EmailMessage.

But are there other ways besides emails (e.g. direct replies/posts in a dedicated support website)?

(I'm creating an app, part of which involves collecting CaseFeeds in order to display the Case conversations, but I need to know if I need to display anything else for customers, besides emails. I am currently displaying other things a user can do, because I know of them from seeing the Service Cloud dashboard and seeing the buttons for Reply, Post, Upload File, etc. But not sure what options customers have.)
Hi,

How to assign all contacts last name in the related account objects description field using trigger?H
I need to roll back a package to beta that isn't installed anywhere because we have some changes to make to custom fields. We are in development with it currently. I had to change it to released because I have an extension package that also uses this one, and you can't deploy a package that's an extension of a beta package. When I go to log a case, it tells me that all cases are supported by the developer community for this. Can anyone help me?
This is not a how to question, but a best practice/opinion question. I have a request to update a calculation on specific child records when a field on a parent record is updated. I am hesitant to do this since then the children records will go through the entire save procedure (including a good amount of Apex code), so it would add a bit more processing to the Apex transaction. My question is, when would you go ahead with this request vs pushing back and trying to find another solution (i.e. batch update of the child records every hour/night, new business process-- after updating the parent, go and check this checkbox on the children, . . . )? In general there shouldn't be more than 5 child records per parent that need to be updated.
I am trying to build a trigger to update a field on Account for a custom object that has a lookup relationship to the acccount (Investment__c).

The field on Account that I'm trying to update is DealCount__c  Number (3, 0).
The field on Investment__c that I am using to get the count is Deal_Unique_ID__c

The ID for Investment__c is a text field.

Any help or advice is greatly appreciated....my experience writting triggers is almost non-existent...and I'm trying to learn.  

Below is the error I'm receiving and the trigger:

//Error:Apex trigger AllDealCounts caused an unexpected exception, contact your administrator: AllDealCounts: execution of AfterUpdate caused by: System.StringException: Invalid id: PharmaMetrics (2017): External entry point
//Trigger
trigger AllDealCounts on Investment__c (after update,after insert) 
{
List <ID> DealIDs = new List<Id> ();
List <Account> accounts = new List<Account>();
List <AggregateResult> requirements = New List<AggregateResult>();

for(Investment__c req:trigger.new)
{
DealIDs.add(req.Name);
}
Accounts = [Select ID, DealCount__c from Account  where ID in :accounts];
 Requirements = [Select Target_Company__C,  Count(Deal_Unique_ID__c) from Investment__c where Target_Company__c in :accounts group by Target_Company__c];
For(AggregateResult ar: requirements)
{
for(Account a:accounts) 
{
if (ar.get('Accounts') == a.ID)
{a.DealCount__c =  Decimal.ValueOf(String.ValueOf(ar.get('expr0'))) ;}
}
}
}
I have a field on the cases object with the following formula:
IF(
ISBLANK(Initial_Email_response_with_time__c ),
NULL,TEXT(
FLOOR(Initial_Email_response_with_time__c - CreatedDate )
) & " Days " &
TEXT(
ROUND(MOD((Initial_Email_response_with_time__c - CreatedDate )*24,24),0)
) &" Hours " &
TEXT(
ROUND(MOD((Initial_Email_response_with_time__c - CreatedDate )*1440,60),0)
) &" Minutes ")

Is there anywhere to incorporate the business hours? The objective of this field to report on cases open and making sure they are responded to within 4 hours but when it comes to off hours and weekends, it wont work.
Over the course of years of creating campaigns with different member status, we have about 80+ status in the "Status" standard field on the Campaign Member object. I have created a simple custom visualforce page that uses a pageblock table to list member from a campaign and I have enable inline editing so users can double click on the fields to edit.  

When users click on the Status field only about 50% of the available status appear.  Any new status that is created will simply not appear in the dropdownlist
<apex:column style="width:8%;height:30px">
                    <apex:outputField value="{!record.Status}">
                         <apex:inlineEditSupport event="ondblClick" showOnEdit="saveButton"/>
                    </apex:outputField>          
                    <apex:facet name="header">Status</apex:facet>
                </apex:column>

 

Hello guys, I'm having a weird behavior with <apex:inputField>...

When the page loads, it receives the value from a Map variable on from it's controller, but when i change the value and click the SAVE button, it's value doesn't get updated. When debug the Map variable still has its original values.

VF:
 

<apex:pageBlockSection id="pbsModalidade" columns="1" title="{!segmento.Codigo__c} {!segmento.Nome_Segmento__c}" collapsible="true">
            <apex:inputField value="{!objetivosMP[grupo.id].Meta__c}" rendered="{!NOT chancelar}"></apex:inputField>
</apex:pageBlockSection>
 


Controller: 
 

public Map<Id, Objetivo__c> objetivosMP {get; set;}

public void save() {
      for (Id idGrupo: objetivosMP.keyset()){
            System.debug('objectives ' + objetivosMP.get(idGrupo));
      }
}

Anyone, can help me?
I'm using Named Credentials with "Allow Merge Fields in HTTP Body" in Apex code.
How to include exact char sequence "{!$Credential.OAuthToken}" (avoid replaceing into OAuth token) into my request body?
 
When adding products to an Opportunity the list is not sorted alphabetically.  How can I update this list view to display all my product alphabetically rather than randomly as the appear below?

User-added image

This is my Apex code where it brings in the product list.

<apex:outputLabel value="Product Name" for="productName"/> <apex:selectList id="productName" value="{!PricebookEntrys}" size="1" required="true"> <apex:selectOptions value="{!items}"/> </apex:selectList>

Can anyone help sort the products alphabetically?

Thanks in advance for any assistance
HI,

I'm working with a visualforce page and form and I wanted to display a list if U.S. States as just text with checkboxes underneath each state for the cities in that state. 

So for example:

Nevada
 - Reno
 - Carson City
 - Las Vegas

Colorado
 - Denver
 - Boulder

I have a custom object that stores customer records.  In the address fields I store the city and state.  I want to generate the output above using this data and have a checkbox rendered for each city.

Any ideas on how to do this using visualforce?
 
  • September 16, 2015
  • Like
  • 1
Need help with my VF page.  I am trying to display only the list view with no header, no buttons, no sidebar and not actions.  Anyone know how?
 
<apex:page sidebar="false" >
  
   <apex:enhancedlist type="Location__c" height="730" customizable="false" rowsPerPage="50" Listid="00B19000000S8a3"  />
  
</apex:page>

 
Hi folks,

I have written one class in org1.I generated wsdl file and partner wsdl of that class. I login to other salesforce org2 and import those two files into this org. I created one stub class in org2 and using this class i have called those classes and methods and callout this stub class using developer console. While executing this class it throws an error [System.CalloutException: IO Exception: Unauthorized endpoint, please check Setup-&gt;Security-&gt;Remote site settings. endpoint = https://login.salesforce.com/services/Soap/u/34.0]. I have pasted login url in Remote site settings in org 2.

Apex class in Org1:
global class webservicesoap1
{
 webservice static string createcontact(string Fname,string Lname,String phone)
 {
 list<contact> conlist=[select id from contact where firstname =:fname and lastname =:lname and phone =:phone];
  if(conlist.size()!=0)
   {
    return 'contact already exists';
    }
    else{
     contact c=new contact();
     c.firstname=fname;
     c.lastname=lname;
     c.phone=phone;
     insert c;
     return c.id;
     }
     }
     }

Stub Class i implemented in org2:

public class soapcallout
{

    public soapcallout(ApexPages.StandardController controller) {

    }

 public soapcallout()
 {
    partnerSoapSforceCom.soap spc=new partnerSoapSforceCom.soap();
    string username ='sfgt@283.com';
    string password ='radhekrishna***AIyGjqKUpuRnKaBzoX6XRUnzH';
    partnerSoapSforceCom.loginresult loginresult = spc.login(username, password);
    system.debug(loginresult.sessionid);
    
    soapSforceComSchemasClassWebservice.webservicesoap1 websrvc= new soapSforceComSchemasClassWebservice.webservicesoap1();
    soapSforceComSchemasClassWebservice.SessionHeader_element sessionheader =new soapSforceComSchemasClassWebservice.SessionHeader_element();
    sessionheader.sessionid = loginresult.sessionid;
    websrvc.timeout_x = 120000;
    websrvc.sessionheader = sessionheader;
    string s = websrvc.createcontact('Mahesh','Krishna','9526389523');
    }
    }



 
hi
when i convert lead to opportunity i want to display lead name that converted in opportunity.i want to write it in triggers based on a check box i am updating that field. 
 
It has been a few years since I've worked on Salesfoce. But I'm back for more! I was pocking around looking for a new sparkly IDE that might be waiting for me and I'm left with a feeling of confusion. What is going on? I get that Salesforce has/is working hard on the tooling api but who has a solid IDE solution that has professional support and sparkly toys? I know I know, I can just use the Eclipse plugin but you know, its not sparkly.

Cloud9 looks like the perfect solution for salesforce developers. The two cloud geeks are already working together with Heroku so why don't they have a OOTB Cloud9 solution for Salesforce.com development?

Has anyone tried to hook up a salesforce org with Cloud9? If not someone should make that happen. Or maybe I should have a go at it.
I looked at BrainEngine but the sign up page gives an azure 403, for that last week. It didn’t look like BrainEngine had more than one guy supporting it, and not open source. Maybe I’m overlooking something?

Any up dates on whats going on would be helpful.
 
I want to use extjs in visualforce but i am getting error Uncaught ReferenceError: Ext is not defined i also added all library related to ext js but this time also getting same error so How to solve this error. I have a urgent requirement to solve this issue .

Posting this in order to help others who, months from now, might Google "OP_WITH_INVALID_USER_TYPE_EXCEPTION" and find this explanation.

 

We wrote an Apex trigger on the User object, to insert a custom object record anytime a user updates their Chatter status.  This was done to fulfill a client's requirement to audit all Chatter activity.

 

The trigger worked fine, until one day the client signed up some Chatter Free users.  When such a user tried to update their status, they got a pop-up with an OP_WITH_INVALID_USER_TYPE_EXCEPTION error.

 

We scratched our collective heads for awhile.  After all, Apex triggers run in "system mode," right?  That is supposed to mean that "object and field-level permissions of the current user are ignored."  And yet this trigger seemed like it was running in "user mode," enforcing restrictions based on who the current user was.

 

The root cause turned out to be that a Chatter Free user cannot be the owner of a custom object record, and SFDC by default sets the current user as a new record's first owner.  We discovered this when we realized, via experiment, that Apex triggers fired as the result of actions by Chatter Free users could definitely update an existing record, but were having problems creating records.

 

So the simple solution was to explicitly set the owner of the new record to some fully-licensed user prior to inserting it.