• Raidan
  • SMARTIE
  • 730 Points
  • Member since 2015
  • Rightpoint.com

  • Chatter
    Feed
  • 24
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 157
    Replies
Getting error "Loop Variable Mut be of Type Account Line 7".
Here is my code.
No classes named accoutn.

trigger HasWorkPaperManager on Account (after insert, after update) {

    Map<ID, Account> parentAccount = new Map<ID, Account>();
    List<Id> listIds = new List<Id>();
    List<Id> LineItems = new List<Id>();

    for (AMS_Inventory_Rollup__c childObj : Trigger.new) {
        listIds.add(childObj.AccountID__c);
        LineItems.add(childObj.Id);
    }
  
    parentAccount = new Map<Id, Account>([SELECT id,Has_WorkPaper_Manager__c,(Select id from Ams_inventory_rollups__r where name = '511000') FROM account WHERE ID IN :listIds]);
   
    for (AMS_Inventory_Rollup__c AMSInventoryRollup: Trigger.new){
         Account myParentAccount = parentAccount.get(AMSInventoryRollup.Account);
        if(parentAccount.containsKey(AMSInventoryRollup.Account) && parentaccount.get(AMSInventoryRollup.Account).AMSInventoryRollups__r.size() > 0)
        {
            myParentAccount.Has_WorkPaper_Manager__c = true;
        }
        else
        {
            myParentAccount.Has_WorkPaper_Manager__c = false ;
        }
    }
    update parentAccount.values();
 }
I'm not sure how to create a formula check box field on the Lead object to say if Profile is ________ & profile is __________, then True.  
So, I need the check box to be checked when a particular Profile creates the lead. 
Hello,

I have below structure of code

Triggger{
    ClassX.functionAsyn();
}

global class ClassX{
    @Future(callout=true)
    Public static void functionAsyn()
    {
      url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins='+address1+'&destinations='+address2+'&mode=driving&key=AIzaSyDCrFBIYoXyYhmEwsNcQ';
                req.setEndPoint(url); 
                resp = http.send(req);
                JSON2Apex obj = JSON2Apex.parse(resp.getBody()); 
    }
}


resp.getBody() is always nulll because  "Web Service Callouts" are not allowed,

I followed this link https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_wsdl2apex_testing.htm

But still i am difficult to write a test class

Can anyone provide more help on this ?

thank you
 
Hi all
 I have a cutom object A which has certain fields like Center, District, Region, etc. I have another object where I need to create custom lookup fields to individual fields of the object A like a field to capture Center of object A, District of Object A and so on.
Is it possible and how?
Thank you
Hi All,

I need to find out the Names Corresponding to each OwnerID in the SQL server database.
​Whoch table I should use to gte the desired results? 
I'm trying to write test code for a class that is invoked by a custom button.  This is the first time I've done this and lots of googling has not provided me with the answer!

Thank you very much for your help on this!

This is the button:
/apex/SendAdverseEvents?id={!Adverse_Event__c.Id}

I have successfully created an Adverse Event in my test code but and I think I need to instantiate the SendAdverseEventsController but I'm not sure how to do this.

Here is my test code so far:
@isTest
public class SendAdverseEventsTest {
  //Setup test data
  static testMethod void SendAdverseEvtTest() {
        
    Id rtPA = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId();
  
    //create new account for testing       
    Account a = New Account ();
           a.FirstName = 'Robert';
           a.LastName = 'Smith';
           a.RecordTypeId = rtPA;
           a.Email__c = 'test@example.com';
           a.Gender__c = 'Male';
           Insert a;
    

   //find contact ID of the new account
     account RS = [Select PersonContactID from Account where LastName = 'Smith'];
    
    //create adverse event
    Adverse_Event__c AE = New Adverse_Event__c();
        AE.Patient_Identifier__c = RS.PersonContactId;
        AE.Does_the_patient_give_permission_to_call__c = 'Yes';
            AE.Does_the_patient_give_permission_to_cont__c = 'Yes';
          AE.Suspect_Drug_1__c = 'Suspect Drug 1';
          AE.Brand__c = 'Harvoni';
          AE.Is_Patient_Affiliated_with_an_Ambassador__c = 'No';
          Insert AE;
        system.debug(AE);
       
        //find ID of the new adverse event
       Adverse_Event__c AECreated = [Select ID, Name, Auto_Initials__c, Suspect_Drug_1__c, Document_File_Name__c, Document_File_Name_Gilead__c, CreatedDate from Adverse_Event__c where Patient_Identifier__r.LastName = 'Smith'];
    system.debug(AECreated);
        system.debug(AECreated.id);
    
    
    //test.startTest();
      //SendAdverseEventsController con = new SendAdverseEventsController(); // Create instance of controller class
      //con.adverseEvent.id = AECreated.Id; // Set the Id
      //con.SendAdverseEventsController(); // Call the class method, before calling method, you can populate the fields, which are require in this method
    //test.stopTest();
  }
}
    
The commented code at the end I copied from developer forums but I can't work out how to get it to work.

The SendAdverseEventsController is this:

public with sharing class SendAdverseEventsController extends BaseClass {
    
    public Adverse_Event__c adverseEvent { get; set; }
    public String toAddresses { get; set; }
    public String toContacts { get; set; }
    public String ccAddresses { get; set; }
    public String ccContacts { get; set; }
    public String bccAddresses { get; set; }
    public String bccContacts { get; set; }
    public String documentTemplateId { get; set; }
    public String subject { get; set; }
    public String body { get; set; } 
    public User contactLookup {get; set;}
    public Boolean hasAccess { get; set; }
    
    public static final String GLOBAL_EMAIL_NAME = 'AE Reports';
    public static final String GLOBAL_EMAIL = 'aereports@snow-companies.com';
    
    public String defaultBccEmail {get;set;}
    
    private Map<Id,String> documentTemplates;
    private Map<String,String> contactNames;
    
    
    public SendAdverseEventsController() {
        
        this.defaultBccEmail = GLOBAL_EMAIL;
        this.bccAddresses = GLOBAL_EMAIL;
        
        contactLookup = new User();

        Map<String,String> params = ApexPages.currentPage().getParameters();

        for (Adverse_Event__c ae : [select Name, Auto_Initials__c, Suspect_Drug_1__c, Document_File_Name__c, Document_File_Name_Gilead__c, CreatedDate from Adverse_Event__c where Id = :params.get('id')]) {
            adverseEvent = ae;  
        }
        
        for (EmailTemplate et : [select Subject, HtmlValue from EmailTemplate 
                                  where Folder.Name = 'Adverse Events Emails' 
                                    and Name = 'Email Template']) {
            //subject = et.Subject;
            subject = adverseEvent.Document_File_Name__c;
            body = et.HtmlValue;
        }

        String username = UserInfo.getUserName().split('@')[0];

        if (ApexPages.currentPage().getParameters().get('signature') != null) {
            username = ApexPages.currentPage().getParameters().get('signature');
        }

        for (EmailTemplate et : [select Subject, HtmlValue from EmailTemplate 
                                  where Folder.Name = 'Signatures' 
                                    and Name = :username]) {
            
            if (body == null) {
                body = '';
            }
            
            body += et.HtmlValue;
        }
        List<Adverse_Events_Access__c> access = Adverse_Events_Access__c.getAll().values();
        hasAccess = false;
        for(Adverse_Events_Access__c aea : access){
            if(aea.Username__c == UserInfo.getUserName()){
                hasAccess = true;
                break;
            }
        }
    }
    
    public String getGileadSubject(Adverse_Event__c  ae){
       String dateString = ae.CreatedDate.format('ddMMMyyyy').toUpperCase();
       String subjectFormatted = dateString + '-' + ae.Auto_Initials__c + '-' + ae.Suspect_Drug_1__c + '-' + ae.Name;
       
       return subjectFormatted;
   }
   
   public void setSubjectName(){
       if(this.documentTemplateId != null && documentTemplates.get(this.documentTemplateId) == 'Gilead AE Form'){
            subject = this.getGileadSubject(adverseEvent);
       }
       else{
           subject = adverseEvent.Document_File_Name__c;       
       }
   }
    
    public SelectOption[] getTemplates() {
        SelectOption[] templates = new SelectOption[]{ new SelectOption('', '-None-') };
        
        documentTemplates = new Map<Id,String>();
        for (EmailTemplate et : [select Name from EmailTemplate where Folder.Name = 'Adverse Events Templates']) {
            templates.add(new SelectOption(et.Id, et.Name));
            documentTemplates.put(et.Id, et.Name);  
        }
        
        return templates;
    }
    
    
    public PageReference sendEmail() {
        
        //mergeContactsAddresses();
        
        MandrillClient.Message message = new MandrillClient.Message();
        addEmailAddresses(message.to, toAddresses, 'to');
        addEmailAddresses(message.to, ccAddresses, 'cc');
        addEmailAddresses(message.to, bccAddresses, 'bcc');
        
        if (!message.to.isEmpty()) {
            
            //User user = [select Name, Email from User where Id = :UserInfo.getUserId()];                    
            //message.from_name = user.Name;
            //message.from_email = user.Email;
            
            message.from_name = GLOBAL_EMAIL_NAME;
            message.from_email = GLOBAL_EMAIL;
            
            this.setSubjectName();
            
            message.html = body;
            message.subject = subject;
            message.campaign = 'GPS'; //TODO: Change for other
            message.what = adverseEvent.Id;
            
            //Attachment
            Blob file = new PageReference('/apex/DocumentMerge?id=' + adverseEvent.Id + '&tid=' + documentTemplateId).getContent();
            MandrillClient.MandrillAttachment attach = new MandrillClient.MandrillAttachment();
            //attach.name = documentTemplates.get(documentTemplateId) + '.pdf';
            attach.name = subject + '.pdf';
            attach.type = 'application/pdf';
            attach.content = Encodingutil.base64Encode(file);
            message.attachments.add(attach); 
            
            String allRecipients = '';
            
            for (MandrillClient.Recipient recipient : message.to) {
                allRecipients += ', ' + recipient.email;
            }
            
            allRecipients = (allRecipients != '' ? allRecipients.substring(2) : '');
            
            try {
                Map<String,String> response = MandrillClient.send(new MandrillClient.Message[]{ message });
                Task[] tasks = MandrillClient.insertTasks();
                
                for (Task t : tasks) {
                    t.Adverse_Events_Recipients__c = allRecipients;
                }
                update tasks;
                
                Attachment a = new Attachment();
                a.Name = attach.name;
                a.ContentType = attach.type;
                a.Body = file;
                a.ParentId = adverseEvent.Id;
                insert a;
                
                return new PageReference('/' + adverseEvent.Id);
            }
            catch (Exception e) {
                addErrorMessage(e.getMessage());
            }                            
        }
        
                        
        return null;
    }
    
    
    private void mergeContactsAddresses() {
        String[] cids = new String[]{};
        
        for (String cid : toContacts.split(';')) {
            cids.add(cid);
        }
        for (String cid : ccContacts.split(';')) {
            cids.add(cid);
        }
        for (String cid : bccContacts.split(';')) {
            cids.add(cid);
        }
        
        Map<String,String> contactEmails = new Map<String,String>();
                
        contactNames = new Map<String,String>();
        for (Contact c : [select Name, Email from Contact where Id = :cids and Email <> null]) {
            contactNames.put(c.Email.toLowerCase(), c.Name);
            contactEmails.put(c.Id, c.Email.toLowerCase());
        }
        
        for (String cid : toContacts.split(',')) {
            if (contactEmails.containsKey(cid)) {
                if (toAddresses != null && toAddresses.trim() != '') {
                    toAddresses += ',';
                }
                toAddresses += contactEmails.get(cid) + ',';
            }
        }
        for (String cid : ccContacts.split(';')) {
            if (contactEmails.containsKey(cid)) {
                if (ccAddresses != null && ccAddresses.trim() != '') {
                    ccAddresses += ',';
                }
                ccAddresses += contactEmails.get(cid) + ',';
            }
        }
        for (String cid : bccContacts.split(';')) {
            if (contactEmails.containsKey(cid)) {
                if (bccAddresses != null && bccAddresses.trim() != '') {
                    bccAddresses += ',';
                }
                bccAddresses += contactEmails.get(cid) + ',';
            }
        }        
    }
    
    
    private void addEmailAddresses(MandrillClient.Recipient[] recipients, String addr, String type) {
        if (addr != null) {
            for (String email : addr.split(',')) {
                if (email != null && email.trim() != '') {
                    MandrillClient.Recipient recipient = new MandrillClient.Recipient();
                    recipient.email = email.trim().toLowerCase();
                    
                    //if (contactNames.containsKey(recipient.email)) {
                    //   recipient.name = contactNames.get(recipient.email);    
                    //}
                    
                    recipient.type = type;
                    recipients.add(recipient);              
                }
            }
        }
    }
    
    
    public PageReference cancel() {
        if (adverseEvent != null) {
            return new PageReference('/' + adverseEvent.Id);
        }
        else {
            return new PageReference('/home/home.jsp');
        }
    }
}
 
Hi guys,

I've got a difficult problem on which I am working a few hours but still wasn't able to solve.

In our organisation we've got lots of orders with different order items. I cannot find a custom implementation for calculating the TotalAmount of an order, so I assume that it is calculated by Salesforce itself and sums up the TotalPrice fields of the order items of an order. We've also implemented a custom field (let's call it BillingPercent) which holds a percent value that indicates how  much percent of the TotalAmount of the order is already billed.

If I insert, update or remove some of the order items of an order the TotalAmount of this order changes. So now, every time the TotalAmount changes, I want to recalculate the value of my custom field BillingPercent, so that it adapts to the new TotalAmount.

I tried the following:
- I tried to add this functionality to my onBeforeUpdate Trigger for Orders, so that I can use the old and new TotalAmount values of the order to calculate the new BillingPercent value. Unfortunately doesn't get called if I insert, update or delete some of my order items.
- I implemented a new onBeforeInsert/Update/Delete-Trigger on OrderItems in which I was able to calculate the new BillingPercent value. This works fine for just updating existing order items, but if I insert or delete an new order item, the trigger crashes with the following message:

first error: SELF_REFERENCE_FROM_TRIGGER

The reason why the trigger crashes is obvious: I delete an order item, the BillingPercent value of the order is updated and because of this the UpdateOrder trigger gets called. The UpdateOrder trigger itself has the function to add all the default order items we specified in another table. 

Delete (default) order item from order --> UpdateOrderItem.trigger is called --> BillingPercent is calculated --> update order --> UpdateOrder trigger is called --> UpdateOrder trigger updates the order items and so the UpdateOrderItem.trigger is called again and crashes because the order items is already referenced in the trigger.

Anybody got an idea how to solve the problem and achieve the simple recalculation of the BillingPercent value after the TotalAmount value changes? I'm not fixed on using triggers, I already thought about using a workflow rule but I don't know if this could be the right way. Maybe there are some other possibilities how to achieve the desired behaviour.

Thanks for your help :)

Best Regards,
Jenny
Hi, 

I would like to create a custom field formula that has two conditions and based on that conditions it will perform a formula. 
*IF (field is empty/null) -> perform formula 1
otherwise (field is not empty/null) -> perform formula 2

Thanks !
 
So I've been stuck on this for way too long; I've scoured the forums and made every change I could think of, but I have no idea why I'm not getting the save to function. I've tried using the standard controller's save, and the current setup using the custom save method. The way I've got it set now, the developer console shows that there are DML calls being made, but the changes aren't sticking. 

If someone could tell me where I'm going wrong, I'd really appreciate it.

The VF page:
<apex:page standardController="WeeklyDevStats__c" recordSetVar="weeklyDevList" extensions="MaxHoursController2">
    
 <apex:pageBlock >
 <apex:pageMessages />
  <apex:pageBlockSection >
   <apex:form >
    <apex:selectList label="Week" value="{!selectedWeek}" size="1" multiselect="false" >
     <apex:actionSupport event="onchange" action="{!changeWeek}" />
      <apex:selectOptions value="{!weeks}" />
    </apex:selectList>
    
   </apex:form>
  </apex:pageBlockSection>
  <apex:pageBlockSection >
   <apex:dataTable value="{!weeklyDevList}" var="dev" columnsWidth="150">
      <apex:column headerValue="Developer">
         <apex:outputField value="{!dev.Dev_name__c}"/>
      </apex:column>
      <apex:column headerValue="Max Hours">
         <apex:form ><apex:inputField value="{!dev.MaxHours__c}">
           
         </apex:inputField></apex:form>
      </apex:column>
   </apex:dataTable>
  </apex:pageBlockSection>
 </apex:pageBlock>
 <apex:form ><apex:commandButton value="Save" action="{!saveHours}"/></apex:form>
 
</apex:page>
The controller:
public class MaxHoursController2 {


    public String selectedWeek { get; set; }
    public List<SelectOption> weeks { get; set; }
    public List<WeeklyDevStats__c> weeklyDevList {get; set;}
    
    public Apexpages.standardsetcontroller sc;
    
    public MaxHoursController2(ApexPages.StandardSetController controller) {
        sc = controller;
        selectedWeek = CalendarClass.getInstance().getMonday().format();
        weeks = new List<SelectOption>();
        
        setWeekList();
        setWeeklyDevList(Date.parse(selectedWeek));
    }
    

    public PageReference changeWeek() {
        setWeeklyDevList(Date.valueOf(selectedWeek));
        
        return null;
    }
    
    public PageReference saveHours() {
        
        try {
            update weeklyDevList;
        } catch(DMLException e) {
            Apexpages.addmessages(e);
        }
        return null;
    }
    
    public void setWeekList() {
        for (Date day : CalendarClass.getInstance().getNextMondays(8)) {
            weeks.add(new SelectOption(String.valueOf(day), String.valueOf(day)));
        }
   }

    public void setWeeklyDevList(Date week) {
    
        weeklyDevList = [SELECT Dev_name__c, MaxHours__c FROM WeeklyDevStats__c WHERE Week_dev__c = :week];
    }
    
    public List<WeeklyDevStats__c> getWeeklyDevList() {
        return weeklyDevList;
    }
    
}


 
I have this custom button with Javascript that is working perfectly fine: 

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

if ({!pba__Offer__c.pba__SystemIsCancelled__c}) { 
alert("{!$Label.pba__Offer_ErrorAlreadyCancelled}"); 
} else { 

if (confirm("{!$Label.pba__Offer_ConfirmCancellation}")) { 

var updateSobject = new sforce.SObject("pba__Offer__c"); 

try { 

updateSobject.Id = "{!pba__Offer__c.Id}" ; 
updateSobject.pba__SystemIsCancelled__c = true; 

result = sforce.connection.update([updateSobject]); 
if (result[0].getBoolean("success")) { 
location.reload(true); 
} else { 
alert("{!$Label.pba__Generic_ErrorOccured}: " + result[0].errors.message); 


} catch(e) { 
alert("{!$Label.pba__Generic_ErrorOccured}: " + e); 




}


I want to include an additional line to this code, can you please help me on where this new line should go:

if (ISBLANK({!pba__Offer__c.Offer_canceled_comments__c}) { 
alert ("Please specify the reason why the Offer has been canceled!!!!"); 
} else { 
Hello,

I am attempting to set up a workflow process that will send me and a few other admins an email when the number of cases for a certain location hits 7 within 7 days.  I was looking at this, and it seems to be somewhat close to what I am tring to do, but not quite.

If anyone has any suggestions I would appreciate it!

Thank you!
Hello Guy, 
I'm tried with this code .
<aura:attribute name="opp" type="Opportunity"/>
<li class="slds-page-header__detail-block">
          <p class="slds-text-heading--label-normal accInfoLabel slds-truncate slds-m-bottom--xx-small" title="Billing Account">Billing Account</p>
          <p>
            <span title="{!v.opp.Billing_Account__c}">{!v.opp.Billing_Account__c}&nbsp;</span>
          </p>
        </li>

I try to display Account.Name that Billing Account field is look up to account , but when I get it show me as ID . 
So I don't know how to display Account Name on custom field instead ID of Account?? 

Please, help me .
Thanks in advance.
Currently I am working on changing our opportunity screen to change the way it is being filled out. This way it follows our sales process. A simple way to put it is that I have created 5 sections on the opportunity screen each representing a different stage. Now what I want to happen is that each time a stage is selected, I would like that section to become available for editing. All new opportunities should begin in the opportunity section, therefore I would like that section to be available for editing, but I want the other sections to be visible but locked from being edited. Then once the next stage is selected, the next section becomes available for editing and the remainder remain visible but locked, etc.

So far I tried testing this with just the opportunity stage. What I did was I created a field set including all the fields in the opportunity section. Then I created a visualforce page. My current issue with this is that it is doing the opposite of what I want. It is blocking the opportunity section (and it is not even visible) until after I save the record. Once the record is saved the opportunity section appears but the entire screen is available for editing. This is my current visualforce page criteria.

<apex:page standardController="Opportunity"> 
    <apex:form >
            <apex:pageblock > 
                    <apex:pageBlockSection title="Opportunity"> 
                         <apex:repeatvalue="{$ObjectType.Opportunity.fieldsets.opportunityFieldSet}"var="fieldValue">                    
                                 <apex:Inputfield value="{!Opportunity[fieldValue]}"/> 
                          </apex:repeat>
                    </apex:pageBlockSection> 
             </apex:pageblock>
         </apex:form> 
  </apex:page>

Any assistance would be greatly appreciated. Thanks!
Hi,

I just deployed my first VF page and associated Apex Class. The validation and deployment were all successful and if I open the developer console in the live org I can see the VF page and APEX class and test class. When I go to the Account Page layout though in the live org to add the VF page there is no option for VisualForce Pages. It's all working fine and displaying in the Sandbox.
The page simply gets all of the open opportunities for accounts where the Parent Account is equal to the account that is currently being displayed.
This is my code that is working in the Sandbox

VF Page:
<apex:page sidebar="false" showHeader="false" Controller="ChildOpportunitiesAP">
   <apex:form >
          <apex:pageBlock title="Open child opportunities" id="pb"> 
              Filter:
              <apex:selectList value="{! selectListValue }" size="1">
                  <apex:selectOptions value="{!availableFilters}"/>
                  <apex:actionSupport event="onchange" action="{!refresh}" reRender="pb"/>
              </apex:selectList>
          <apex:pageBlockTable value="{!RelatedOpportunities}" var="opp">
              <apex:column >
                  <apex:facet name="header"> 
                      <apex:commandLink action="{!sortByAccountName}"
                                    reRender="pb">Account Name
                      </apex:commandLink>
                  </apex:facet>    
                     <apex:outputLink value="/{! opp.Account.id}" target="_top">
                                {!opp.Account.Name}
                     </apex:outputLink>     
               </apex:column>
              <!--<apex:column value="{! opp.Account.Name}" >
                  <apex:facet name="header"> 
                      <apex:commandLink action="{!sortByAccountName}"
                                    reRender="pb">Account Name
                      </apex:commandLink>
                  </apex:facet>        
               </apex:column>-->
              <apex:column >
                  <apex:facet name="header"> 
                      <apex:commandLink action="{!sortByOpportunityName}"
                                    reRender="pb">Opportunity Name
                      </apex:commandLink>
                  </apex:facet>    
                     <apex:outputLink value="/{! opp.id}" target="_top">
                                {!opp.Name}
                     </apex:outputLink>     
               </apex:column>
              <!--<apex:column value="{! opp.Name}">
                  <apex:facet name="header">
                  <apex:commandLink action="{!sortByOpportunityName}"
                                    reRender="pb">Opportunity Name
                      </apex:commandLink>
                  </apex:facet>
              </apex:column>-->
              <apex:column value="{! opp.Total_Opportunity_Amount__c}">
                  <apex:facet name="header">
                  <apex:commandLink action="{!sortByAmount}"
                                    reRender="pb">Total Opportunity Amount
                      </apex:commandLink>
                  </apex:facet>
              </apex:column>
              <apex:column value="{! opp.StageName}">
                  <apex:facet name="header">
                  <apex:commandLink action="{!sortByStage}"
                                    reRender="pb">Stage
                      </apex:commandLink>
                  </apex:facet>
              </apex:column>
          </apex:pageBlockTable>
        <apex:panelGrid columns="7">
                <apex:commandButton status="fetchStatus" reRender="pb" value="|<" action="{!controller.first}" disabled="{!!controller.hasPrevious}" title="First Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value="<" action="{!controller.previous}" disabled="{!!controller.hasPrevious}" title="Previous Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value=">" action="{!controller.next}" disabled="{!!controller.hasNext}" title="Next Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value=">|" action="{!controller.last}" disabled="{!!controller.hasNext}" title="Last Page"/>
                <apex:outputText >{!(controller.pageNumber * size)+1-size}-{!IF((controller.pageNumber * size)>noOfRecords, noOfRecords,(controller.pageNumber * size))} of {!noOfRecords}</apex:outputText>
                <apex:commandButton status="fetchStatus" reRender="pb" value="Refresh" action="{!refresh}" title="Refresh Page"/>
                <apex:outputPanel style="color:#4AA02C;font-weight:bold">
                    <apex:actionStatus id="fetchStatus" startText="Fetching..." stopText=""/>
                </apex:outputPanel>
            </apex:panelGrid>
    </apex:pageBlock>
  </apex:form>
</apex:page>

APEX page:

public with sharing class ChildOpportunitiesAP {
    private id Parent_Acc_Id;
    Public Integer noOfRecords{Get;Set;}
    Public Integer size {get;Set;}
    public String selectListValue{get;Set;}
    private String sortColumn = 'Name';
    private String previousSortColumn = null;
    private String sortOrder = 'ASC';
     
          public ApexPages.StandardSetController controller {
                    get{
                 Parent_Acc_Id = ApexPages.currentPage().getparameters().get('id');
                        system.debug('ChildOpps-Test:' + Parent_Acc_Id);
                        if(controller == null){
                            system.debug('ChildOpps-Test-2');
                            size = 4;
                            string queryString = '';
                             system.debug(' Before query - Sort order = ' + sortColumn);
                            if (selectListValue == 'All') {
                                system.debug('ChildOpps-Test-3');
                                queryString = 'SELECT Account.Name, Name, Total_Opportunity_Amount__c, StageName ' +
                                ' FROM Opportunity WHERE Account.Parent.id=: Parent_Acc_Id AND IsWon = False ORDER BY ' + sortColumn + ' ' + sortOrder;
                            }
                            else {
                                system.debug('ChildOpps-Test-4');
                                queryString = 'SELECT Account.Name, Name, Total_Opportunity_Amount__c, StageName ' +
                                ' FROM Opportunity WHERE Account.Parent.id=: Parent_Acc_Id AND IsWon = False AND Name =: selectListValue ORDER BY ' + sortColumn + ' ' + sortOrder ;
                            }
                            system.debug(queryString);
                            system.debug(Parent_Acc_Id);
                                 controller = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                        controller.setPageSize(size);
                            noOfRecords = controller.getResultSize();
             }
             return controller;                              
            }set;
        }
    
    public ChildOpportunitiesAP() {
        selectListValue = 'All';
    }
    
        public List<Opportunity> getRelatedOpportunities(){
                        List <Opportunity> childOpps = New List<Opportunity>();
        FOR(Opportunity opp:(List<Opportunity>)controller.getRecords())
            childOpps.add(opp);
                 Return childOpps;   
         }
    
        public pageReference refresh(){
            controller = null;
            /*getRelatedOpportunities();*/
            controller.setPageNumber(1);
            return null;
        }  
    
    public List<selectOption> getAvailableFilters(){
        List<selectOption> options = new List<SelectOption>();
        List<Opportunity> availableOpps = new List<Opportunity>();
        availableOpps = [SELECT Account.Name, Name, Total_Opportunity_Amount__c, StageName FROM Opportunity WHERE IsWon = False AND Account.Parent.id=: Parent_Acc_Id];
        options.add(new SelectOption('All','All'));
        
        Set<Id> accountIdSet = new Set<Id>();
        for (Opportunity opp:availableOpps){
            if(!accountIdSet.contains(opp.accountID)) {
                options.add(new SelectOption(opp.AccountId, opp.Account.Name));
                accountIdSet.add(opp.AccountId);
            }
        }
        return options;
    }
    
    Public pageReference getFilteredOpportunities(){
        /*getRelatedOpportunities();*/
        controller.setPageNumber(1);
        return Null;
    }
    
    public pageReference sortByAccountName() {
        setSortOrder('Account.Name');
        return Refresh();
    }
    
    public pageReference sortByOpportunityName(){
        setSortOrder('Name');
         return Refresh();
    }
    
    public pageReference sortByAmount(){
        setSortOrder('Total_Opportunity_Amount__C');
        return Refresh();
    }
      
    public pageReference sortByStage() {
        setSortOrder('StageName');
        return Refresh();
    }
    
    private void setSortOrder(string columnName){
        sortColumn = columnName;
        if (previousSortColumn == sortColumn){
            sortOrder = 'DESC';
            previousSortColumn = null;
        }
        else{
            previousSortColumn = sortColumn;
            sortOrder = 'ASC';
        }        
    }
}

Could you someone offer some advice please

Thanks
Hi,
I am very new to Salesforce and have been struggling with writing a validation rule for a week now and am getting nowhere fast!  Essentially I want 3 fields to become required when data is entered into another field.  When a new Contact is created and an Email address is added to the Contact I want a picklist that will capture the Source of the Email, a date field that will capture when the Email was obtained and a text field that will capture who obtained the Email to become mandatory. On a net new record the rule should only run if an Email address is added.  To make matters even more difficult I will also have Contacts in my system that have been imported from a legacy CRM system.  These Contacts may not have an existing Email address.  I also want this rule to run if an Email is added to one of these existing records, or if the Email address on the existing record is changed and the three required fields I note above are blank.
I started out small with just the following.  The appropriate error message does show, but when I choose a picklist value and try to save the error message won't go away and won't let me save the record.

AND
(OR(ISNEW(),(ISCHANGED(Email)),
ISBLANK(TEXT(Email_Source__c))
))

As I've mentioned, I'm very new to Salesforce and am still trying to understand how this validation function works. Any suggestions would be appreciated.
I have a custom object (Properties__c) that is a related list item for Accounts. Since some of the properties have been sold, users only want to see the Active Properties in the related list for Acccounts. I have attempted to use the Account Standard Controller in Visualforce along with an extension to accomplish this:
My Visualforce page markup is as follows:
<apex:page sidebar="false" showHeader="false" StandardController="Account" extensions="ActProp">
  <apex:pageBlock title="List of Properties">
 <apex:pageBlockTable value="{!props}" var="a">
        <apex:column value="{!a.Name}"/>
        <apex:column value="{!a.Asset_Type__c}"/>
        <apex:column value="{!a.RecordType.Name}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
 </apex:page> 


My Controller extension is as follows:
public class ActProp{
   public ActProp(ApexPages.StandardController cont) {}
   List<Property__c> props = [Select Name, RecordType.Name, Asset_Type__c from Property__c where Status__c ='1'];
      public List<Property__c> getprops(){
      return props;
      } 
}


My Visualforce page an custom controller both save with no issues; however, when I run the Page with a valid account (one with properties), the only thing that is returned is the "List of Properties" Block Title. I have read through the VF documentation and viewed related YouTube videos to try to figure this out. I know that I am thisclose, but am missing an element. Any assistance would be greatly appreciated. Thank you.
In my opportunity, I have fields where they can schedule machines for jobs.  The machine is a custom object that has a maximum qty that can be scheduled in a rolling 9 day period.  I'm trying to keep them from over scheduling the machine so I need to select all opportunities in the 9 day range that are still open and are scheduled on the same machine as the new opportunity. 

I've written the below trigger, but I don't know how to format the List or Map to get the collection of Opportunities I need - I get an error, Error: Compile Error: expecting a colon, found 'o.Mfg_Machine__c' at line 28 column 66 (I've bolded the offending List statement below).

Any help would be greatly appreciated!

trigger oppMachineSchd on Opportunity (before update, before insert) {

   Map<Opportunity> oppMfgNew = new Map<id,Opportunity>();
   List<Opportunity> oppsOnMachine = new List<Opportunity>();
   Set<Id> machId = new Set<Id>();

   for (Opportunity opp:System.Trigger.new){
      if (opp.isWon && opp.Manufacturing_Due_Date_F__c != null && Manufacturing_Complete_D__c == null){
         system.debug('in new: ' + opp.Machine__c + ' ' + opp.Manufacturing_Due_Date_F__c);
         oppMfgNew.add(opp);  
         machId.add(opp.Mfg_Machine__c);
      }
   }
   
   if (OppMfgNew.size() > 0){
      Map<Id, Machine__c> mach = new Map<Id, Machine__c>(
        [SELECT Id, Name, Max_7_Day_Qty__c 
           FROM Machine__c 
           WHERE id in :machId]);

// get all open             
      for (Opportunity o:oppMfgNew){
         BeginDate = o.Manufacturing_Due_Date_F__c.addDays(-9);
         system.debug('working on: ' + o.Name + ' ' + o.Manufacturing_Due_Date_F__c + ' ' + BeginDate);
         List<Opportunity> oppsOnMachine = [SELECT Name, Mfg_Machine__c, Manufacturing_Due_Date_F__c, Quantity__c
                                           FROM Opportunity 
                                           WHERE Mfg_Machine__c = o.Mfg_Machine__c AND Manufacturing_Complete_D__c = null AND Manufacturing_Due_Date_F__c >= BeginDate 
                                                 AND Manufacturing_Due_Date_F__c <= o.Manufacturing_Due_Date_F__c]; 
        

         for (Opportunity oom:oppsOnMachine){
            system.debug('oom: ' + Name + ' ' + oom.Mfg_Machine__c + ' ' + oom.Quantity__c);
            totQty += oom.Quantity__c;
         }
        
         totQty += o.Quantity__c;
         Machine__c mQty = mach.get(o.Machine__c);
         if (totQty > mQty.Max_7_Day_Qty__c){
            o.addError('Machine is overscheduled; Please select a later date');
         }
      }
   }
}       
 
Hi,
I was wondering if someone could help me. I am trying to populate a List of selectOption with distinct values.
I thought by using a set I could achieve this, but I'm still getting duplicates.

By code is as follows:

public List<selectOption> getAvailableFilters(){
        List<selectOption> options = new List<SelectOption>();
        List<Opportunity> availableOpps = new List<Opportunity>();
        availableOpps = [SELECT Account.Name, Name, Total_Opportunity_Amount__c, StageName FROM Opportunity WHERE IsWon = False AND Account.Parent.id=: Parent_Acc_Id];
         options.add(new SelectOption('All','All'));
        FOR(Opportunity opp:availableOpps)
        {
            List<opportunity> tempOptionList = new List<opportunity>();
            Set<selectOption> mySetOfOptions = new Set<selectOption>();
            tempOptionList.add(opp);
            for(opportunity myOpp:tempOptionList){
                if (mySetOfOptions.add(new SelectOption(myOpp.Account.ID, myOpp.Account.Name))){
                    options.add(new SelectOption(myOpp.Account.ID, myOpp.Account.Name));
                }
            }
                  }
       
        return options;
    }


Any help would be much appreciated.
Thanks
I am trying to grab the picklist values from the State field on my Lead object. The State field is part of the Address date type. The following code returns nothing:
List<Schema.PicklistEntry>  fieldResult = Lead.State.getDescribe().getPicklistValues();
        system.debug('States = ' + fieldResult);
        
        Map<string,string> options = new Map<string,string>();
		for( Schema.PicklistEntry f : fieldResult )
   			{
      			options.put(f.getLabel(),f.getLabel());
                system.debug('State =' + f.getLabel());
   				}

 
Hoping someone can help me.
I need to find a way to add products to other line items without creating them as seperate products.
What I mean, we have products that get added to line items as the primary products. Often, we need to add other products related to these line items, such as install fee's and additional products (almost like a bundle situation).

Currently, we add all of these as individual line items, but this causes issues further down our sales process.

Ive tried creating a Junction object, related lists, lookup fields etc but I cant find anything that works.

We have a visualforce page to select initial product, and we have a custom object called "Provisioning Details" that we use to add all the technical requirements related to a line item.
Ideally, id like either a opplineitem related list within the provisioning detail object, or a way to add a secondary product line item to the primary line item.

Anyone have any suggestions on the best way to do this?
Long story short - previous admin over engineered the Convert Lead to Contact/Account Process many of the moving pieces of it are begining to fail.  Is there a way to completely turn all this off and revert back to the standard SalesForce conversion process? 
I'm reading through the documentation and the example provide shows the following for creating a test class using MockHttpResponse. 
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        
        // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        HttpResponse res = CalloutClass.getInfoFromExternalService();
        
        // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"foo":"bar"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}

Since my class is @future it does not return anything. How do I approach creating the test class for a callout that does not return anything. I've been reading and see the use of Test.startTest() and Test.stopTest() but not sure where to apply that in my test class. 

Thanks for the help. 
HI all,

I have submitted my application code for force.com security scanner and recieved result report with some secutiy SOQL Injection Vulnerability issues. 
below is the one of the example and already i have implemeted escape singlequote also. but it shows again there is SOQL Injection vulnerability issue on below mentioned screen. pleae help me out how to handle this issue.
User-added image

Thanks,
Yarram.
  • August 24, 2016
  • Like
  • 0
Hi , 
I am new to Salesforce Partner community. I am using Salesforce Developer Org.
I do not find a Stand-alone component to choose in Service Not available lookup in Community Management console. Can someone tell me what are all the components to develop in my Org so I can select the correct static resource for Service Not Avaliable in Partner Management. 

Also, Please let me know how to test the Service not available feature for Partner community.
Apex code :
public class myClass {
    public ID seekAccount(String e164) {
        ID ref = NULL ;
        List<List< SObject>> searchList = [ FIND :e164 IN PHONE FIELDS RETURNING Account(ID LIMIT 1) ] ;

        Account[] searchAccounts = (Account[])searchList[0];
        for(Account a : searchAccounts)
        {
            ref = a.ID ;
        }
        return ref ;
    }        
}

Why Apex Test Code don't covere 100%, no " ref = a.ID " ?
@isTest
private class myClassTest {
    @isTest
    static void seekAccountTest() {     
        Id elt = null ; 
        Account a = new Account(Phone='33618181800', Name='33618181800') ;
        insert a ;

        myClass test = new myClass() ;
        elt = test.seekAccount('33618181800')  ;
        System.assertNotEquals(null, elt) ;
        System.assertEquals(a.ID, elt) ;
        elt = test.seekAccount('33618181801')  ;
        System.assertEquals(null, elt) ;
    } 
}

But It work if I use this solution, but I don't wish use it, because I must check severals objects :
 
public class myClass {
        public ID seekAccount(String e164) {
            ID ref = NULL ;
            List<Account> searchList = [ SELECT ID FROM Account WHERE Phone=:e164 ] ;
            for(Account a : searchList)
            {
                ref = a.ID ;
            }
            return ref ;
         }        
    }

 
  • August 08, 2016
  • Like
  • 0
I've got an after update trigger on account that works fine when individual records are updated.  But when I go to do a bulk update on say 200 accounts in my sandbox the trigger is not fired.  

Here's the class that the account after update trigger calls that does the work.  Something is not bulkified in here but I can't see it.  I don't think I've got any queries in for loops which usually is the problem.  What is wrong with this code?
 
public without sharing class RelatedAccountsManager{

    public static void createRelatedAccounts(object[] newTrigger) {

        List<Account> accList = (List<Account>) newTrigger;
            List<Account> accList3 = new List<Account>();
            List<Related_Account__c> raList = new List<Related_Account__c>();
            String thisDUNS;
            Id originalAccount;
                                
            for(Account a: accList){
                thisDUNS = a.Convey_Global_Ultimate_D_U_N_S__c;
                originalAccount = a.Id;
            }
         
            List<Related_Account__c> raListCheck = [SELECT Id, Related_Account__c, Account_Connection__r.Id from Related_Account__c WHERE Account_Connection__r.Id =: originalAccount LIMIT 1];
          
            if(raListCheck.size()>0){
            }else{                
              List<Account> accList2 = [SELECT ID,Type,Convey_Global_Ultimate_D_U_N_S__c FROM Account WHERE Convey_Global_Ultimate_D_U_N_S__c =: thisDUNS AND Convey_Global_Ultimate_D_U_N_S__c != null];        
                for(Account a1: accList2){
                    if(a1.Id != originalAccount && a1.Convey_Global_Ultimate_D_U_N_S__c!= null && accList2.size()>0 && a1.Type != 'Prospect'){
                        Related_Account__c ra = new Related_Account__c();
                        ra.Account_Connection__c = originalAccount;
                        ra.Related_Account__c = a1.Id;
                        raList.add(ra);       
                        accList3.add(a1);             
                     }
                }
             }
             insert raList;  
             
             List<Account> accList4 = new List<Account>();
             
             for(Account a2: accList3){
                accList4.add(a2);
             }
             
             update accList4;
     }   
}

 
Hi,
There is a checkbox in the users profile called "Bulk API Hard delete" which allows deletion of records without storing in recycle-bin.
Is anyone know if this works only through Data Loader, or it works in any Bulk API deletions?
Also, is there a way to have this functionality using Soap API?
Thanks.
Yaon.
Getting error "Loop Variable Mut be of Type Account Line 7".
Here is my code.
No classes named accoutn.

trigger HasWorkPaperManager on Account (after insert, after update) {

    Map<ID, Account> parentAccount = new Map<ID, Account>();
    List<Id> listIds = new List<Id>();
    List<Id> LineItems = new List<Id>();

    for (AMS_Inventory_Rollup__c childObj : Trigger.new) {
        listIds.add(childObj.AccountID__c);
        LineItems.add(childObj.Id);
    }
  
    parentAccount = new Map<Id, Account>([SELECT id,Has_WorkPaper_Manager__c,(Select id from Ams_inventory_rollups__r where name = '511000') FROM account WHERE ID IN :listIds]);
   
    for (AMS_Inventory_Rollup__c AMSInventoryRollup: Trigger.new){
         Account myParentAccount = parentAccount.get(AMSInventoryRollup.Account);
        if(parentAccount.containsKey(AMSInventoryRollup.Account) && parentaccount.get(AMSInventoryRollup.Account).AMSInventoryRollups__r.size() > 0)
        {
            myParentAccount.Has_WorkPaper_Manager__c = true;
        }
        else
        {
            myParentAccount.Has_WorkPaper_Manager__c = false ;
        }
    }
    update parentAccount.values();
 }
Help!  I'm a complete novice for SFDC, but was asked why our API calls had been exceeded.  Now we are unable to do our refresh with HubSpot because the daily limit cut us off.  What would cause my instance of SFDC to suddenly surge on API?  Any assistance greatly appreciated.

Thank you, SFDC Gods and Goddesses.

Kristi the SFDC Newbie
Hello Brilliant People,

This may be a simple question with a complex answer.

Is there a way to update fields that are ONLY blank/null on update or upsert?

I am uploading a set of Contact records and I only want to update the field if it is blank or null. I dont want it to overwrite it if a value exists, if it is a blank value I want it to populate. If the Contact doesnt exist, I want it to create the record with all metadata.

And I dont think this matters, but I dont have the ContactID's so will be keying off of the email address.

Thank you as always for the help!
We currently use an Apex Class that will generate opportunities from Orders that are imported nightly from an SSIS package. Originally the only orders that would generate opportunities were the ones that were of the Sales_Order type, but recently we changed the trigger to also include Service_Orders, so now we have to figure out how to modify our code so that it'll assign the correct opportunity record type based on the order type. The class was written by someone else and I'm REALLY new to coding so I'm hoping you guys can help me. Here is the class:
 
 

https://www.dropbox.com/s/dvotyvt765pv6we/Order_Helper.pdf?dl=0

(I had to do it this way because there's a charater limit.)

If I understand this correctly, the class puts all the orders on a list and runs through the Opportunity Number field. If it has a valid number it'll simply link the Order to the Opportunity with that number. However, if the Order does not have an Opportunity Number, or the number does not match an existing Opportunity's number, it'll generate a new opportunity through the Order Wrapper section. I'm pretty sure that the part that the part that currently sets the record type is the part that I've put in bold letters, my question is: why did they put that section there and not define it in the Order Wrapper section that sets the other Opportunity fields? And, I tried replacing that part with the loop below but got an error saying we had maxed out our SOQL inquiries, how can I rewrite this to work? Or, if you think there's a better way, how would you do it? 
list<Id> oppRT = new list<id>();
            String rtLabel = '';
            for(Order__c xxx:orders ){
            if(xxx.Order_Type__c=='Sales_order' ){
           
            for(RecordType rt : [SELECT Id, Name FROM RecordType WHERE IsActive = true AND SobjectType = 'Opportunity' AND DeveloperName = 'Standard_Quote_Order']){
                oppRT.add(rt.Id);
                         

                rtLabel = rt.Name;
            } 
            }
            else{
            for(RecordType rt : [SELECT Id, Name FROM RecordType WHERE IsActive = true AND SobjectType = 'Opportunity' AND DeveloperName = 'Service_Job']){
                       

                oppRT.add(rt.Id);
                rtLabel = rt.Name;
            } 
            }}
            integer o1=0;
            for(OrderOppWrapper oow : orderOppWrapList){
                if(acctMap.containsKey(oow.order.AccountId__c)){
                    if(oppRt != null){
                        oow.oppty.RecordTypeId = oppRt[o1];
                        o1++;
                    }
                    if(takerId.containsKey(oow.order.Taker__c)){
                        oow.oppty.OwnerId = takerId.get(oow.order.Taker__c);
                    }
                    else if(defaultUser instanceof Id){
                        oow.oppty.OwnerId = defaultUser;
                    }
                    else{
                        oow.oppty.OwnerId = acctMap.get(oow.order.AccountId__c).OwnerId;
                    }                   
                    upsertOpps.add(oow.oppty);
                }
            }
            if(upsertOpps.size() > 0 && isInsert){
                upsert upsertOpps;
            }

 
I'm not sure how to create a formula check box field on the Lead object to say if Profile is ________ & profile is __________, then True.  
So, I need the check box to be checked when a particular Profile creates the lead. 
Hello,

I've created a batch job where I am updating some Account records.  In the job I am trying to run a Database.update call passing false as the 2nd parameter to enable saving of successful records even if some of them fail.  The problem I am having is that when 1 of the records fails due to a validation error, it is throwing an exception and not saving the rest of the records.  The documentation states this should not occur and that instead the records that didn't fail should be saved and the failed records be returned from the method call in a Database.SaveResult[] array.What is even stranger is that I have wrapped the Database.update call in a try..catch block and the exception isn't even caught.  I am thinking there is a bug somewhere in the platform causing this not to work as it previously used to.  Here is the code for the execute method in my batch job:
 
public void execute(Database.BatchableContext BC, List<sObject> recs) {

        for (sObject sObj : recs) {
            Account acct = (Account)sObj;
            acct.Growth_Rate__c = 0;
        }
        
        try {
            // Update Accounts
            Database.SaveResult[] srList = Database.update(recs, false);            
            
            Set<Id> errorIds = new Set<Id>();
            for (Database.SaveResult sr : srList) {
                if (!sr.isSuccess()) {
                    errorIds.add(sr.getId());
                }
            }
            System.debug('errorIds: ' + errorIds);
        }
        catch (Exception ex) {
			System.debug('Exception thrown: ' + ex.getMessage());
        }
}

Any help would be greatly appreciated.

Thanks,
Al