• Shikibu
  • SMARTIE
  • 632 Points
  • Member since 2009

  • Chatter
    Feed
  • 23
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 57
    Questions
  • 274
    Replies

Hello!

 

I tried to delete from eclipse, and because the apex classes were linked to some vf pages, they didnt get deleted in the live instance, however, got deleted in the eclipse IDE.

 

Now, I see no way of deleting the classes I want in the live instance.

 

How does one do this?

 

Pranav

Hi Friends,

 

Please help me out,

 

I am using required inputFields a Visual Force Page with standardController Object .

I am refereshing each input field for onblur event in order validate the field immidiately.

 

The problem, i dont want to have default error message Error: You must enter a value

 

 I dont want to remove the required attribute , as i need to have the required field symbol.

 

Please let me if there is any work around for this:

 

Thanks,

yvk

 

 

Message Edited by yvk431 on 01-05-2010 05:55 AM
  • January 05, 2010
  • Like
  • 0

I am a newbie for VF and APEX, I am trying to display a list of records in  apex datatable with a radio button, the radio buttons should be initially unchecked and only one radio button can be checked by the user, I need to grab the SF Id once user clicks on the radio button for a record, I have written a wrapper class to get the radio button with the list in VF, the problem is, my VF page loads with all the radio button selected.

 

 

Code for Wrapper Class:

 

public class Select_Wrapper {

public Orgs__c aum {get; set;}

        public Boolean selected {get; set;}

        

        public Select_Wrapper(Orgs__c nc){

            aum = nc;

            selected = false;

        }

 

Code For Controller :

 

public with sharing class abc {

public string msg{get;set;}

public string oid{get;set;}

public string compName{get;set;}

public string compDomain{get;set;}

public string ssId{get;set;}

public string Info{get;set;}

public integer updFlag = 0;

public integer recCount{get;set;}

public List<KOW> Selected_KOW;

public List<Orgs__c> InfgNCO = new List<Orgs__c>();

public List<Select_Wrapper> wrapPrd = New List<Select_Wrapper>();

    public abc(ApexPages.StandardSetController controller) {

     Selected_KOW = (List<KOW>) controller.getSelected();

       }

     

    public List<Select_Wrapper> Os(){

        if(wrapPrd == null){

            wrapPrd = new List<Select_Wrapper>();

        }            

            

     wrapPrd.clear();

     for(Orgs__c nc : [Select Name,Co_in__c,Co__c,ss_ID__c,Info__c From Orgs__c where something...]){

     Select_Wrapper objWrap = new Select_Wrapper(nc);

     wrapPrd.add(objWrap);

    

     }

        }

        return wrapPrd;

    }

    public Pagereference Finddata()

    {

     return null;

    }

    

}

 

VF Page:

 

<apex:page standardController="KOW"  recordSetVar="var2" extensions="abc">

<apex:form id="theForm">

...   

  <apex:outputPanel id="theResultPanel">

  <apex:actionStatus startText="(Fetching Data...)" stopText=" " id="searchStatus"/>

  <apex:pageBlock>

  <apex:dataTable value="{!Os}" var="var1" cellPadding="4" border="1" width="100%">

  <apex:column >

                    <apex:selectRadio value="{!var1.selected}"/>

                </apex:column>

  <apex:column >

  <apex:facet name="header">Name</apex:facet>

  <apex:outputText value="{!var1.aum.Name}"/>

</apex:column>

  <apex:column >

  <apex:facet name="header">Cross Link</apex:facet>

<apex:outputText value="{!var1.aum.Co_in__c}"/>

</apex:column>

  <apex:column >

  <apex:facet name="header">Company</apex:facet>

<apex:outputText value="{!var1.aum.Co__c}"/>

</apex:column>

  <apex:column >

  <apex:facet name="header">Addfd</apex:facet>

<apex:outputText value="{!var1.aum.ss_ID__c}"/>

</apex:column>

  <apex:column >

  <apex:facet name="header">Information</apex:facet>

<apex:outputText value="{!var1.aum.Info__c}"/>

</apex:column>

  </apex:dataTable>  

  </apex:pageBlock>

  </apex:outputPanel>

</apex:form>

</apex:page> 

 

Hi,

 

If I have a dataList that is populated using an array that is defined by the controller, how can I have a button on each row for deleting that row? When the button on row x is pressed the corresponding entry from the array should be removed as well. I have something like this but it doesn't work:

 

 

<apex:dataList value="{!myArray}" var="f" id="myList"> <apex:outputText value="{!f}"/> <apex:outputPanel onclick="removeJS({!f});" styleClass="btn"> Remove </apex:outputPanel> </apex:dataList> ... <apex:actionFunction action="{!removeFromArray}" name="removeJS" rerender="myList"> <apex:param name="firstParam" assignTo="{!valueToRemove}" value=""/> </apex:actionFunction>

 

*** CONTROLLER ***

// the member variable valueToRemove does not get updated when the JS function is called

 

 This is what I have and I think I know why it doesn't work. If you got an idea please go ahead and present. Thanks!

 

  • November 06, 2009
  • Like
  • 0

How can i make the radio button as well as label for the radio button clickable?

 

Code:

        <apex:outputLabel value=""/> 

              

        <table border="0">   

         

        <tr>

            <td> 

                 <apex:selectRadio id="searchType" layout="pageDirection" disabled="true" value="{!searchType}" onclick="setSearchType(this);" styleClass="radio_b">

                 <apex:selectOptions value="{!items}"/>

                 </apex:selectRadio>                

            </td>

        </tr>

        

        </table> 

Hi there,

 

So I think that I kind of understand Maps, in that if you create a map with a SOQL query, such as

 

 

Map<ID,sObject> sObMap = new Map<ID,sObject>([SELECT *fields* FROM sObject WHERE *conditions*]);

 you get the key/value pairing of an sObject ID and the sObject itself. I'm slightly unsure as to the purpose of the *fields* in the SOQL query, but it seems to work where I need it to, namely in specifying an sObject from a list of IDs.

 

Today I was trying to create an <ID,ID> map, so I can take a list of accounts and iterate through them to get a key/value pairing for the IDs of a set of Master-Detail related sObjects (Clent_Form__c). I want to insert a set of a third object (Assessments__c), which has lookups to the Account and the related Client_Form__c. The only way I think I can do this is by putting SOQL in a FOR loop (METHOD 1 below), which I know is bad practice for bulk triggers.

 

Is there a better way of taking a list of Accounts and mapping them to detail sObjects?

 

Here's the working (messy) class as it stands.

 

 

public with sharing class createAssessments { public static void IEF(List<Account> accs){ //Declare owner ID variable for IEF Assessments queue Id ownerId = [Select q.Queue.Id from QueueSobject q where q.Queue.Name = 'Application Screenings' and q.SobjectType = 'Assessment__c'].Queue.Id; //Create a list of assessments to be inserted List<Assessment__c> assessments = new List<Assessment__c> (); //METHOD 1 - works but I've got SOQL in a loop //Create map of Account ID => Client Form ID Map<ID,ID> IEFs = new Map<ID,ID>(); for (Account a:accs){ IEFs.put(a.Id,[SELECT Id FROM Client_Form__c WHERE Account__c = :a.Id].Id); } //METHOD 2 - doesn't work as I'm putting sObject Client_Form__c into an ID field when I create the assessments //Create list of account IDs for object list accs - is this necessary or could I reference the object list directly? //List<ID> refAccs = new List<ID> (); //for (Account z:accs){ //refAccs.add(z.Id); //} //Query client forms for account IDs and put in a map //Map<ID,Client_Form__c> IEFs = new Map<ID,Client_Form__c>([SELECT Id, Account__c FROM Client_Form__c WHERE Account__c IN :refAccs]); //For each account, create two IEF assessments for(Account a:accs){ Assessment__c assess = new Assessment__c(); assess.Client_Form__c = IEFs.get(a.Id); assess.RecordTypeId = '01280000000BR0VAAW'; assess.OwnerId = ownerId; assess.Account__c = a.Id; assessments.add(assess); assessments.add(assess.clone()); } //Insert the assessments insert assessments; } }

Thanks in advance,

 

Joe

 

 

 

I have an input field that is appearing too small, making it hard for the user to read its contents (text up to 100 characters). 

 

I'd like to have it span the width of the form, but no matter what, it still only appears in column 1 of 2.  Here is what I tried to no avail:

 

<apex:pageBlockSection title="Email Contents" columns="1"> <apex:inputField value="{!notification.EmailTemplateName__c}"/> </apex:pageBlockSection>

 

You would have thought that columns="1" would have done it.  

 

How do I get this field (including the label) to span the width of the page block section or form instead of leaving the right half blank?  

 

 

Hi all

 

Hope someone can help with this, have been trying to do this for a while and have searched for a solution to no avail. 

 

Here is a snippet from my VF page

<apex:inputField value="{!Service__c.Service_Fee__c}" id="txtServiceFee"/> ... <apex:inputField value="{!Service__c.Type__c}"> <apex:actionSupport event="onblur" action="{!UpdateServiceFee}" rerender="txtServiceFee"/> </apex:inputField>

 

What I am trying to do is update the txtServiceFee inputField value on the VF page whenever the onblur event of lookup field Type__c is triggered. I have attempted to do that with the APEX code below:

 

public class ServiceFee { private Service__C servc; public ServiceFee(ApexPages.StandardController stdController) { servc = (Service__C)stdController.getRecord(); servc.Service_Fee__C = 12.00; } public void UpdateServiceFee() { servc.Service_Fee__C = 16.00; } }

 

When the page loads the txtservicefee input field is set to 12.00 as expected. However when the onblur event is triggered the inputField IS rerendered but isn't updated to 16.00.

 

What am I doing wrong here? Any help would be greatly appreciated.

 

Thanks

Paul

Message Edited by Pjay on 10-28-2009 05:40 PM
  • October 29, 2009
  • Like
  • 0

Hi

 

am pretty new to visualforce and am trying to get some css to work -  without any success!

 

Even when i use the example from http://wiki.developerforce.com/index.php/An_Introduction_to_Visualforce I can't get it to work.

 

This is what I do:

 

paste the following into notepad & save as styles.css

.mystyle {
background: url(img/mybackground.png);
font-size:18pt;
font-weight:bold;
width:220px;
height:59px;
}


 I upload as a static resourse called "styles".

 

create a new vfpage using

 

<apex:page showHeader="true" standardStyleSheets="false">
<apex:styleSheet value="{!URLFOR($Resource.styles,'styles.css')}"/>
<apex:outputPanel styleClass="mystyle" layout="block">
My Styled Panel
</apex:outputPanel>
</apex:page>

 and it renders as plain unformatted text.

 

any suggestions ? I guess there is some css syntax that I'm missing ??

So I have an APEX page that uses a sandardcontroller and the {!save} action. However, when a save is performed the user is take to the object record view rather then the retURL. How can I redirect the user to the correct page after performing a save action?

Hi Gurus--

 

I am new to Force.com. I was going to the Online Tutorial provided by SalesForce.com and I am stuck at the below step (see below bold part) in Eclipse. Below steps wants me to change the Admin.profile but I can NOT find the Profiles folder under src folder in eclipse. Please Help me!! Also let me know if you have any questions or if my question is not clear. Thanks in Advance-- Basant

 

================================================================

Configure user profiles:

a. To bring the updated profiles back to the IDE, right-click the src folder and choose Force.com > Refresh from Server.
b. Expand the src > profiles folder, double-click the Admin.profile file to open it in the XML editor.
c. Change the value of the <visible> element for Mileage Tracker to true, as illustrated in the bold text below:

<?xml version="1.0" encoding="UTF-8"?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
 <applicationVisibilities>
  <application>Mileage Tracker</application>
  <default>false</default>
  <visible>true</visible>
 </applicationVisibilities>
...
</Profile>

d. Click Save.

Hi,

 

  I am looking for a way to insert custom object in Database in Apex code.

  I am able to compute the column values of the row but not able to figure out how to create this custom object instance and store in database.

 

  Thanks for the Help.

When I try to open a file in Excel 2007 exported from Salesforce Report, I receive the following warning message:
The file you are trying to open, xxxx.xls is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

Help text from Excel 2007 reveals that "The warning message is a user-notification function that was added to Excel 2007. The warning message can help prevent unexpected problems that might occur because of possible incompatibility between the actual content of the file and the file name extension."

 

A case logged with Salesforce replied that they do not have such problem. Does anyone encounter the same issue? Is there any compatibility issue on MS Office 2007 with Salesforce? Any advise is greatly appreciated.

 

I have a bunch of class and trigger names I need to update in production. What is the safest way to do this.  Should I clone my production into the sandbox and make sure evertything is in sync. Then, I plan on modifying the class and trigger names in Sandbox and deploy it in Production. 2 questions

 

1. Will this be safe and and will it work?

 

2. If I want to update the class and trigger name in sandbox, how can I do this in eclipse? When I try overwriting the name of the class and the trigger callling the class, i get an error

 

Thanks

I noticed that my Visualforce page threw the following error when I tried to add a related list that was perfectly well defined in the object's setup but happened not to be in the Page Layout: 'SubContracts__r' is not a valid child relationship name for entity Licensing Contract

This appears to be an undocumented restriction on the use of <apex:relatedList> not to mention one that could potentially cause some nasty issues in a production environment should an admin update a page layout or create a new one after the orginal page is deployed. Likewise, if they create new recordtypes or recordtype/profile assignments. This restriction is not intuitive; one generally thinks of Visualforce as an alternative to a Page Layout, not as an extension that is bound to it and inherents its content restrictions. Additionally, for developers who have over-ridden all page-layouts for an object with VF pages, it is counter-intuitive to have to edit a Page Layout that is not in use simply to include the list in their VF pages.

Could someone respond back with some clearer details on how this actually works? Does Visualforce simply require that one page layout include the related list or does it require the page layout for the given record type include it. Wouldn't it be more robust to simply define the apex:related list to display based on user permissions rather than throw an error if the list is not found in the related page layout.


Message Edited by lnryan on 12-16-2008 01:12 PM
  • December 16, 2008
  • Like
  • 0
AccountContactRelation.AccountId cannot be updated.

If I insert a clone of the existing AccountContactRelation pointing to the new Account,  it gets changed to indirect.

The original AccountContactRelation record cannot be deleted because the Contact requires a parent Account.

 
I'm stumped by this, because there may be multiple triggers fired. Really what I want is a trigger on the opp when any related opportunitysplit is inserted, updated, or deleted (that's how OpportunityLineItem works). But OpportunitySplit does not seem to fire Opportunity triggers.

I can't figure out how to use the OpportunitySplit trigger, because multiple triggers may fire (insert, update, delete), and I only want to send one email when any aspect of the OpportunitySplit changes.
I am having the developer console fail on me often enough (as described in Salesforce Help) that I got tired of using Workbench to fix it, and I wrote a Visualforce page that uses https://jsforce.github.io and the Tooling API to do the trick.

My source code is here: https://gist.github.com/bolaurent/65e3f59ac81ee2587a7d67a2d372996e

There's one issue that is bugging me. When you press the "Delete my IDEWorkspace" button, the delete operation works correctly, but the page refreshes, and it complains that it cannot find the user's IDEWorkspace (because it has been deleted).

Why is this refresh happening? How can I prevent it?

 
I'm an experienced Apex/Visualforce developer, and working on my first Lightning Component.

I get the impression that after I save/compile a modified Lightning bundle file (component or javascript), there is a delay before it becomes available in my sandbox instance. My Lightning component is invoked as a quick action on a custom object. If I hit save (in developer console or in my IDE, which is The Welkin Suite), and then refresh the lightning detail page and click the quick action button, it sure looks like the *old version of my code runs. If I refresh the detail page again, I sometimes get a "Sorry to Interrupt" popup. And then if I refresh again, I get the new code invoked.

Is there a delay between saving Lightning component code and the code actually being available in the sandbox instance?

I just enabled forecast overrides (with Customizable Forecasting). Sales reps want to edit opportunity forecast stage. We have validation rules that prevent them from advancing the opportunity stage (for instance, can't advance the stage until you get pricing approval). 
 

These rules are apparently firing when they try to create a forecast override. I noticed that the lastmodifieddate on opportunity is altered when I enter a forecast override. But I don't understand why that should be, nor what field is being edited. The users want to override forecasts precisely because they are not able to advance the opp stage. 

How can I make the validation rule not fire in the case of a forecast override editing the opp?

 

I had a requirement to identify all Salesforce reports that were filtered on certain standard fields, stagename values, and a custom field (all of which were being changed). Salesforce provides very nice documentation of the Reports and Dashboards REST API, but I didn't find any sample code.

I have published my work, in python, at a gist named SearchSalesforceReports. I'm publishing the code below as well, for easier searching. It works by extending simple_salesforce; this technique is useful for other Salesforce APIs too.
 
#!/usr/local/bin/python3


# https://developer.salesforce.com/docs/atlas.en-us.api_analytics.meta/api_analytics/sforce_analytics_rest_api_getbasic_reportmetadata.htm

import pdb
import json
from collections import OrderedDict
import config
from progressbar import ProgressBar


import simple_salesforce

class SFDC(simple_salesforce.Salesforce):
    def __init__(self, username=None, password=None, security_token=None,
                sandbox=False, version=config.DEFAULT_API_VERSION):
        super(SFDC, self).__init__(username=username, password=password, security_token=security_token,
                                    sandbox=sandbox, version=version)


    def describeReport(self, id):
        """Describes report with given id
        """
        url = self.base_url + "analytics/reports/{}/describe".format(id)
        result = self._call_salesforce('GET', url)
        if result.status_code != 200:
            raise SalesforceGeneralError(url,
                                         'describe',
                                         result.status_code,
                                         result.content)
        json_result = result.json(object_pairs_hook=OrderedDict)
        # json_result = result.json()
        if len(json_result) == 0:
            return None
        else:
            return json_result

def init():
    salesforce_credentials = json.loads(open(config.SFDC_CONFIGFILE).read())

    username = salesforce_credentials['user']

    if salesforce_credentials['sandbox']:
        username += '.' + salesforce_credentials['sandbox']
        config.SFDC_URL = 'https://canonical--staging--c.cs87.visual.force.com/'
    else:
        config.SFDC_URL = 'https://eu1.salesforce.com/';

    sfdc = SFDC(username=username, 
                      password=salesforce_credentials['password'], 
                      security_token=salesforce_credentials['token'], 
                      sandbox=salesforce_credentials['sandbox'],
                      version=config.DEFAULT_API_VERSION)
                      
    return sfdc

reportFields = [
    'Id'
    ,'Name'
    # ,'FolderName'
    ,'DeveloperName'
    ,'CreatedDate'
    ,'CreatedBy.Name'
    ,'LastRunDate'
    ,'LastModifiedBy.Name'
    ,'LastModifiedDate'
    ,'LastViewedDate'
    ,'Description'
]


def dumpHeader():
    print('\t'.join([
        'FolderName'
        ,'Name'
        ,'CreatedDate'
        ,'LastModifiedDate'
        ,'LastRunDate'
        ,'CreatedBy.Name'
        ,'LastModifiedBy.Name'
        ,'Note'
        ,'Url'
    ]))

def quotify(s):
    if s == None:
        return '';

    s = str(s)
        
    if len(s) == 0:
        return '';
    return '"' + s.replace('\n', '\\n').replace('"', '\"') + '"'


def get(dict, keys):
    if not keys:
        return dict
        
    if not isinstance(keys, list):
        return dict[keys]
    
    return get(dict[keys.pop(0)], keys)
    
        
def dumpReport(folderName, reportJson, reportRecord, sfdcUrl, note):
    print('\t'.join([quotify(cell) for cell in 
                        [folderName] +
                        
                        [reportJson['reportMetadata']['name']] + 
                        
                        [get(reportRecord, keys) for keys in [
                            'CreatedDate'
                            , 'LastModifiedDate'
                            , 'LastRunDate'
                            , ['CreatedBy', 'Name']
                            , ['LastModifiedBy', 'Name']
                        ]] +
                        [note] +
                        [sfdcUrl + reportJson['reportMetadata']['id']]
            ]))
    pass
    


# queryWhereClause = "where id = '00OD00000072LjH'"
queryWhereClause = ""

relevantStageNames = ['Value Proposition', 'Negotiation/Review', 'Proposal']

def relevant(reportJson):
    stages = []
    if reportJson and 'reportMetadata' in reportJson:
        for filter in reportJson['reportMetadata']['reportFilters']:
            if filter['column'] == 'Renewal__c':
                return 'Renewal__c'

            if filter['column'] == 'FORECAST_CATEGORY':
                return 'Forecast Category'
                
            elif filter['column'] == 'STAGE_NAME':
                values = filter['value'].split(',')
                for value in relevantStageNames:
                    if value in values:
                        return 'Stage'
                
    return None
    

def getFolderName(reportJson, folderNamesById):
    folderId = reportJson['reportMetadata']['folderId']
    folderName = ''
    if folderId in folderNamesById:
        folderName = folderNamesById[folderId]
    elif folderId.startswith('005'):
        folderName = 'My Personal Custom Reports'
    elif folderId.startswith('00D'):
        folderName = 'Unfiled Custom Reports'
    else:
        folderName = folderId
        
    return folderName
        
                    
def main():
    sfdc = init()
    
    sfdcUrl = 'https://{instance}/'.format(instance=sfdc.sf_instance)
    
    folderNamesById = {}
    for folder in sfdc.query_all("select Id, Name from folder")['records']:
        folderNamesById[folder['Id']] = folder['Name']
    
    result = sfdc.query_all("select {} from report {} ".format(','.join(reportFields), queryWhereClause))

    dumpHeader()
    progressbar = ProgressBar()
    for reportRecord in progressbar(result['records']):
        reportJson = None
        try:
            reportJson =  sfdc.describeReport(reportRecord['Id'])
        except Exception as e:
            if e.status == 501:
                pass
            else:
                pdb.set_trace()
                print(reportRecord['Id'], str(e))

        relevance = relevant(reportJson)
        if relevance:
            folderName = getFolderName(reportJson, folderNamesById)
                        
            try:
                dumpReport(folderName, reportJson, reportRecord, sfdcUrl, relevance)
            except Exception as e:
                pdb.set_trace()
                print(reportRecord['Id'], str(e))
            continue
            
    
    
if __name__ == "__main__":
    main()
    pass

 
I have a unit test that is throwing UNABLE_TO_LOCK_ROW when it is doing an insert. I don't understand why that should happen. Here's the code (excerpted). The exception is thrown on the insert statement. Because this is a new record, and contained within a test class, how can it throw a UNABLE_TO_LOCK_ROW exception?

@istest
private class MyTest {
    ...
    theQuote = new Quote(Name='Test Quote',
                         OpportunityId = theOpp.Id,
                         Term__c=12,
                         pricebook2id=thePricebook.id);
    insert theQuote;
    ...
}


SoqlXplorer is one of the tools I use almost every day.

 

Today, I went to use the details window, and it seemed as if it were invisible. But when I resized the main window small enough, I discovered that the details window is stuckl behind the main window. I can't get the details window to come to the front.

 

This is on OSX 10.8.2, with SoqlXplorer 1.9. I tried rebooting the mac, but the behavior did not change. I've never seen it do this before.

I use SoqlXplorer daily. I just allowed it to update to 1.80. The new version boots, asks for a login, and when I select one that is stored in a keychain, it hangs. I've tried rebooting it, and I've tried directing it to a different sfdc instance (in a sandbox), with no improvement.

 

I downloaded 1.70 from http://www.pocketsoap.com/osx/soqlx/, and it does not exhibit this problem.


My environment is a MacBook Air, 10.8.2. Simon, let me know if you would like any other data.


Thanks,


Bo

I'm trying to disable a commandbutton when any element of a form has been changed.


My js for detecting the form change is working ok, but the following js does not succeed in enablng or disabling the button.

 

<script type="text/javascript">

    function enableCreateButton(state) {
        document.getElementById('{!$Component.thePage.theForm.thePageBlock.thePageBlockButtons.theCreateButton}').disabled = state;
    }
    
 </script>

Here's the markup:

<apex:commandButton value="Create Lead" 
                    action="{!createLead}" 
                    id="theCreateButton"/>

 

 I can run enableCreateButton(true) or enableCreateButton(false) in the firebug console, and it has no effect. I can display document.getElementById('{!$Component.thePage.theForm.thePageBlock.thePageBlockButtons.theCreateButton}') in the console, and I see the component. I can see that running enableCreateButton changes the value of its disabled element.

 

What am I doing wrong here?

 

 

 

 

I have the following code: 

 

public String retURL() {
    return Page.DupeChecker.getUrl();
}

public PageReference createLead() {
    String leadPrefix = Schema.getGlobalDescribe().get('Lead').getDescribe().getKeyPrefix();
    
    PageReference p = new PageReference('/' + leadPrefix + '/e');
    p.setRedirect(True);
    p.getParameters().put('nooverride', '1');
    
    p.getParameters().put('retURL', EncodingUtil.urlEncode(retURL(), 'UTF-8'));
    
    return p;
}

 It produces an url as follows:

 

https://cs7.salesforce.com/00Q/e?nooverride=1&retURL=%252Fapex%252Fdupechecker

 This url opens a lead page for editing, which is what I wanted.

 

However, if the user hits cancel, the browser returns to an url like this, which is invalid. Why is there a '00Q/' at the beginning of hte url?

 

https://cs7.salesforce.com/00Q/%2Fapex%2FDupeChecker

 

 

I am familiar with overriding the new action for any object in the browser based interface. For the first time I am trying to do this in the mobile app (iphone).

 

My VF page is displayed when I click new lead in the browser. But when I click new lead in the mobile app, I get the standard mobile page.

 

In fact, this page states "If you override a standard button in Salesforce, that button is still available in Connect Offline or Salesforce Mobile, but it retains its original behavior ".

 

How do I override the mobile new lead page?

I have a trigger on CaseComment that wants to run certain code only if the comment was posted by a selfserviceuser.

 

How can I exercise this code in a test class? System.RunAs will not accept a selfserviceuser as argument.

I am testing a webservice that accepts a list of Asset Ids, changes each asset.Status to "Active." 

 

When there is any kind of error on the DML update, the saveresult does not provide me with the Id. Here's an example; the asset has been deleted.

 


20100202213448.608:Class.AssetActivateWS.activateAssets: line 35, column 13: Database.SaveResult[getErrors=(Database.Error[getFields=();getMessage=entity is deleted;getStatusCode=System.StatusCode.ENTITY_IS_DELETED;]);getId=null;isSuccess=false;]

 

I can add code to generate the id myself, but it seems strange (a bug even) that SaveResult.getId returns null if saveResult.isSuccess is false.

 

Any insights?



 

 

 

Why do I get "twistSection is not defined" javascript errors for the following use of pageBlockSection?

 

 

<apex:page standardController="Account" extensions="OEMTeamReportController" showHeader="true" tabStyle="account" standardStylesheets="true" title="OEM Services Team Resources"> <apex:form > <apex:pageBlock title="OEM Opportunities for Review"> <apex:repeat value="{!accounts}" var="this_account"> <apex:pageBlockSection title="{!this_account.acct.Name}" columns="1" collapsible="true">

<table class="opps_table">
etc...

 

 

 

I am trying to use google visualizations for the first time. I installed parts of the code share project referenced here. I am producing a bar chart, but I have to specify the vertical height in pixels. I'd like to calculate the vertical height based on the number of bars; otherwise google makes the text larger or smaller to fit, and it's always the wrong size.

 

But if I try to use an apex variable, when I try to save the VF page salesforce complains that "Error: Literal value is required for attribute height in <c:BarChart>".

 

Looking at the Google api docs, I don't see a way to tell Google to determine an appropriate size for the height. 

 

Is it possible to specify a calculated height for the barchart, based on the number of rows? The code seems to insist on a predetermined integer pixel count.

 

I have a selectList like this, with the required attribute set to True:

 

 

<apex:pageBlockButtons > <apex:commandButton action="{!saveAction}" value="Save"/> <apex:commandButton action="{!cancel}" value="Cancel"/> </apex:pageBlockButtons> <apex:pageBlockSection columns="1" title="Information"> <apex:inputhidden value="{!OpportunityCompetitor__c.Opportunity__c}"/> <apex:pageBlockSectionItem> <apex:outputLabel value="Competitor" for="competitor"/> <apex:selectList value="{!OpportunityCompetitor__c.Competitor__c}" required="True" size="1" id="competitor"> <apex:selectOptions value="{!competitorOptions}"/> <apex:actionSupport event="onchange" action="{!copyStrengthsWeaknesses}" rerender="strengths, weaknesses"/> </apex:selectList> </apex:pageBlockSectionItem>

 

 

  

The selectlist component is not displayed with a red bar.

 

The first value is an empty string, with '-- None --' as label. If the user presses the Save button, the page flashes but does not save, because the page validation is failing.

 

However, no validation message is displayed.

 

If I display apex messages, I can see the validation fails, but these messages are ugly; I don't want to display them to users.

 

How can I get the validation failure to display a nice message next to the field?

 

How can I get the red bar to display on the selectList?

 

 

 

Message Edited by Shikibu on 01-08-2010 10:59 AM

I'm trying to style a page for renderas pdf. The following code works fine in html, but the image is broken when rendered to pdf. It's broken whether I use eps or pdf for the logo. I can render the png into pdf, but of course the quality is very low.

 

I'm pretty sure that the urlfor is correct (I rendered it as aoutput link to check it, and of course the png i s ion the

same zip file).

 

 

<apex:image value="{!if($CurrentPage.parameters.pdf == null, URLFOR($Resource.Logos, 'Logos/canonical_side_small.png'), URLFOR($Resource.Logos, 'Logos/canonical_side.eps'))}"/>

 

 

 

 Is it possible to render a pdf with an embedded pdf or eps image?

I'm seeing this (all by itself) in a debug log. What does it mean? And why does it claim to take 9,136 ms? And why is there another debug log, immediately following, and resulting from the same (single) click, but with a start time only three seconds later?

Element thePage called method {!checkManageability} returned type PageReference: none

 If I want to display, for instance, an account name, with a label, in a vf pageSection, I can do this:

 

 

<apex:outputField value="{!theAccount.Name}"/>

 

But if I want to have it link to the account, do I really have to write all this markup?

 

 

 

<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Name" for="the_account"/>
<apex:outputLink value="/{!theAccount.Id}" id="the_account">
<apex:outputText value="{!theAccount.Name}"/>
</apex:outputLink>
</apex:pageBlockSectionItem>

 

 I'm wishing I could write:

 

 

<apex:outputText value="{!theAccount.Name}" linksto="{!theAccount.Id}"/>

 

 

 

 

 

 

I have a unit test that is throwing UNABLE_TO_LOCK_ROW when it is doing an insert. I don't understand why that should happen. Here's the code (excerpted). The exception is thrown on the insert statement. Because this is a new record, and contained within a test class, how can it throw a UNABLE_TO_LOCK_ROW exception?

@istest
private class MyTest {
    ...
    theQuote = new Quote(Name='Test Quote',
                         OpportunityId = theOpp.Id,
                         Term__c=12,
                         pricebook2id=thePricebook.id);
    insert theQuote;
    ...
}


I'm stumped by this, because there may be multiple triggers fired. Really what I want is a trigger on the opp when any related opportunitysplit is inserted, updated, or deleted (that's how OpportunityLineItem works). But OpportunitySplit does not seem to fire Opportunity triggers.

I can't figure out how to use the OpportunitySplit trigger, because multiple triggers may fire (insert, update, delete), and I only want to send one email when any aspect of the OpportunitySplit changes.
I am an Admin with no coding/developer skills, and we don't have a developer. Salesforce Support told me that my problem could be solved by setting a trigger to manually update stage history. I'm hoping someone can explain how to do this.

Basically, my team created an opportunity in July '18 that shouldn't have been created until December '18, and I need it to show up as created in December '18 with the stage set to Evaluation in December, as well.

2 days ago (January '19), I deleted the original opportunity and created a new opportunity through import with the CreatedDate set to December 12, 2018, with the stage set to Evaluation. However, while the opportunity correctly appears as having been created in December, the stage value is not set until January. Therefore, the opportunity is missing from my Opportunity Trend report in december, because it is considered stageless until January.

Can someone tell me how to create a trigger that will set the opportunity stage history to show the evaluation stage being set in December? Thank you!
I am trying to use the DML statement to make an insert to the parent and child tables all at once.

I have got it to this point so far, I am not sure how to link the child to the parent when doing the insert in one command.

I tried following the instructions on the post below, got a bit confused. On the code there they use an external ID to make it happen which I am not sure about as I want the child objects to have the id of the parent record on its foreign key relationship field. I already have a master-detail relationship setup between the custom objects.

https://salesforce.stackexchange.com/questions/133906/insert-list-of-parent-and-child-records-in-one-dml-statement][1]

Here is what I go to so far. How do I link the 2 objects using the master-detail relationship setup and how to use the insert statement.
 
List<addressMaster__c> mduMaster = new List<addressMaster__c>();
            List<addressDetail__c> mduDetails = new List<addressDetail__c>();         
            Object[] values = (Object[])System.JSON.deserializeUntyped(mdus);
            for( Object mdu : values) {
                Map<String,Object> data = (Map<String,Object>)mdu;
                streetAddress = String.valueof(data.get('streetAddress'));
                totalUnits = Integer.valueof(data.get('totalUnits'));
                nnUnits = Integer.valueof(data.get('nnUnits'));            
                addressDetail__c newMduDetail = new addressDetail__c(Name=streetAddress,nnUnits__c=nnUnits,lastReportDate__c=DateTime.now());                                                         
                addressMaster__c newMduMaster = new addressMaster__c(Name=streetAddress,totalUnits__c=totalUnits);
                    
                mduDetails.add(newMduDetail);
                mduMaster.add(newMduMaster);
            }
Please advise!
 
I recently ran into an Apex unexpected exception error that I believe is related to permissions related to deleting attachments.  The process is, when an opportunity is set to a certain stage (converted to project) it creates a project and, among other things, moves all the attachments from the opportunity to the project via Apex and then deletes the attachments from the opportunity.

Here is the error in the debug log:

11:34:10.365 (2365851365)|DML_BEGIN|[98]|Op:Delete|Type:Attachment|Rows:5 11:34:10.365 (2365868983)|LIMIT_USAGE|[98]|DML|3|150 11:34:10.365 (2365882912)|LIMIT_USAGE|[98]|DML_ROWS|11|10000 11:34:10.365 (2365901258)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:24 11:34:10.365 (2407602848)|DML_END|[98] 11:34:10.365 (2407856725)|EXCEPTION_THROWN|[98]|System.DmlException: Delete failed. First exception on row 0 with id 00P1C00003o9HWfUAM; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: [] 11:34:10.365 (2408457394)|HEAP_ALLOCATE|[98]|Bytes:161 11:34:10.365 (2408509370)|METHOD_EXIT|[71]|01p15000007Y5uA|ProjectTriggerHandler.bulkAfter() 11:34:10.365 (2408531750)|METHOD_EXIT|[27]|01p15000007Y5uD|TriggerFactory.execute(ITrigger) 11:34:10.365 (2408544364)|SYSTEM_MODE_EXIT|false 11:34:10.365 (2408558460)|METHOD_EXIT|[3]|01p15000007Y5uD|TriggerFactory.createHandler(Schema.SObjectType) 11:34:10.365 (2409077931)|FATAL_ERROR|System.DmlException: Delete failed. First exception on row 0 with id 00P1C00003o9HWfUAM; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: [] Class.ProjectTriggerHandler.bulkAfter: line 98, column 1 Class.TriggerFactory.execute: line 71, column 1 Class.TriggerFactory.createHandler: line 27, column 1 Trigger.ProjectTrigger: line 3, column 1 11:34:10.365 (2409210634)|FATAL_ERROR|System.DmlException: Delete failed. First exception on row 0 with id 00P1C00003o9HWfUAM; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: []

The id in the error is for an attachment on the opportunity.  

I'm not a developer but am managing this salesforce instance.  My understanding was that Apex ran as at a system privilege level but the error makes it seem like the DML statement is running with the user permission of the user that saves the record.  Is there a way to make it so this particular Apex trigger runs with elevated privileges so we don't need to give this user more privileges or change the role hierarchy?  
 

I am going through the SLDS trail as follows:
Trailhead > Develop for Lightning Experience > Lightning Design System > Use Images, Icons, and Avatars
https://trailhead.salesforce.com/trails/lex_dev/modules/lightning_design_system/units/lightning-design-system5

In the Page Header section, a box is supposed to display an avatar alongside the header text "Accounts / My Accounts".  What I get is a missing image indicator and the brower console gives me a 404 error.

The code in question looks like this:

<img src="{!URLFOR($Asset.SLDS, '/assets/images/avatar1.jpg')}" alt="" />

(along with appropriate spans and divs)   Looking into the Visualforce documentation, I see that the path to assets should be without the leading slash, so the code should look like this:

<img src="{!URLFOR($Asset.SLDS, 'assets/images/avatar1.jpg')}" alt="" />
but that doesn't work, either.

Question:  how do you reference Salesforce assets in this context?

My full code is below.  (This whole module is very difficult to use because the code samples appear all on one (long) line without line breaks, making them very difficult to copy/paste.)
 

<apex:page showHeader="false" standardStylesheets="false" sidebar="false" 
           applyHtmlTag="false" applyBodyTag="false" docType="html-5.0"> 
    <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" lang="en"> 
        <head> 
            <meta charset="utf-8" /> 
            <meta http-equiv="x-ua-compatible" content="ie=edge" /> 
            <title>Salesforce Lightning Design System Trailhead Module</title> 
            <meta name="viewport" content="width=device-width, initial-scale=1" /> 
            <!-- Import the Design System style sheet --> 
            <apex:slds /> 
        </head> 
        <apex:remoteObjects > 
            <apex:remoteObjectModel name="Account" fields="Id,Name,LastModifiedDate"/> 
        </apex:remoteObjects> 
        <body>            
            <!-- REQUIRED SLDS WRAPPER --> 
            <div class="slds-scope"> 
                <!-- MASTHEAD --> 
                <p class="slds-text-heading--label slds-m-bottom--small"> 
                    Salesforce Lightning Design System Trailhead Module 
                </p> 
                <!-- / MASTHEAD --> 
                <!-- PAGE HEADER --> 
                <div class="slds-page-header" role="banner"> 
                    <div class="slds-grid"> 
                        <div class="slds-col slds-has-flexi-truncate"> 
                            <!-- HEADING AREA --> 
                            <div class="slds-media slds-no-space slds-grow"> 
                                <div class="slds-media__figure"> 
                                    <span class="slds-avatar slds-avatar--medium"> 
                                        <img src="{!URLFOR($Asset.SLDS, 'assets/images/avatar1.jpg')}" 
                                             alt="" />
                                    </span> 
                                </div> 
                                <div class="slds-media__body"> 
                                    <p class="slds-text-title--caps slds-line-height--reset">
                                        Accounts
                                    </p> 
                                    <h1 class="slds-page-header__title slds-m-right--small slds-align-middle slds-truncate" 
                                        title="My Accounts">
                                        My Accounts
                                    </h1> 
                                </div> 
                            </div> 
                            <!-- / HEADING AREA -->
                        </div> 
                        <div class="slds-col slds-no-flex slds-grid slds-align-top"> 
                            <button class="slds-button slds-button--neutral">
                                New Account
                            </button> 
                        </div> 
                    </div> 
                    <div class="slds-grid"> 
                        <div class="slds-col slds-align-bottom slds-p-top--small"> 
                            <p class="slds-text-body--small page-header__info">
                                COUNT items
                            </p> 
                        </div> 
                    </div> 
                </div> 
                <!-- / PAGE HEADER -->                
                <!-- PRIMARY CONTENT WRAPPER --> 
                <div class="myapp"> 
                    <!-- CREATE NEW ACCOUNT --> 
                    <div aria-labelledby="newaccountform"> 
                        <!-- CREATE NEW ACCOUNT FORM --> 
                        <form class="slds-form--stacked" id="add-account-form"> 
                            <!-- BOXED AREA --> 
                            <fieldset class="slds-box slds-theme--default slds-container--small"> 
                                <legend id="newaccountform" class="slds-text-heading--medium slds-p-vertical--medium">
                                    Add a new account
                                </legend> 
                                <div class="slds-form-element"> 
                                    <label class="slds-form-element__label" for="account-name">
                                        Name
                                    </label> 
                                    <div class="slds-form-element__control"> 
                                        <input id="account-name" class="slds-input" type="text" 
                                               placeholder="New account"/> 
                                    </div> 
                                </div> 
                                <button class="slds-button slds-button--brand slds-m-top--medium" type="submit">
                                    Create Account
                                </button> 
                            </fieldset> 
                            <!-- / BOXED AREA --> 
                        </form> 
                        <!-- CREATE NEW ACCOUNT FORM --> 
                    </div> 
                    <!-- / CREATE NEW ACCOUNT -->
                    <!-- ACCOUNT LIST TABLE --> 
                    <div id="account-list" class="slds-p-vertical--medium">
                        
                    </div> 
                    <!-- / ACCOUNT LIST TABLE --> 
                </div> 
                <!-- / PRIMARY CONTENT WRAPPER -->
                
                <!-- FOOTER --> 
                <footer role="contentinfo" class="slds-p-around--large"> 
                    <!-- LAYOUT GRID --> 
                    <div class="slds-grid slds-grid--align-spread"> 
                        <p class="slds-col">Salesforce Lightning Design System Example</p> 
                        <p class="slds-col">&copy; Your Name Here</p> 
                    </div> 
                    <!-- / LAYOUT GRID --> 
                </footer> 
                <!-- / FOOTER -->            
            </div> 
            <!-- / REQUIRED SLDS WRAPPER --> 
            <!-- JAVASCRIPT --> 
            <script> 
            (function() { 
                var account = new SObjectModel.Account(); 
                var outputDiv = document.getElementById('account-list'); 
                var updateOutputDiv = function() { 
                    account.retrieve( { 
                        orderby: [{ LastModifiedDate: 'DESC'}, 
                                  { Name: 'ASC'}
                                 ]//, 
                        //limit: 10 
                    }, function(error, records) { 
                        if (error) { 
                            alert(error.message); 
                        } else { 
                            // create data table 
                            var dataTable = document.createElement('table'); 
                            dataTable.className = 'slds-table slds-table--bordered slds-table--cell-buffer slds-no-row-hover'; 
                            // add header row 
                            var tableHeader = dataTable.createTHead(); 
                            var tableHeaderRow = tableHeader.insertRow(); 
                            var tableHeaderRowCell1 = tableHeaderRow.insertCell(0); 
                            tableHeaderRowCell1.appendChild(document.createTextNode('Account name')); 
                            tableHeaderRowCell1.setAttribute('scope', 'col'); 
                            tableHeaderRowCell1.setAttribute('class', 'slds-text-heading--label'); 
                            var tableHeaderRowCell2 = tableHeaderRow.insertCell(1); 
                            tableHeaderRowCell2.appendChild(document.createTextNode('Account ID')); 
                            tableHeaderRowCell2.setAttribute('scope', 'col'); 
                            tableHeaderRowCell2.setAttribute('class', 'slds-text-heading--label'); 
                            var tableHeaderRowCell3 = tableHeaderRow.insertCell(2); 
                            tableHeaderRowCell3.appendChild(document.createTextNode('Last Mod')); 
                            tableHeaderRowCell3.setAttribute('scope', 'col'); 
                            tableHeaderRowCell3.setAttribute('class', 'slds-text-heading--label'); 
                            // build table body 
                            var tableBody = dataTable.appendChild(document.createElement('tbody')); 
                            var dataRow, dataRowCell1, dataRowCell2, dataRowCell3, recordName, recordId; 
                            records.forEach(function(record) { 
                                dataRow = tableBody.insertRow(); 
                                dataRowCell1 = dataRow.insertCell(0); 
                                recordName = document.createTextNode(record.get('Name')); 
                                dataRowCell1.appendChild(recordName); 
                                dataRowCell2 = dataRow.insertCell(1); 
                                recordId = document.createTextNode(record.get('Id')); 
                                dataRowCell2.appendChild(recordId); 
                                dataRowCell3 = dataRow.insertCell(2); 
                                lastMod = document.createTextNode(record.get('LastModifiedDate')); 
                                dataRowCell3.appendChild(lastMod); 
                            }); 
                            if (outputDiv.firstChild) { 
                                // replace table if it already exists 
                                // see later in tutorial 
                                outputDiv.replaceChild(dataTable, outputDiv.firstChild); 
                            } else { 
                                outputDiv.appendChild(dataTable); 
                            } 
                        } 
                    } ); 
                } 
                updateOutputDiv(); 
            })(); 
            var accountForm = document.getElementById('add-account-form'); 
            var accountNameField = document.getElementById('account-name'); 
            var createAccount = function() { 
                var account = new SObjectModel.Account(); 
                account.create({ Name: accountNameField.value }, 
                               function(error, records) { 
                                   if (error) { 
                                       alert(error.message); 
                                   } else { 
                                       updateOutputDiv(); 
                                       accountNameField.value = ''; 
                                   } 
                               }); 
            } 
            accountForm.addEventListener('submit', 
                                         function(e) { 
                                             e.preventDefault(); 
                                             createAccount(); 
                                         }
                                        );
            </script> 
            <!-- / JAVASCRIPT -->
        </body> 
    </html> 
</apex:page>
Hi All,

I have 2 triggers written on contact object. I need to make it to one trigger and retain the functionalities of both triggers. 
 
trigger DupePreventer on contact
                               (before insert, before update) {

    Map<String, contact> contactMap = new Map<String, contact>();
    for (contact contact : System.Trigger.new) {
        
        
        if ((contact.Email != null) &&
                (System.Trigger.isInsert ||
                (contact.Email != 
                    System.Trigger.oldMap.get(contact.Id).Email))) {
        
           
    
            if (contactMap.containsKey(contact.Email)) {
                contact.Email.addError('Another new contact has the '
                                    + 'same email address.');
            } else {
                contactMap.put(contact.Email, contact);
            }
       }
    }
    
 
    for (contact contact : [SELECT Email FROM contact
                      WHERE Email IN :contactMap.KeySet()]) {
        contact newcontact = contactMap.get(contact.Email);
        newcontact.Email.addError('A contact with this email '
                               + 'address already exists.');
    }
}
 
trigger DeactivateUser on Contact (before update) 
{
	
	Map<Id, Boolean> contactToActivateDeactivate = new Map<Id, Boolean>(); 
	
	
	for(Contact contact : trigger.new)
	{
		
		
		if (contact.Blacklisted__c != trigger.oldMap.get(contact.Id).Blacklisted__c)
		{
			
			contactToActivateDeactivate.put(contact.Id, !contact.Blacklisted__c);
		}
	}

	
	
	if (!contactToActivateDeactivate.IsEmpty())
	{
		activateDeactivateUser activateDeactivateUser = new activateDeactivateUser(); //referring to class
		activateDeactivateUser.updateUser(contactToActivateDeactivate);
	} 
}

Kindly provide me solution

Thanks,
Anuj​
Hi All,

I am trying find a contact by phone number.

I'm able to find a Contact whose phone# is exactly xxxxxxxxxx or something like +xxxxxxxxxx but it can't match numbers like:

91xxxxxxxxxx(Start with country code)

xxx-xxx-xxxx

(xxx)  yyy - zzzz(multiple embedded blanks)

So, in case the phone number is not stored in correct format, the contact is not found even though the phone number is basically the same.
Hi all,
I want to validate the custom check box before submitting Force.com sites custom vfpage. Can we use standard validation over here...? because i want to make the check box as mandetory. how can we achive this. Can anyone help me over here.

Thanks in advance.
regards,
Suneel.
Hi I have a custome clone button which will take the user to a visualforce page. However, everytime I try to save the record and open in Edit mode, I noticed the URL still says Clone = 1 even though I speficially assigned an url. Please help. 

Here's the URL :

User-added image

This is after I have saved the record. 

In my Pagerefence I have assigned the new record ID to refresh the page and route user to the correct page. 
pv = new Pagereference('/'+controller.getId() +'/e?&retUrl=%2F'+controller.getId())

This should save the record and take the user to edit page of the newly created record. However, I see the URL still have the Clone = 1. 

How do I get rid of this? Please help. 
 
I had a requirement to identify all Salesforce reports that were filtered on certain standard fields, stagename values, and a custom field (all of which were being changed). Salesforce provides very nice documentation of the Reports and Dashboards REST API, but I didn't find any sample code.

I have published my work, in python, at a gist named SearchSalesforceReports. I'm publishing the code below as well, for easier searching. It works by extending simple_salesforce; this technique is useful for other Salesforce APIs too.
 
#!/usr/local/bin/python3


# https://developer.salesforce.com/docs/atlas.en-us.api_analytics.meta/api_analytics/sforce_analytics_rest_api_getbasic_reportmetadata.htm

import pdb
import json
from collections import OrderedDict
import config
from progressbar import ProgressBar


import simple_salesforce

class SFDC(simple_salesforce.Salesforce):
    def __init__(self, username=None, password=None, security_token=None,
                sandbox=False, version=config.DEFAULT_API_VERSION):
        super(SFDC, self).__init__(username=username, password=password, security_token=security_token,
                                    sandbox=sandbox, version=version)


    def describeReport(self, id):
        """Describes report with given id
        """
        url = self.base_url + "analytics/reports/{}/describe".format(id)
        result = self._call_salesforce('GET', url)
        if result.status_code != 200:
            raise SalesforceGeneralError(url,
                                         'describe',
                                         result.status_code,
                                         result.content)
        json_result = result.json(object_pairs_hook=OrderedDict)
        # json_result = result.json()
        if len(json_result) == 0:
            return None
        else:
            return json_result

def init():
    salesforce_credentials = json.loads(open(config.SFDC_CONFIGFILE).read())

    username = salesforce_credentials['user']

    if salesforce_credentials['sandbox']:
        username += '.' + salesforce_credentials['sandbox']
        config.SFDC_URL = 'https://canonical--staging--c.cs87.visual.force.com/'
    else:
        config.SFDC_URL = 'https://eu1.salesforce.com/';

    sfdc = SFDC(username=username, 
                      password=salesforce_credentials['password'], 
                      security_token=salesforce_credentials['token'], 
                      sandbox=salesforce_credentials['sandbox'],
                      version=config.DEFAULT_API_VERSION)
                      
    return sfdc

reportFields = [
    'Id'
    ,'Name'
    # ,'FolderName'
    ,'DeveloperName'
    ,'CreatedDate'
    ,'CreatedBy.Name'
    ,'LastRunDate'
    ,'LastModifiedBy.Name'
    ,'LastModifiedDate'
    ,'LastViewedDate'
    ,'Description'
]


def dumpHeader():
    print('\t'.join([
        'FolderName'
        ,'Name'
        ,'CreatedDate'
        ,'LastModifiedDate'
        ,'LastRunDate'
        ,'CreatedBy.Name'
        ,'LastModifiedBy.Name'
        ,'Note'
        ,'Url'
    ]))

def quotify(s):
    if s == None:
        return '';

    s = str(s)
        
    if len(s) == 0:
        return '';
    return '"' + s.replace('\n', '\\n').replace('"', '\"') + '"'


def get(dict, keys):
    if not keys:
        return dict
        
    if not isinstance(keys, list):
        return dict[keys]
    
    return get(dict[keys.pop(0)], keys)
    
        
def dumpReport(folderName, reportJson, reportRecord, sfdcUrl, note):
    print('\t'.join([quotify(cell) for cell in 
                        [folderName] +
                        
                        [reportJson['reportMetadata']['name']] + 
                        
                        [get(reportRecord, keys) for keys in [
                            'CreatedDate'
                            , 'LastModifiedDate'
                            , 'LastRunDate'
                            , ['CreatedBy', 'Name']
                            , ['LastModifiedBy', 'Name']
                        ]] +
                        [note] +
                        [sfdcUrl + reportJson['reportMetadata']['id']]
            ]))
    pass
    


# queryWhereClause = "where id = '00OD00000072LjH'"
queryWhereClause = ""

relevantStageNames = ['Value Proposition', 'Negotiation/Review', 'Proposal']

def relevant(reportJson):
    stages = []
    if reportJson and 'reportMetadata' in reportJson:
        for filter in reportJson['reportMetadata']['reportFilters']:
            if filter['column'] == 'Renewal__c':
                return 'Renewal__c'

            if filter['column'] == 'FORECAST_CATEGORY':
                return 'Forecast Category'
                
            elif filter['column'] == 'STAGE_NAME':
                values = filter['value'].split(',')
                for value in relevantStageNames:
                    if value in values:
                        return 'Stage'
                
    return None
    

def getFolderName(reportJson, folderNamesById):
    folderId = reportJson['reportMetadata']['folderId']
    folderName = ''
    if folderId in folderNamesById:
        folderName = folderNamesById[folderId]
    elif folderId.startswith('005'):
        folderName = 'My Personal Custom Reports'
    elif folderId.startswith('00D'):
        folderName = 'Unfiled Custom Reports'
    else:
        folderName = folderId
        
    return folderName
        
                    
def main():
    sfdc = init()
    
    sfdcUrl = 'https://{instance}/'.format(instance=sfdc.sf_instance)
    
    folderNamesById = {}
    for folder in sfdc.query_all("select Id, Name from folder")['records']:
        folderNamesById[folder['Id']] = folder['Name']
    
    result = sfdc.query_all("select {} from report {} ".format(','.join(reportFields), queryWhereClause))

    dumpHeader()
    progressbar = ProgressBar()
    for reportRecord in progressbar(result['records']):
        reportJson = None
        try:
            reportJson =  sfdc.describeReport(reportRecord['Id'])
        except Exception as e:
            if e.status == 501:
                pass
            else:
                pdb.set_trace()
                print(reportRecord['Id'], str(e))

        relevance = relevant(reportJson)
        if relevance:
            folderName = getFolderName(reportJson, folderNamesById)
                        
            try:
                dumpReport(folderName, reportJson, reportRecord, sfdcUrl, relevance)
            except Exception as e:
                pdb.set_trace()
                print(reportRecord['Id'], str(e))
            continue
            
    
    
if __name__ == "__main__":
    main()
    pass

 
Is that possible to restrict some user to be owner of any "Accounts" and "contacts". They can create but they cannot be owner of the Account or Contact.

Not sure if it possible. 
Hi,

 In below trigger am getting too many soql query in line 65 Please suggest me how to modify this issue to resolve. 

  /* Get subscription list of all quote id */
    list<QuoteLineItem> subqtlne = [select id  from  QuoteLineItem
                               where quoteid in :listIds and
                                     Subscription_Terms__c <> 0];


 
trigger GenQuoteApproval on QuoteLineItem (After Insert, After Update,After Delete) {

  Decimal LineMaxDiscount;
  Decimal LineMaxACV;
  Decimal SubLineMaxDiscount;
  Decimal SubLineMaxACV;
  Decimal SerLineMaxDiscount;
  Decimal SerLineMaxACV;
  Decimal TraLineMaxDiscount;
  Decimal TraLineMaxACV;
  Map<ID, Quote> ParentQuote = new Map<ID, Quote>();
  String SALREPID;
  String MRGID;
  String SALID;
  String CFOID;
  String SERID;
  String TRAID;
  String Level;
  Integer GSublevel1Count;
  Integer GSublevel2Count;
  Integer GSublevel3Count;
  Integer GSublevel4Count;
  Integer GSerlevel1Count;
  Integer GSerlevel2Count;
  Integer GSerlevel3Count;
  Decimal SubscriptionTerm;
  Integer GTralevel1Count;
  Integer GTralevel2Count;
  Integer GTralevel3Count;
 

 
Try 
{
if ( Trigger.isAfter)
  {
 List<Id> listIds = new List<Id>();
 //Set<Id> listIds = new Set<Id>();

 List<Quote> QuotetList = new List<Quote>();

 /* Get Quote ID */
 for (QuoteLineItem childquoteline :  Trigger.new)
 {
        listIds.add(childquoteline.QuoteId);
    }
 
   
 ParentQuote = new Map<Id, Quote>([SELECT id,Level_1__c,Level_2__c,Level_3__c,Level_4__c,Level_5_Service__c,Level_6_Training__c FROM Quote WHERE ID IN :listIds]);
 
  /* Get service list of all quote id */
   list<QuoteLineItem> serqtlne = [select id  from  QuoteLineItem
                                     where quoteid in :listIds and
                                           product2.Productcode  like 'CBSVC%'];
   
  list<id> serviceid = new list<id>();
  for(QuoteLineItem getserviceid :  serqtlne)
   {
      serviceid.add(getserviceid.id);

   }


  /* Get subscription list of all quote id */
    list<QuoteLineItem> subqtlne = [select id  from  QuoteLineItem
                               where quoteid in :listIds and
                                     Subscription_Terms__c <> 0];
                                     
  list<id> subscriptionid = new list<id>();
  for(QuoteLineItem getsubscriptionid :  subqtlne )
   {
      subscriptionid.add(getsubscriptionid.id);

   }

 /* Subscription Discount and ACV */
    List<AggregateResult> MaxSubscription = [select max(Discount_Percent__c) SubQuoteLineMaxDiscount,sum(f_ACV__c) SubQuoteLineMaxACV
                                                   from  QuoteLineItem
                                                   where quoteid in :listIds and Subscription_Terms__c <> 0 and
                                                         ID not in :serviceid
                                                 ];

  for (AggregateResult SubQuoteMaxDiscount : MaxSubscription)
  {
  SubLineMaxDiscount = (Decimal)SubQuoteMaxDiscount.get('SubQuoteLineMaxDiscount');
  SubLineMaxACV = (Decimal)SubQuoteMaxDiscount.get('SubQuoteLineMaxACV');
  }

   system.debug('Subscription Line Discount  :' + SubLineMaxDiscount);
   system.debug('Subscription Line ACV  :' + SubLineMaxACV);

   /* Service Discount and ACV */
  List<AggregateResult> MaxService = [select max(Discount_Percent__c) SerQuoteLineMaxDiscount,SUM(f_ACV__c) SerQuoteLineMaxACV
                                      from  QuoteLineItem
                                      where quoteid in :listIds and product2.Productcode  like 'CBSVC%' and
                                            id not in :subscriptionid];

  for (AggregateResult SerQuoteMaxDiscount : MaxService)
  {
  SerLineMaxDiscount = (Decimal)SerQuoteMaxDiscount.get('SerQuoteLineMaxDiscount');
  SerLineMaxACV = (Decimal)SerQuoteMaxDiscount.get('SerQuoteLineMaxACV');
  }

   system.debug('Service Line Discount  :' + SerLineMaxDiscount);
   system.debug('Service Line ACV  :' + SerLineMaxACV);
   
   
   /* Training Discount and ACV */
  List<AggregateResult> MaxTraining = [select max(Discount_Percent__c) TraQuoteLineMaxDiscount,SUM(f_ACV__c) TraQuoteLineMaxACV
                                      from  QuoteLineItem
                                      where quoteid in :listIds and product2.Productcode  like 'T%' and
                                            id not in :subscriptionid and id not in :subscriptionid];

  for (AggregateResult TraQuoteMaxDiscount : MaxTraining)
  {
  TraLineMaxDiscount = (Decimal)TraQuoteMaxDiscount.get('TraQuoteLineMaxDiscount');
  TraLineMaxACV = (Decimal)TraQuoteMaxDiscount.get('TraQuoteLineMaxACV');
  }

   system.debug('Training Line Discount  :' + TraLineMaxDiscount);
   system.debug('Training Line ACV  :' + TraLineMaxACV);
   

  Opportunity Opp = [select ownerid
                    from opportunity
                    where
                    id in (select OpportunityId from quote where id in :listIds) ];

  system.debug(listIds);
  
  SubscriptionTerm = ApprovalUtils.GetSubscriptionTerm(listIds);
  

  system.debug('Get New Subscription Term' + SubscriptionTerm);
  
  /* Get Manager ID */
  User Usr = [select managerid from user where id = :opp.ownerid];

 /* Subscription Query to get level 1..4 values */
   if ( SubscriptionTerm != null &&
        SubLineMaxACV != null &&
        SubLineMaxDiscount != null)
   {
       GSublevel1Count = ApprovalUtils.SubLevel1(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level1 :' + GSublevel1Count);

       GSublevel2Count = ApprovalUtils.SubLevel2(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level2 :' + GSublevel2Count);

       GSublevel3Count = ApprovalUtils.SubLevel3(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level3 :' + GSublevel3Count);

       GSublevel4Count = ApprovalUtils.SubLevel4(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level4 :' + GSublevel4Count);

        
   }    
   
      /* Service Query to get level 1..4 values */
   if (SerLineMaxACV != null && SerLineMaxDiscount != null)
    {
       GSerlevel1Count = ApprovalUtils.SerLevel1(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level1 :' + GSerlevel1Count);

        GSerlevel2Count = ApprovalUtils.SerLevel2(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level2 :' + GSerlevel2Count);

        GSerlevel3Count = ApprovalUtils.SerLevel3(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level3 :' + GSerlevel3Count);
    } 
    
        /* Training Query to get level 1..4 values */
   if (TraLineMaxACV != null && TraLineMaxDiscount != null)
    {
        GTralevel1Count = ApprovalUtils.TraLevel1(TraLineMaxACV,TraLineMaxDiscount);
        system.debug('Training Level1 :' + GTralevel1Count);
        
        GTralevel2Count = ApprovalUtils.TraLevel2(TraLineMaxACV,TraLineMaxDiscount);
        system.debug('Training Level2 :' + GTralevel2Count);
        
        GTralevel3Count = ApprovalUtils.TraLevel3(TraLineMaxACV,TraLineMaxDiscount);
        system.debug('Training Level3 :' + GTralevel3Count);
    }
    
     If( GSublevel1Count >= 1  || GSerlevel1Count >= 1  || GTralevel1Count >= 1)
     {
      SALREPID = Opp.OwnerId;
      }   
     
     
    If (GSublevel2Count >= 1 || GSerlevel2Count >= 1  || GTralevel2Count >= 1)
    {
      SALREPID = NULL;
      MRGID = Usr.managerid;
    }
 
    /* Future here you may have to change for amount > 1000000 if its going only to SVP */
   If ( GSublevel3Count >= 1 || GSerlevel3Count >= 1 ||  GTralevel3Count >= 1)
      {
      SALREPID = NULL;
      MRGID = Usr.managerid;
      SALID = '00580000007jaoA';
      }
   
    /* Assign this to Pete */ 
    If ( GTralevel3Count >= 1)
    {
     TRAID = '00580000006GbpI';
     }
    else
    {
     TRAID = NULL;
     }  
     
     /* Asssing to asif */
    If ( GSerlevel3Count >= 1)
    {
     SERID = '0053400000839zg';
     }
    else
    {
     SERID = NULL;
     } 
      
    If ( GSublevel4Count >= 1 )
    {
    SALREPID = NULL;
    MRGID = Usr.managerid;
    SALID = '00580000007jaoA';
    CFOID = '00534000008oOCr';
    Level = '4sub';
    }  
  
    //system.debug('Which Level :' + Level);
    system.debug('Sales Rep :' + SALREPID);
    system.debug('Manager :' + MRGID);
    system.debug('Sales Ops :' + SALID);
    system.debug('CEO CFO :'  + CFOID);
    system.debug('Service:' + SERID);
    system.debug('Training:' + TRAID);
 
  
for (QuoteLineItem gqtl : Trigger.new)
 {
   Quote MyParentQuote = ParentQuote.get(gqtl.QuoteId);

    MyParentQuote.Level_1__c = SALREPID;
    MyParentQuote.Level_2__c=MRGID;
    MyParentQuote.Level_3__c=SALID;
    MyParentQuote.Level_4__c=CFOID;
    MyParentQuote.Level_5_Service__c = SERID;
    MyParentQuote.Level_6_Training__c = TRAID;
 
  }

  update ParentQuote.values();
  

 }
  
}

catch(Exception e) {
    System.debug('The following exception has occurred: ' + e.getMessage());    
}
  
}


Thanks

Sudhir

  • November 16, 2016
  • Like
  • 0
From my research, the REST API does not support lead conversion.  I am using the Group Edition for SalesForce, so I don't have access to the "Enterpise API (WSDL)).  Am I correct that the API does not support conversion?  If I were to write my own, does the conversion simply do:

1. Create Contact
2. Create Account
3. Set Lead status to converted

Is there anything else it does behind the scenes?