• Terence_Chiu
  • SMARTIE
  • 815 Points
  • Member since 2015
  • Adviceforce


  • Chatter
    Feed
  • 27
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 127
    Replies

I have a VF page that uses the standardController for Opportunity. Is there a way, without writing an extension class, to get the Contact Name from the Contact Roles related list?

I found a solution for my email template that works like a charm (see below), but I'm struggling getting it to work on the VF page that is used by a custom button. I'm a developerless novice admin, pardon my ignorance. 

 

Working in VF Email Template: 

<apex:repeat value="{!RelatedTo.OpportunityContactRoles}" var="ContactRole"> {!ContactRole.Contact.Name}</apex:repeat>

Hello,

I've enabled the object in my DEV enviornment and taken a look at the metedata.  Does not appear to be a property on the fields for Tracking History.

<fields>
<fullName>SplitPercentage</fullName>
</fields>

Can historty tracking be enabled for splits? 

Scenario - User sets it to 50/50 on day 1 and 6 months later changes it to 75/25. 

I know we can put a valdiation rule that prevents editing it after being closed.

Thanks!,
Joseph
 
I'm trying to figure out how to update a field on a custom object, "Vendor Products", when an opportunity is closed. There is a lookup field on the opportunity that attaches it to the Vendor Product and the opportunities show up on a related list on the Vendor Product object. Is there an effective way to do this?
Hello

My users often use the clone case button.  Unfortunately, the cloned cases have fields populated that should not be when a case is first created.

Currently, I clear some of the fields using the URL on a custom button but I would prefer to create a VF page that mimics my case page layout. What is the easiest way to basically duplicate my Standard case page layout in VF for my new Clone case button?

Thank you in advance for your time.

B
I want to restrict the following characters ‘ “ , * % @ and if possible remove any extra spaces at the end of the field. I've found validation rules for allowing characters but none for just restricting, I don't really want to have to input every single charachter other than those listed above. (infact when I try to do that I get syntax errors). Any guidence would greatly be appreciated.
I'm new to SalesForce and new to using the SOAP API to create a record. I am trying to create a Case and link it to an Account, but nothing I have tried has worked yet. Error received:

"ERROR creating record: Field name provided, Id is not an External ID or indexed field for Account"

I have read the documentation on "create() and Foreign Keys" and followed the example code. (This is in Java.) As far as I can tell the Account Id field is what is used to link the Case to the Account. If I query the Case for Case.AccountId equal to the value in Account.Id I get a list of Case records. But when I try to create a Case with the Account Id I get the error shown.

I have used describeSObjects() to look at all the fields in Account and Case, but I don't see anything that indicates external id or index. I thought that if the Case records are already linked by Account Id then it would be set, but that is not seeming to be true. How can I find this out?

Thanks,
Peter
Hi,

I'm looking to create a custom field on the contact object which will store the last completed event date logged against the record.

I've tried to create this through the use of formula fields and the 'last activity date' but unfortunatly this brings through the date of previous tasks and any future events scheduled. Can someone recommend a solution? Appreciate this may only be accomplished through APEX.
 
Hi there - is it possible to use a wildcard within a contains function? I can't seem to find much on the subject other than where wildcards are related to SOQL or search API. I'd like to use it in a class like this:

if (myAtt.Name.contains('Project' + '%' + 'Budget')) {                    
                myAtt.Name = myAcc.Name + '_' + myAtt.Name;               
                }

These are attachments and I'm trying to find string which contain the word 'Project' and 'Budget' but I need to control for cases where the words are separated with just a space, maybe an underscore, or maybe no spaces at all. I've tried the above syntax and it doesn't work for me. 
Hey Folks,
I'm using the SOAP API to enter Contacts into PropertyBase. My script is working except for a custom field called "Stage" I've created.
 
Fatal error: Uncaught SoapFault exception: [sf:INVALID_FIELD] INVALID_FIELD: No such column 'Contact.Stage__c' on entity 'Contact'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. in /[REMOVED]/soapclient/SforceBaseClient.php:499 Stack trace: #0 //[REMOVED]//soapclient/SforceBaseClient.php(499): SoapClient->__call('create', Array) #1 //[REMOVED]//soapclient/SforceBaseClient.php(499): SforceSoapClient->create(Object(stdClass)) #2 //[REMOVED]//soapclient/SforcePartnerClient.php(99): SforceBaseClient->_create(Object(stdClass)) #3 //[REMOVED]/.php(120): SforcePartnerClient->create(Array, 'Contact') #4 //[REMOVED]/.php(60): creat in //[REMOVED]//soapclient/SforceBaseClient.php on line 499
As you can see I have a custom field called Contact.Stage__c that is not being recoginzed.

From all my research this has to do with "field level security" but everywhere I could find all the boxes are checked to "visible".

Where exactly should I be looking for these settings or what other things can I check?
Hi All,

I am writing a class to send an email follow-up when a community user hasn't logged in in 2 weeks. I think I have the class how it should be, but cannot figure out how to get the test class to cover the code.  

The class:
public class EmailFeedbackSurvey {
    public static void getFeedback(){
        
        //date calculation for soql
        date d = system.today().addDays(-14);
        
        //list for feedback survey
        User[] u = [SELECT Id, Email, Contact.Name FROM User 
                    WHERE ProfileId = '00e16000000S7BU' AND LastLoginDate = Null];
            User n = new User();
            u.add(n);
        
        List<Messaging.SingleEmailMessage> feedbacks = new List<Messaging.SingleEmailMessage>();
        
         
        for(Integer i= 0; i< u.size(); i++){
            Messaging.SingleEmailMessage feedback = new Messaging.SingleEmailMessage();
                List<String> sendTo = new List<String>();
                sendTo.add(n.Email);
                feedback.setToAddresses(sendTo);
                feedback.setReplyTo('info@digitalonramps.com');
                feedback.setSenderDisplayName('Digital On-Ramps');
                feedback.setTemplateId('00X17000000Dqey');
            
            feedbacks.add(feedback);
            
             }
        Messaging.sendEmail(feedbacks);
    }

}

The test class: 
@isTest public class EmailFeedbackSurveyTest {
    @isTest public static void emailUser(){
        Id p = [SELECT id FROM Profile WHERE name = 'Learner Profile Community User'].id;
        
        Account acct = new Account(name= 'TestAcct');
        insert acct;
        
        Contact con = new Contact(LastName = 'Learner', AccountId = acct.Id);
        insert con;
        
        User u = new User(alias = 'learner1', email = 'learner@testing.org', emailencodingkey='UTF-8', lastname='Learner', languagelocalekey='en_US',
                localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                ContactId = con.Id,
                timezonesidkey='America/Los_Angeles', username='tester@noemail.com');
        insert u;
        
                
        System.runAs(u){
            EmailFeedbackSurvey test = new EmailFeedbackSurvey();
            
            
            
        }

        
    }

}

I'm pretty sure something needs to happen after 
EmailFeedbackSurvey test = new EmailFeedbackSurvey();
but I'm not sure what. I started coding last week, so I think I'm in a bit over my head with this. 
I have a custom object which I am importing into a data table.  What I want is for each row to have a background color that is based on the Edibility__c database field. 

Any suggestions?

Here is the IF statement that I am trying to use.  I get an error if I put this into the Search Results block or if I try to attach it to the pageBlockTable tag (the latter because it doesn't recognize the variable name.

            <apex:outputPanel styleClass="{!IF(bol.Edibility__c == 1,'red',
                                                       IF(bol.Edibility__c  == 2,'yellow',
                                                       IF(bol.Edibility__c  == 3,'blue',
                                                       'green')))}">

Here is the code for the table.

            <apex:pageBlock title="Search Results"  id="bolete_list">
                <apex:outputText >{!showResultSize} of {!showRecordSize} records displayed</apex:outputText>
                <br/>
                <apex:pageBlockTable value="{! Boletes }" var="bol" style="width: 100%">
                    <apex:column width="75">
                        <apex:outputLink value="/apex/boleteDetailView?id={!bol.Id}" id="viewLink">
                            View
                        </apex:outputLink>
                    </apex:column>
                   
                    <apex:column width="75">
                        <apex:image id="imageURL" url="{!bol.ImageURL__c}" height="75"/>
                    </apex:column>

                    <apex:column value="{! bol.genus__c }">
                        <apex:facet name="header">
                            <apex:commandLink action="{! sortByGenus }" reRender="bolete_list">Genus
                            </apex:commandLink>
                        </apex:facet>
                    </apex:column>
                   
                    <apex:column value="{! bol.species__c }">
                        <apex:facet name="header">
                            <apex:commandLink action="{! sortBySpecies }" reRender="bolete_list">Species
                            </apex:commandLink>
                        </apex:facet>
                    </apex:column>
                   
                    <apex:column value="{! bol.Common__c }"/>
                </apex:pageBlockTable>
            </apex:pageBlock>
        </apex:pageBlock>
I have a Zipped Static Resource which includes a .js file and several images.  The images load fine from the HTML with following :
<img src = "{!URLFOR($Resource.images,'img/')}ToolBumper24S7DS120x140.png"/>

but the following code in Javascript produces an undefined error.

image.onload = image.addEventListener("load", function(){                                 
          canvas.drawImage(image, x, y, w, h);
          }, false);
          
image.onload =  image.addEventListener("error", function(e){
          console.log("error loading image " + is + "  " + JSON.stringify(e) );
});

image.src = "{!URLFOR($Resource.images,'img/')}ToolBumper24S7DS120x140.png";

Why does the image not load?

 
Hello, 
I am trying to create a field that displays week of the year that the lead was created based off the CreatedDate (Date/Time) Field.

I think I need to first convert the CreatedDate (Date/Time) to a (Date) field and then use a formula to change the date into a Week Number.

The output of the formula should be a number (between 0-52).

This is what I'm working with right now... but this formula has errors:

DAY( DATEVALUE( date/time ))
IF(
2
  CEILING( ( date - DATE( YEAR( date ), 1, 1) + 1) / 7) > 52,
3
  52,
4
  CEILING( ( date - DATE( YEAR( date ), 1, 1) + 1) / 7)
5
)

Any help would be greatly appreciated! 
Hey all, 
I'm working a bit of code to automatically re-add products to an opportunity if they get deleted as a result of the user changing the pricebook.  I experimented with trying to clone the OLIs in a beforeDelete trigger, but couldn't get that work, I assume becuase updating the pricebook deleted the newly created clones in addition to the old products.

Instead I've built a custom object called OLI_Clone__c for which records are inserted every time a new OLI is added to an oppty and then deleted later when the oppty goes to closed won or closed lost.  Basically, when the pricebook updates on the oppty, the code queries back to the OLI_Clone__c records associated with the oppty and then uses the data stored there to recreate the OLIs.  The biggest challenge is that I can't create a lookup to ProcebookEntry on a custom object so I had to create a lookup to Product and then use a combination of the Opportunity's new Pricebook Id and the OLI_Clone__c's product Id to query for the correct PricebookEntry.  

I've been able to get a list of PricebookEntryIds, but I can't figure out how get the correct PricebookEntryId for each OLI_Clone__c without querying for it inside of my for loop, which is obviously a big no no.  I do know that I should be using a map, but I am relatively novice coder, and I just can't seem to get the syntax right.

Thanks in advance for your help!

I've pasted my service class below with a few comments:
public with sharing class autoAddProductsAfterPBChange {

//create a filter to listen for a change in the pricebook below
      public static list<opportunity> filterOpp(map<id, opportunity> oldMap, list<opportunity> newList) {
        list<opportunity> temp=new list<opportunity>();
        for (opportunity newOpp : newList){
            if (oldMap.get(newOpp.id).PriceBook2Id != newOpp.PriceBook2Id){
                temp.add(newOpp);
            }
        }
        return temp;
    }        

//find the pricebook entries and recreate the OLIs   
    public static void autoAdd(list<Opportunity> opps){
        Opportunity opp = new Opportunity(); 
        Pricebook2 pb = new Pricebook2();    
        for(Opportunity opp2 : opps){
            opp.id = opp2.Id;
            pb.id = opp2.Pricebook2Id;
        }
        list<OLI_Clone__c> olics = [SELECT Quantity__c, Additional_Discount_off_List__c, Manual_Discount__c, Opportunity__c, Product__c, Sales_Price__c, Service_Term_in_Months__c
                                                     FROM OLI_Clone__c
                                                     WHERE Opportunity__c =: opp.id];
        list<Id> prodids = new list<Id>();
        for(OLI_Clone__c olicprod : olics){
            prodids.add(olicprod.Product__c);
        }
        List<PricebookEntry>pbeids = [SELECT Id, Product2Id
                           			         FROM PricebookEntry
                                                         WHERE Product2Id in: prodids AND Pricebook2Id =: pb.id];
 		Map<Id, PricebookEntry> pbeMap = new Map<Id, PricebookEntry>(pbeids);  // Is this map correct? 
 		list<OpportunityLineItem>toInsert = new list<OpportunityLineItem>();
        for(OLI_Clone__c olic : olics){
            if(pbeMap.containsKey(olic.Product__c)){
                OpportunityLineItem oli = new OpportunityLineItem();
                PricebookEntry pbe = pbeMap.get(); // I know I need to be "getting" something here but I'm not sure how to structure the syntax, and I'm not sure that my map above is configured correctly either.  Basically I need to get the correct PricebookEntryId based on the Product__c field on the OLI_Clone__c in this loop and the parent Opportunity's pricebook.
                oli.Quantity = olic.Quantity__c;
                oli.UnitPrice = olic.Sales_Price__c;
                toInsert.add(oli);
            }
        }
        insert toInsert;
	}

}




 
I'm looking to track/count each time a custom button is clicked. i.e. each time Send Quote is clicked, i'd like to see the count go up incrementally. *This custom button is an onclick javascript. Thank you in advance. 
Need to route the user to a visualforce page for creating multiple child records on save of parent record.

Summary
  • Three objects involved: Opportunity, Demographic, and Quota. 
  • One Opportunity has Many Demographics
  • One Demographic has Many Quotas
  • I've created a visualforce page where I add many Quotas to the Demographic at once. Currently this is launched from a custom button on the Demographic Detail Page.
    • Page Name = addQuotas
    • Page has a standard "add row"/"delete row" function to create a Quota record each row from custom controller
    • I pass multipe details from the parent Demographic onto each Quota row through an extension
  • I've created a visualforce page to override the standard new/edit Demographic layout so I can build a custom save button to route to the addQuotas page.
    • Page Name = addDemographic, uses a standard controller, no extensions at the moment
Question
What I want to have happen is when saving the Demographic, the user is immediately taken to the addQuotas page as if they had clicked the button on the detail page. I'm having difficulty making any of this work, trying custom buttons from the Opportunity and hacking the SaveURL, and I'm just not having luck saving the Demographic, grabbing the Id of that Demographic, and then going to the addQuotas page with that Demographic Id in tow. 

What do I add to the Save action on the addDemographic visualforce page to then route to the addQuotas page for THAT Demographic?

Basically, I want on Save of Demographic to automatically go here: /apex/addQuotas?id={!Demographic__c.Id}&retURL={!Demographic__c.Id}

Code and Pictures:
addDemographic page
<apex:page standardController="Demographic__c" tabStyle="Demographic__c">
     <apex:sectionHeader title="Edit Demographic" subtitle="New Demographic"/>
        <apex:form >
                <apex:pageBlock title="Edit Demograhic" mode="edit">
                    <apex:pageblockButtons >
                        <apex:commandButton action="{!save}" value="Add Quotas"/>
                    </apex:pageblockButtons>
                    <apex:pageblockSection title="Demographic Information" columns="1">
                        <apex:inputfield value="{!Demographic__c.Opportunity__c}"/>
                        <apex:inputfield value="{!Demographic__c.Qualification__c}"/>
                    </apex:pageblockSection> 
                </apex:pageBlock>
        </apex:form>

</apex:page>

addQuotas page:
<apex:page standardController="Demographic__c"
            extensions="EditableQuotaListExtension"
            showHeader="true" 
            sidebar="false"
            title="Edit Quota">
    <apex:form >
    <apex:pageMessages id="messages"/>
    <apex:pageBlock title="Edit Quotas">
      <apex:pageBlockButtons >
        <apex:commandButton value="Cancel" action="{!cancel}" />
        <apex:commandButton value="Save" action="{!save}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection title="Demographic Information" collapsible="false">
      <apex:outputLink value="/{!Demographic__c.Id}" target="_blank">{!Demographic__c.Name}</apex:outputLink>
        <apex:pageBlockSectionItem >
          <apex:outputText value="{!Demographic__c.QualificationName__c}" />
          <apex:outputText value="{!Demographic__c.Qualification_Text__c}" />
        </apex:pageBlockSectionItem>
      </apex:pageBlockSection>
      <apex:pageBlockSection id="childList" columns="1" title="Quotas" collapsible="false">
        <apex:variable var="rowNum" value="{!ZERO}" />
        <apex:outputLabel value="No Quotas currently exist. Click below to Add." rendered="{!NOT(hasChildren)}"/>
        <apex:pageBlockTable value="{!children}" var="quota" rendered="{!hasChildren}">
        <apex:column headerValue="Condition">
          <apex:inputField value="{!quota.Condition__c}"/>
        </apex:column>
        <apex:column headerValue="Option">
          <apex:inputField value="{!quota.Condition_Option__c}"/>
        </apex:column>
        <apex:column headerValue="Description">
          <apex:inputField value="{!quota.Description__c}"/>
        </apex:column>
        <apex:column headerValue="Quota Amount">
          <apex:inputField value="{!quota.Quota_Amount__c}" />
        </apex:column>        
        <apex:column headerValue="%/#">
          <apex:inputField value="{!quota.Quota_Calculation_Type__c}"/>
        </apex:column>
        <apex:column headerValue="Demographic">
          <apex:inputField value="{!quota.Demographic__c}"/>
        </apex:column>
        <apex:column headerValue="Qualification">
          <apex:inputField value="{!quota.Qualification__c}"/>
        </apex:column>
          <apex:column headerValue=" ">
            <!-- This is the second half of the trick to keep track
                  of your row index for deletion. -->
            <apex:variable var="rowNum" value="{!rowNum + 1}" />
            <apex:commandLink value="Delete" action="{!removeFromList}" rerender="childList, messages" immediate="true">
              <apex:param name="removeIndex" assignTo="{!removeIndex}" value="{!rowNum}" />
            </apex:commandLink>
          </apex:column>
        </apex:pageBlockTable>
        <apex:commandButton value="Add Quota" action="{!addToList}" rerender="childList, messages" immediate="true" />
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>

addQuotas Extenstion (grabbing details from Demographic parent):
public with sharing class EditableQuotaListExtension extends EditableQuotaList
{


 public Demographic__c mydemo {get; private set;}

  public EditableQuotaListExtension(ApexPages.StandardController stdController) 
  {
    super(stdController);

    this.mydemo = [SELECT Id,
                              Name,
                                Qualification__r.Name
                            FROM Demographic__c
                            WHERE Id =: stdController.getRecord().Id];
    
    this.childList = [SELECT Id,
                          Condition__c,
                          Description__c,
                          Quota_Amount__c,
                          Quota_Calculation_Type__c,
                          Condition_Option__c,
                          Qualification__c,
                          Demographic__c
                      FROM Quota__c
                      WHERE Demographic__c =: mysObject.Id];
  }

  /*
   * This method is necessary for reference on the Visualforce page, 
   * in order to reference non-standard fields.
   */
  public List<Quota__c> getChildren()
  {
    return (List<Quota__c>)childList;
  }


  public override sObject initChildRecord()
  {
    Quota__c child = new Quota__c();
    child.Demographic__c = mydemo.Id;
    child.Qualification__c = mydemo.Qualification__c;
    child.Quota_Amount__c = 100;
    child.Quota_Calculation_Type__c = '%';
    
    return child;
  }
}

View of the addQuotas page so you get the idea of the page:
User-added image


Thank you in advance!!

 
Hi Everyone,

I am having an issue getting child recording showing up on a visual force page

Here is my current controller and visual forcepage code


public class MRAController { List<Account> Acts = [Select a.Name, (Select Id , Name, CreatedDate From Opportunities ORDER BY CreatedDate DESC LIMIT 1), (Select Title, CreatedDate From NotesAndAttachments ORDER BY CreatedDate DESC LIMIT 1), (Select Description, CreatedDate From ActivityHistories ORDER BY CreatedDate DESC LIMIT 1) From Account a WHERE OWNERID ='00570000003FI8tAAG' LIMIT 1]; List<Account> Acts2 = [Select a.Name, (Select Id, Name, CreatedDate From Opportunities ORDER BY CreatedDate DESC LIMIT 1), (Select Title, CreatedDate From NotesAndAttachments ORDER BY CreatedDate DESC LIMIT 1), (Select Description, CreatedDate From ActivityHistories ORDER BY CreatedDate DESC LIMIT 1) From Account a WHERE OWNERID ='00570000002ZCzzAAG']; public List<Account> getActs(){ return Acts; } public List<Account> getActs2(){ return Acts2; } }

<apex:page sidebar="false" controller="MRAController" >
<apex:form >   
 
    <apex:tabPanel activeTabClass="Blue" switchtype="ajax" >
    <apex:tab label="Jim Bridger" LabelWidth="100" id="tb1"><apex:pageBlock >
    <apex:pageBlockTable value="{!Acts}" var="a" ID="table">
    <apex:Column value="{!a.ID}" Width="120"/>
    <apex:Column value="{!a.Name}"/>
    </apex:pageBlockTable>
    </apex:pageBlock>
    </apex:tab>
 <apex:tab label="Jim Bridger 2" LabelWidth="100" id="tb2">
    <apex:pageBlock >
    <apex:PageBlockTable value="{!Acts2}" var="b">
    <apex:column value="{!b.ID}"/>
    <apex:column value="{!b.Name}"/>
    </apex:PageBlockTable>
    </apex:pageBlock>
    </apex:tab> 


</apex:tabPanel>
    </apex:form>
</apex:page>

I am having an issue displaying the opportunites

Right now I can only get the Account Information to display and can not get the Opportunity Information to display

Account Name - Opportunity ID - Opportunity Name - Note Title - Created Date - Activity Title - Created Date

 
Hello!

I am trying to raise my code coverage for a trigger that picks up a converted lead, and creates a few records and eventually will send out an email to a client.  however, I cannot get my code over 57% and wanted to turn to the Community for assistance!  Any help you can provide would be awesome!  Please see the trigger below:
 
trigger createcontract on Lead (after update) {


//trigger InsertContract on Opportunity (after insert, after update) {

  List<Sertifi2_0__TestContract__c> Childs = new List<Sertifi2_0__TestContract__c>();
  
  PageReference pdf = Page.ExcelPDF;

  
  for(lead o : trigger.new)
  
    {
    
  // if(trigger.isupdate){
   
    if(o.LeadSource=='[Liberty Reseller]'&& o.isconverted==True){
    
       Sertifi2_0__TestContract__c Child = new Sertifi2_0__TestContract__c ();
       Child.Sertifi2_0__Opportunity__c = o.ConvertedOpportunityId;
       child.Sertifi2_0__Account__c=o.ConvertedAccountId;
       child.Sertifi2_0__Settings__c='Settings';
       Child.Name = 'New Contract'; 
       child.Sertifi2_0__Contact__c=o.Convertedcontactid;
       Childs.add(Child);     
          

    insert Childs;


    Sertifi2_0__EDocument__c signDoc = new Sertifi2_0__EDocument__c(
    Sertifi2_0__TestContract__c = child.id,
    Sertifi2_0__Name__c = 'FurstPerson Agreement for '+ child.Sertifi2_0__Contact__r.Name+'.pdf',
    //Sertifi2_0__Sertifi_ID__c = 'qwerty',
    Sertifi2_0__Number_Signed__c = 0,
    Sertifi2_0__Document_Type__c = 'Signing Document');
    
insert signDoc;

if (!Test.isRUnningTest()) {
            Document thedoc = [select body from document where Name = 'Sertifi Contract1'];
            //String pdfBody = EncodingUtil.urlEncode(thedoc.body.toString(), 'UTF-8');


Contact tempContact = [select id,name,email from Contact where Id =: o.Convertedcontactid][0];
Sertifi2_0__ContractContactJunction__c signer = new Sertifi2_0__ContractContactJunction__c(
    Sertifi2_0__Contact__c = tempContact.id,
    Sertifi2_0__TestContract__c = child.id,
    Sertifi2_0__Signer_Order__c = 1,
    
    Sertifi2_0__Level_Name__c = '1st Signer',
                Sertifi2_0__Email__c = tempcontact.email);
insert signer;

Attachment attach = new Attachment();
           //AttachedContentDocument attach = new AttachedContentDocument();
           //attach.ContentDocumentId = '015J0000000gLXk';
            attach.Body = thedoc.body;
            attach.name = 'Furst Agreement for ' + child.Sertifi2_0__Contact__r.Name+'.pdf';
            attach.ParentId = signDoc.Id;
            //attach.
            insert attach;
            
            Sertify_Methods.callSertifi(child.Id);

}
}
}
}

And the test class:
@isTest (SeeAllData=true)
public class Contractreatetestclass{
    static Document document;
    
    static {

    document = new Document();
    document.Body = Blob.valueOf('Some Text');
    document.ContentType = 'application/pdf';
    document.DeveloperName = 'my_document';
    document.IsPublic = true;
    document.Name = 'Sertifi Contract1';
    document.FolderId = [select id from folder where name = 'Public Documents'].id;
    insert document;

  }
  
  static testMethod void ContractreatetestclassMethod(){
  
  Test.startTest();
  
    Lead l = new Lead(FirstName='test',LastName='test',
    Company='test',
    LeadSource='[Liberty Reseller]');
    Insert L;
    
    Database.LeadConvert lc = new database.LeadConvert();
    lc.setLeadId(l.id);
    lc.setDoNotCreateOpportunity(false);
    lc.setConvertedStatus('Qualified');

    Database.LeadConvertResult lcr = Database.convertLead(lc);
    System.assert(lcr.isSuccess());

    Sertifi2_0__TestContract__c Contract = new Sertifi2_0__TestContract__c ();
       Contract.Sertifi2_0__Opportunity__c = l.ConvertedOpportunityId;
       Contract.Sertifi2_0__Account__c=l.ConvertedAccountId;
       Contract.Sertifi2_0__Settings__c='Settings';
       Contract.Name = 'New Contract'; 
       Contract.Sertifi2_0__Contact__c=l.Convertedcontactid;
       insert contract;


    Contact tempContact = new Contact(FirstName='test',LastName='Test',AccountId=l.convertedAccountId);
    
    insert tempContact;
    
    Sertifi2_0__EDocument__c signDoc = new Sertifi2_0__EDocument__c(
    Sertifi2_0__TestContract__c = contract.id,
    Sertifi2_0__Name__c = 'FurstPerson Agreement for '+ contract.Sertifi2_0__Contact__r.Name+'.pdf',
    //Sertifi2_0__Sertifi_ID__c = 'qwerty',
    Sertifi2_0__Number_Signed__c = 0,
    Sertifi2_0__Document_Type__c = 'Signing Document');
    
    insert signDoc;


    Sertifi2_0__ContractContactJunction__c signer = new Sertifi2_0__ContractContactJunction__c(
    Sertifi2_0__Contact__c = tempContact.id,
    Sertifi2_0__TestContract__c = Contract.id,
    Sertifi2_0__Signer_Order__c = 1,
    
    Sertifi2_0__Level_Name__c = '1st Signer',
                Sertifi2_0__Email__c = tempcontact.email);
    insert signer;
    
    Attachment attach = new Attachment();
           //AttachedContentDocument attach = new AttachedContentDocument();
           //attach.ContentDocumentId = '015J0000000gLXk';
            attach.Body = document.body;
            attach.name = 'Furst Agreement for ' + Contract.Sertifi2_0__Contact__r.Name+'.pdf';
            attach.ParentId = signDoc.Id;
            //attach.
            insert attach;
            

    Test.stopTest(); 


    
   }}

Where am I failing to build out the necessary components to be successful with this code?  Thank you for any support and have a great day!

Kevin Chiles
 
Hi i'm trying to create a validation that only allows to save text field that contains Numbers [0-9] and Commas [,] any other characters or letter should fail to validate.

I would appreciate if anyone can help , as I was not able to figure it out

Thank you in advance
Hi All,

I ran into an issue in my production org that did not occur in sandboxes so wanted to see if anyone ran into this issue.

I have built a lightning app with lightning components and I am loading it onto a visualforce page using lightning out. The visualforce page is used within a Force.com site. When loading the page either via the vf page while logged into salesforce or from the public url of the site the following error is written to the brower's console log.

XMLHttpRequest cannot load https://XXXXX.lightning.force.com/c/XXXXXXXX.app?aura.format=JSON&aura.formatAdapter=LIGHTNING_OUT. Redirect from 'https://XXXXX.lightning.force.com/c/XXXXXX.app?aura.format=JSON&aura.formatAdapter=LIGHTNING_OUT' to 'https://XXXXXX.my.salesforce.com/visualforce/session?url=https%3A%2F%2FXXXXX.lightning.force.com%2Fc%2FXXXXXXXX.app%3Faura.format%3DJSON%26aura.formatAdapter%3DLIGHTNING_OUT' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://XXXXXXX.secure.force.com' is therefore not allowed access.

I've masked the domain names and app component names, however, I have added the urls referenced in the above message in the CORS whitelist settings. I did the same in the sandboxes and was able to load the page without any issue. Could there be something I could be missing?

Thanks in advance!
 
Following up from this Question: https://success.salesforce.com/answers?id=9063A000000iRnpQAE

I am trying to track the most current campaign on a lead record when a lead status changes. We built a trigger already that tracks the date a lead status changes (below), but now I want to also track the current (or newest) campaign on the lead record.  Can I do this with a trigger?

Here is the current trigger in place that tracks the date a lead changes status:
// fills in the Recycle_Conversion_Date__c field with today's date
// whenever a lead's status is updated from Recycle to
// A, B, C, or TQL status.
trigger RecycleConversionDate on Lead (before update) {
  for (Lead oldLead : Trigger.old) { 
    Lead newLead = Trigger.newMap.get(oldLead.Id);
    if (oldLead.status == 'Recycle' && 
      (newLead.status == 'A- Lead Pursuing' || 
       newLead.status == 'B- Lead Contacted' || 
       newLead.status == 'C- Lead Responded' ||
        newLead.status == 'TQL - Totally Qualified Lead')) {
         newLead.Recycle_Conversion_Date__c = System.today();
    }
  }
}

Can we change this trigger to insert the most recent campaign on the lead record instead of the date?  I can't seem to find the proper Apex value that would give me a campaign name on a lead record. (aka, I am not a developer)

Use Case... when a lead changes from Recycle to C- Lead Responded, what is the newest, or most current campaign name on that lead record.  I don't really care about the campaign member status, I just want to know the name of the campaign at the time the lead status changes.

Hope this makes sense!  Thanks for the help!
Hey, So I've been all over the forums and cannot seem to find the solution for this or where I am going. If anyone could shed any light on this it would be much appreciated.

What am trying to achieve: Validation of Picklist which cannot be (Blank) Here is what I've got so far:

AND ( 
$Label.Validation_Switch = "ON", 
Cancelled__c = True, 
(Case_ID__r.UK_Canada__c)= "UK", 
ISBLANK(Reason_for_Cancellation__c), 
TEXT(Reason_for_Job_Cancellations__c) <> "None", 
TEXT(Drill_Down_on_cancelled_reason__c) <> "None")​

Okay so the top couple of lines run and work absolutly fine but then when I place those 2 extra requirements in it accepts the code but validate anything. 

I've tried a few different things this is the last thing I tried and where I am currently stuck!

Any help would be massive on this.
Thanks 

I have a VF page that uses the standardController for Opportunity. Is there a way, without writing an extension class, to get the Contact Name from the Contact Roles related list?

I found a solution for my email template that works like a charm (see below), but I'm struggling getting it to work on the VF page that is used by a custom button. I'm a developerless novice admin, pardon my ignorance. 

 

Working in VF Email Template: 

<apex:repeat value="{!RelatedTo.OpportunityContactRoles}" var="ContactRole"> {!ContactRole.Contact.Name}</apex:repeat>

We have a web-to-lead setup to create a new lead whenever a new Quote Request is made by web visitors regardless of where an email already exists in our SF instance. A new lead received from an existing customer will be treated as a new lead, and we would like to assign those existing customers to the same owner who service them before.

We've written a "before insert" trigger to search Account, Contact and non-converted Lead; and assign the newly created lead to the original owner. The trigger is working fine (from reviewing debug log).

We also have a Lead Assignment Rule, which uses "Lead Number" and "Round Robin ID" to assign leads to a selected few sales reps. The round robin rule works fine for new leads (non-duplicating email addresses), but for those existing emails assigned by the trigger (above) is reassigned by the Lead Assignment Rule.

Is there a way to create a Lead Assignment Rule, which bypasses the assignment if Owner already exists? We would like to keep the owner if it is already assigned by a trigger, and only assign via Round Robin rule if no owner is assigned by the trigger.

Any pointer is greatly appreciated.
 
I'm building a VisualForce page for a custom profile tab, and I need to retrieve the email address of the user being viewed (not the logged in user).  I'm hoping to avoid creating a custom controller and was trying to find a merge field that would retrieve the email address of the user being viewed.  Unfortunately {!user.email} just returns an empty string.  Is there a field I can use or do I have to create a custom controller?
Newbie that needs help.  For leads we have an "unassigned" queue.  From that queue out of the box as you all know we can check the check box next to the leads and then hit change owner which takes you to a new page to choose the new owner and then you hit ok and it changes the owner.  I want to streamline that so we check the box next to the leads and then hit a button with the salespersons name on it and it magically changes the owner to that sales person.  I am assuming from my limited knowledge I could do this with a custom button that executes OnClickJavaScript.   Problem is I have zero idea how to write the needed Javascript.  Can anybody assist?
I am aware that you can add a custom button to the TOP of a related list, but what if I want a button / link that calls a FLOW from each of the line items in the related list?  I have tried creating a hyperlink formula field with the flow but it is not recognising the URL.  Is there any other way to achieve this?
I was doing a APEX Tutorial and my first task was to write a trigger using my Salesforce Developer Org and received the following error:

Error: Compile Error: expecting an equals sign, found '1' at line 2 column 14

Any ideas would be appreciated.

[Hello World Trigger]

trigger HelloWorld on Lead (before update) {
    for (Lead 1 : Trigger.new) {
        1.FirstName = 'Hello';
        1.LastName = 'World';
    }
}
Hello,

I am deploying a change set to production and it won't pass validation. I had no issue deploying to other sandboxes. Here are the errors: User-added image
varCaseID is definitely referenced in the flow. Any thoughts as to what might be causing the issue?
 
I have a trigger already mostly written that relates a lead to a parent account object based on 2 criteria. The first is it's linkedin company id. So some of our leads and accounts have as a record their database id on linkedin. If a lead LID matches an account LID I want the lead to update it's related account to be that account with the same id. The SECOND criteria is name, so if the names match- the lead will update with an account with a matching name. I only want a name match search to happen if the id match doesn't happen. I'll post below what I have so far.
 
trigger updateRelatedAccount on Lead (before update) {
    set<string> accNames = new set<string>();
    set<Decimal> accLIDs = new set<Decimal>();
        for(Lead ld : Trigger.New){
        	accNames.add(ld.Company);
            accLIDs.add(ld.Company_ID__c);
        }
    
    

        list<Account> accs = new list<Account>([Select Id,Name,LinkedIn_Id__c from account where name=:accNames or LinkedIn_Id__c=:accLIDs]);
        map<String,id> mapaccs = new map<String,id>();
    	map<Decimal, id> mapids = new map<Decimal, id>();

        for(Account ac : accs){
        	mapaccs.put(ac.Name,ac.Id);
            mapids.put(ac.LinkedIn_Id__c,ac.Id);
        }

        for(Lead lds : Trigger.New){
            if (lds.Company_ID__c < 0) {
                lds.Related_Account__c = mapids.get(lds.Company_ID__c);
            } else {
                lds.related_account__c = mapaccs.get(lds.company);
            }
            
            
        	
        }
  }

I was patting myself on the back because I really REALLY thought this would work. It seems like it would. The mapids object should contain the LID as the key and then the related account id as the Value pair. 

If I do a name match it works perfectly. But if I try to do a LID match it fails. Can anyone help me out? Thanks!
Hey guys,

I need a APEX Trigger to link an Account to Lead in Related Field if Name or email domain match an Existing Account. 

I look at both the Company name on the lead and check that for a match with the account name or the email domain on the lead matches with the website domain.

I want to modify the below to work if the lead company name is even contained in the Account name or if the lead email domain is contained in the Website (or website domain)

What I have works if exact match but not if it is only part of the name or website domain.

ie: if lead company name is Salesforce and Account name is Salesforce Inc or lead email domain is: example.com and website domain is example.com/help it will not work. 


Here is what I have so far:

trigger addAccount on Lead (before Insert, before Update)
{


 List<string> companies=new list<string>();

 For (lead l:trigger.new){
   companies.add(l.company);
  }

 List<Account> leadAccountIds=[Select Id, Name FROM Account WHERE Name IN: companies];

 Map<String, Id> acctNameId=new Map<String, Id>();

 For (Account a:leadAccountIds){
   acctNameId.put(a.name,a.Id);
  }
 
 For (Lead l2:trigger.new){
  if(acctNameId.containsKey(l2.company)){
    l2.Lead_Account__c=acctNameId.get(l2.company);
   }

  }
 
  
 Map<String, Id> domains = new Map<String, Id>();
 for(Lead record: Trigger.new) {
    domains.put(record.Domain__c, null);
 }
 for(Account record: [SELECT Domain__c FROM Account WHERE Domain__c IN :domains.keySet()]) {
    domains.put(record.Domain__c, record.Id);
 }
 for(Lead record: Trigger.new) {
    if(domains.get(record.Domain__c) != null) {
        record.Lead_Account__c = domains.get(record.Domain__c);
    }
  }
}

Any help is appreciated.
Is there a way to verify a destination zip code a user enters against a list of zip codes from our service area? We only service 50 miles from our main hub, but we still receive a lot of "dead leads" that fall outside of the 50 miles. I would like it if when users enter their destination zip code and hit entered, that the system tell them that we do not service that area (if we don't) and continue on normally if we do. Please let me know. I am a salesforce novice, so please break it down for me. 
Hoping someone can help me here, I'm getting a de-reference null object error on some code. This code has been working perfectly up until now so I'm kind of scratching my head on this one, we haven't made any code changes recently to this class. I know that a de-reference means that I am making a call to a null list or variable, and that to combat that you should do checks for .size > 0 before proceeding with any implementation, but, as far as I can tell, we've already done that?

Salesforce reports the error at line 106 which when looking in Salesforce is this line:
 
System.debug('KLE spc per account : '+accToSPCMap.get(account.id).size() + ' for acc: '+account.id);

That line comes directly after a size check:
if(accToSPCMap.size() > 0){

So, I'm making it past the .size() > 0 check, but then still de-referencing on the System.debug line directly below it. I'm having trouble tracking down WHAT the null is at this point. Anybody see anything I missed or have any suggestions on tracking the null better?  

Thanks for your time.
 
public with sharing class SendAlertForRelatedProductPlans
{
    // Make the constructor private since this is a utility class that should not be instantiated
    private SendAlertForRelatedProductPlans() 
    {
    }

    public static void checkNewSubscriptionProductCharges(List<Zuora__SubscriptionProductCharge__c> newSubscriptionProductCharges) 
    {
       // The below code will query for the accounts related to the SPCs that are being inserted
        Set<Id> accountIdSet = new Set<Id>();
        List<Messaging.SingleEmailMessage> messages = new List<Messaging.SingleEmailMessage>();

        for(Zuora__SubscriptionProductCharge__c spc : newSubscriptionProductCharges)
        {
            if(spc.Zuora__Account__c != null && spc.Zuora__Subscription__c != null) // Make sure the SPCs are related to an account and subscription
            {
                accountIdSet.add(spc.Zuora__Account__c);
            }
        }

        if(accountIdSet.size() == 0)
        {
            System.debug('The SPCs being inserted were not associated with accounts, quitting early.');
            return; // If none of the SPCs are related to accounts, quit early 
        }

        List<Account> accounts = [SELECT Id, Name, Customer_Number__c FROM Account WHERE Id IN :accountIdSet];

        // For each account, we'll need to query for *all* the related active subscriptions.
        Map<Id, Zuora__Subscription__c> subscriptions = new Map<Id, Zuora__Subscription__c>([SELECT Id, Name, Zuora__Account__c
                                                                                             FROM Zuora__Subscription__c 
                                                                                             WHERE Zuora__Account__c IN: accountIdSet 
                                                                                             AND Zuora__Status__c = 'Active'
                                                                                             AND Name != null]);

        // If there are no active subscriptions associated with the accounts specified, we should not continue.
        if(subscriptions.size() == 0)
        {
            System.debug('There were no active subscriptions associated with the SPCs being inserted. Quitting early.');
            return;
        }

        Set<Id> subscriptionIdSet = subscriptions.keySet();

        // We also need to query for all SPCs associated with the above active subscriptions.
        // Retrieve any SPCs that are:
        // (a) Associated with the set of subscriptions ids
        // (b) The subscriptions must be active
        // (c) Associated with the set of account ids within this trigger context 
        // (d) The SPC isn't a Discount Record
        // (e) The SPC has a Rate Plan Classification
        Map<Id,Zuora__SubscriptionProductCharge__c> spcsAssociatedWithActiveSubscription = new Map<Id,Zuora__SubscriptionProductCharge__c>(
                                                                                         [SELECT Id, RatePlanClassification__c, Zuora__Account__c, Zuora__Subscription__c
                                                                                          FROM Zuora__SubscriptionProductCharge__c
                                                                                          WHERE Name != 'Discount' 
                                                                                          AND RatePlanClassification__c != null
                                                                                          AND Zuora__Subscription__c IN : subscriptionIdSet
                                                                                          AND Zuora__Subscription__r.Zuora__Status__c = 'Active' 
                                                                                          AND Zuora__Account__c IN :accountIdSet]);

        Map<Id, List<Zuora__SubscriptionProductCharge__c>> accToSPCMap = new Map<Id, List<Zuora__SubscriptionProductCharge__c>> ();
        for(Zuora__SubscriptionProductCharge__c zs: spcsAssociatedWithActiveSubscription.values()){
            List<Zuora__SubscriptionProductCharge__c> sub = accToSPCMap.get(zs.Zuora__Account__c);
            if(sub == null){
                sub = new List<Zuora__SubscriptionProductCharge__c>();
                sub.add(zs);
                accToSPCMap.put(zs.Zuora__Account__c, sub);
            }else{
                sub.add(zs);
            }

        }

        // The below two maps will capture whether a subscription has:
        // (a) at least one 'Support' related SPC 
        // (b) at least one 'Software' related SPC

        Integer count = 0;

        System.debug('KLE accounts : '+accounts.size());

        for(Account account : accounts){
            Set<ID> subscriptionIdHasSupportSPCs = new Set<ID>();
            Set<ID>  subscriptionIdHasSoftwareSPCs = new Set<ID>();
            Set<ID>  subscriptionIdHasCommSPCs = new Set<ID>();

            if(accToSPCMap.size() > 0){
            System.debug('KLE spc per account : '+accToSPCMap.get(account.id).size() + ' for acc: '+account.id);
                for(Zuora__SubscriptionProductCharge__c spc : accToSPCMap.get(account.id))
                {
                    if(spc.RatePlanClassification__c == 'Support')
                    {
                        subscriptionIdHasSupportSPCs.add(spc.Zuora__Subscription__c);
                        
                    }
                    else if(spc.RatePlanClassification__c == 'Software')
                    {
                        subscriptionIdHasSoftwareSPCs.add(spc.Zuora__Subscription__c);
                        
                    }
                    else if(spc.RatePlanClassification__c == 'Communication')
                    {
                        subscriptionIdHasCommSPCs.add(spc.Zuora__Subscription__c);
                        
                    }
                    count++;

                } // End of loop through SPCs
           }

 
I have an opportunities report created and I am trying to add filters to find out which accounts have not had Closed won opportunities in over a year.  Is there a way to do this using multiple filters?
Hello, I have created a validation rule which stop users linking one company's contacts to another company's account licence. However one record type 'IPAD Contact Licence' is excluded from this rule, all works fine and the formula currently looks like this:

AND( 
Contact__r.AccountId <> Company_Licence__r.Company__r.Id,
RecordType.Name <> "IPAD Contact Licence" 
)

Now I have a challenge to include this record type in this restriction but not fully - the Contact Account ID doesn't have to be equal to the Company Licence Company ID, but needs to be within the company hierarchy so our users can attach a contact to a licence sitting under a different branch.

I'm not sure how to amend the formula to ensure all the other record types follow the existing validation rule and add the exception above.

Hopefully this makes sense. 

Thanks.

Katerina
Hello,

I've enabled the object in my DEV enviornment and taken a look at the metedata.  Does not appear to be a property on the fields for Tracking History.

<fields>
<fullName>SplitPercentage</fullName>
</fields>

Can historty tracking be enabled for splits? 

Scenario - User sets it to 50/50 on day 1 and 6 months later changes it to 75/25. 

I know we can put a valdiation rule that prevents editing it after being closed.

Thanks!,
Joseph