• willard
  • NEWBIE
  • 254 Points
  • Member since 2010
  • Frontera Consulting


  • Chatter
    Feed
  • 7
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 58
    Replies
Hi everyone,

We have multiple records (same record type) and User input percentage field. We need to make sure sum of that field is 100%. Is there any way of validating it in Visualforce page or so?

For example,

Record A    50%
Record B    25%
Record C    based on the inputs above percent for this record must be 25%


Kind regards,

Elgun
Hello,

I have a trigger (below) that is meant to take the value from a custom field on the Account object and copy it to a custom field on related Opportunities that are not closed won or closed lost, but only when the value in the Account field changes.  The trigger saves without any errors, but the value does not write over to the Opportunity.  Can anyone help me figure out why the value is not pulling through?  Thanks,


trigger UpdateConsultant on Account (after update){
       
List<Account> acct = new List<Account>();

FOR(Account a : Trigger.new){

// Query Opportunity records realted to Account that is being created/edited
    List<Opportunity> opps = [SELECT AccountId, IsWon, IsClosed, Consultant_Partner__c, Consultant_Type__c
                              FROM Opportunity
                              WHERE AccountId IN: Trigger.newMap.keySet()];
       
        // Iterating through all the Opportunity records and updating them as per the conditions
        for(Opportunity opps2 :opps){

            // Update Consultant Partner field on Opportunity if Opp is Open and Consultant field changes at Account level
            IF(opps2.IsWon == FALSE && opps2.IsClosed == FALSE && opps2.Consultant_Type__c == 'Primary Consultant' && trigger.NewMap.get(opps2.AccountId).Consultant_Partner_Primary__c != trigger.OldMap.get(opps2.AccountId).Consultant_Partner_Primary__c){
                opps2.Consultant_Partner__c = a.Consultant_Partner_Primary__c;
            }
           
            ELSE IF(opps2.IsWon == FALSE && opps2.IsClosed == FALSE && opps2.Consultant_Type__c == 'Secondary Consultant' && trigger.NewMap.get(opps2.AccountId).Consultant_Partner_Secondary__c != trigger.OldMap.get(opps2.AccountId).Consultant_Partner_Secondary__c){
                opps2.Consultant_Partner__c = a.Consultant_Partner_Secondary__c;
            }
        }
       
        // Update all realted Opportunity records
//        IF(opps.size() > 0)
            update opps;
}
}
  • January 23, 2014
  • Like
  • 0
Does anyone know how I can get the Account Name and use it for the String Customer without doing a SOQL Query?

I'm trying to populate the String 'Customer' with Account Name, which is a look up from the Escalation__c object.

This is my Apex controller extension:

public with sharing class addCasesToEscalation{
    public Escalation__c theEsc {get;set;}
    public String searchString {get;set;}
    public Case[] shoppingCart {get;set;}
    public Case[] AvailableCases {get;set;}
    
    public String toSelect {get; set;}
    public String toUnselect {get; set;}
    public Decimal Total {get;set;}

    public Boolean overLimit {get;set;}
    public Id EscId {get;set;}
    public Id AcctId {get;set;}
   
    //using this for PDF report attachment
    public String pdfName {get;set;}
    public String Customer {get;set;}
 
    private Case[] forRemoval = new Case[]{};
    private Set<Case> clean = new Set<Case>();

    public addCasesToEscalation(ApexPages.StandardController controller) {

       
        // Get information about the Escalation being worked on
            system.debug(controller.getRecord());
            Escalation__c theEsc = (Escalation__c)controller.getRecord();
            EscId = theEsc.Id;
           
           
        // If cases were previously selected need to put them in the "selected cases" section to start with
        shoppingCart = [select Id, CaseNumber, Subject, Status, Priority, IsClosed, CreatedDate, Escalation__c from Case where Escalation__c=:EscId order by CreatedDate Desc];

            }
   

    public void updateAvailableList() {
   
        // We dynamically build a query string and exclude items already in the shopping cart
        String qString = 'select Id, CaseNumber, Subject, Status, Priority, CreatedDate, Escalation__c, IsClosed From Case WHERE AccountId = :AcctId';
       
        // note that we are looking for the search string entered by the user in the name OR description
        // modify this to search other fields if desired
        if(searchString!=null){
            qString+= ' and (Subject like \'%' + searchString + '%\' or CaseNumber like \'%' + searchString + '%\')';
        }
       
        Set<Id> selectedEntries = new Set<Id>();
        for(Case c : shoppingCart){
            selectedEntries.add(c.Id);
        }
       
        if(selectedEntries.size()>0){
            String tempFilter = ' and Id not in (';
            for(Id i : selectedEntries){
                tempFilter+= '\'' + (String)i + '\',';
            }
            String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
            extraFilter+= ')';
           
            qString+= extraFilter;
        }
              
        qString+= ' order by CreatedDate Desc';
        qString+= ' limit 101';
       
        system.debug('qString:' +qString);       
        AvailableCases = database.query(qString);
       
        // We only display up to 100 results... if there are more then we let the user know (see vf page)
        if(AvailableCases.size()==101){
            AvailableCases.remove(100);
            overLimit = true;
        }
        else{
            overLimit=false;
        }
     
    }
   
    public void addToShoppingCart(){
   
        // This function runs when a user hits "select" button next to a product
   
        for(Case c : AvailableCases){
            if((String)c.Id==toSelect){
                c.Escalation__c = EscId;
                shoppingCart.add(c);
                break;
            }
        }
       
        updateAvailableList(); 
    }
   

public PageReference removeFromShoppingCart(){
   
        // This function runs when a user hits "remove" on an item in the "Selected Cases" section
   
        Integer count = 0;
        for(Case ce : shoppingCart){

            if((String)ce.Id==toUnselect){
               
                if(ce.Id!=null&&ce.Escalation__c != null){
                    ce.Escalation__c = null;
                    forRemoval.add(ce);}
                shoppingCart.remove(count);
                break;            
            }
            count++;
        }
       
        updateAvailableList();
       
        return null;
    }
   
    public PageReference onSave(){
   
        // If previously selected devices are now removed, we need to delete them
        if(forRemoval.size()>0)
            //this is a somewhat hackey way to clean the list just in case there are duplicate cases in the list
            clean.addAll(forRemoval);
            forRemoval.clear();
            forRemoval.addAll(clean);
            update(forRemoval);
   
        // Update cases in shoppingCart
            if(shoppingCart.size()>0)
                update(shoppingCart);
       
        // After save return the user to the Escalation
        return new PageReference('/' + EscId);
    }
   
    public PageReference onCancel(){

        // If user hits cancel we commit no changes and return them to the Escalation  
        return new PageReference('/' + EscId);
    }
   
   //pdf attach extension
    public PageReference savePdf() {

    PageReference pdf = Page.escalationReport;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',EscId);

    // create the new attachment
    Attachment attach = new Attachment();

    // the contents of the attachment from the pdf
    Blob body;

    try {

        // returns the output of the page as a PDF
        body = pdf.getContent();

    // need to pass unit test -- current bug   
    } catch (VisualforceException e) {
        body = Blob.valueOf('Something went wrong');
    }
       
    pdfName = Customer + ' escalation report as of '+String.valueOf(System.today());
    attach.Body = body;
    // add the user entered name
    attach.Name = pdfName;
    attach.IsPrivate = false;
    // attach the pdf to the account
    attach.ParentId = EscId;
    insert attach;

    // send the user to the account to view results
    return new PageReference('/'+EscId);

  }
   
}
Is there a way to pull in permission sets into an apex class? We are looking to restrict the ability for users to click on the submit to finance button (custom JS button on the opportunity page layout).  Creating a new profile and page layout isn't an option for a solution, so I was wondering if there was a way to prevent a user from clicking on this button if they do not belong to a specific permission set.  For example, only our Order Admin team can submit opportunities to Finance - these folks have their own permission set called Order Admins.
Thanks for your help!

Hi,

 

I have 5 controller classes and one visualforce page. The code coverage for my classes is 98% in 3classes and 100% in 2classes. The above code coverage is in my sandbox environment. But when i move my code to Development and validate am getting the following error.

'Average test coverage across all Apex Classes and Triggers is 71%, at least 75% test coverage is required'.

 


Please help me...

I'm new with triggers and am having trouble with making one work.

 

I have a child custom object called "Actividad" which has a formula field called "Actor Principal Indicador" that gets updated from a field in its' parent object "Indicador".

"Actividad" is also parent for the object "Entidad participante".

 

What I want my trigger to do is to update a field ("Actor Principal Indicador" - yes, it has the same name as the field in the other object) in "Entidad participante" getting the value from its parent's field "Actor Principal Indicador" (which originally gets its value from the "Indicador" objetc)

 

Is this possible?

Any help would be appreciated!

 

This is what I have so far:

 

trigger ActualizarActorPrincipal on Actividad__c (after update, after insert) {
   Set<ID> IDActividad = new Set<ID>();
    for(Actividad__c A: Trigger.new){
        List<Actividad__c> ActividadActualizada = [SELECT Id, Actor_principal_indicador__c, (Select Id, Actor_principal_indicador__c from Organizaciones_participantes__r)  FROM Actividad__c WHERE Id in :IDActividad];
        List<Entidad_participante__c> EntParticipActualizar = new List<Entidad_participante__c>();
    for (Actividad__c AA: ActividadActualizada){
        for(Entidad_participante__c EP : AA.Organizaciones_participantes__r){  if(EP.Actor_principal_indicador__c == null)
            EP.Actor_principal_indicador__c = AA.Actor_principal_indicador__c;
       EntParticipActualizar.add(EP);
                }
        
   
            update EntParticipActualizar;
       }
    }}

Hi,

 

We are about to start an integration effort and IT shown me a Schema that has a header record.  The contract that we have on our team has said that because of the header information that is required we will have to actually build the XML SOAP format and send it.  I have always tried to be proactive in learning but I cannot find any concrete examples where I would build the XML Soap package and send it in an HTTP transmission.  The contractor said when we get to the point of developing he would show me somethings but I want to learn this stuff sooner rather than later.  Does anyone have any code examples that make sense based on what I have described.  This web service stuff is completely new for me.  He mentioned using XMLDom in this effort.

 

I need something that explains this stuff from the ground up and I really have not seen anything in SFDC's sight that demonstrates the method above.  I have imported a WSDL and made the call to the currency converter and that was a piece of cake but as the contractor stated since IT wants this header information we have to build the XML programmatically and that is where I have not been successful in getting examples from him at this point.  Again I like to be proactive so any help is appreciated.

 

 

I have my own personal developer org and I'm trying to play around with sharing settings.  I found this article to help out with logging in as different users: http://help.salesforce.com/apex/HTViewSolution?id=000089838&language=en_US

 

However, whenever I try to contact salesforce, it says I am unauthorized.  I am assuming it's b/c this is a free developer org.  Is that the case, or am I just not going the right way in contacting salesforce?

 

The way that I did it was to click the 'help' link at the top right corner of the page, click 'Contact Support', and then click 'Open A Case'.  It always brings me back to the Salesforce Help homepage (https://help.salesforce.com/hthome?err=1)

 

Any ideas on how to contact salesforce support to get this enabled in my org?

So I upgraded my force.com IDE according to the instructions here:

http://wiki.developerforce.com/page/Updating_the_Force.com_IDE

 

It looked like it was successful, and the IDE has been restarted.

 

However, when I try to create a new apex class, the only version available in the dropdown is 26.0.  How can I get this so that I can choose later API versions when creating new classes?

 

  • September 18, 2013
  • Like
  • 0

So here's my scenario.

 

  • I am updating 400 Subscription rows via an API call (all rows updated successfuly)
  • Each update is for a different subscription (no overlaps)
  • There is one trigger on Subscription that calls a Batch job (once for every trigger invocation, i.e., runs twice for 400 updates)
  • The batch job takes each subscription and creates an Opportunity off of it.  There are no updates to opportunities in this batch job.  One thing to note is that I am using Database.insert(objs) and not insert objs
  • I have turned off all triggers on the Opportunity to ensure this was not causing the error

I am still getting the "unable to obtain exclusive access to this record" error.  I can't figure this out since these are inserts.  Why would it be giving me this error when there is currently no row to lock?

 

 

I'm having some issues getting the values in my var attribute when using apex:column and apex:outputText.

 

Say I have the following pageBlockTable:

<apex:pageBlockTable value="{!charges}" var="a" id="adjustment_charges">
  <apex:column headerValue="Amend Action" value="{!a.Local_Price__c}" />
  <apex:column headervalue="test">
    <apex:outputText >
       <apex:param value="{!a.Local_Price__c}"/>
     </apex:outputText>
                    
   </apex:column>
</apex:pageBlockTable>

 For me, the first column prints out the local price, while the second "test" column prints out blank

 

Any ideas what I am doing wrong?

Is there an easy way to merge two SObjects?  Right now I have one method that spits out some opportunities with certain values filled in, i.e., CloseDate, Stage, etc..  I have another method that spits out some opportunities with other values filled in, ie. Amount, UpgradeAmount, etc.

 

Is there an easy way to combine these two SObjects into one with the new SObject having all the fields populated?

 

Something like a copyFieldsTo method:

Id oppId = '<someid>';
Opportunity opp1 = new Opportunity(Id = oppId, closedate = today, ...);
Opportunity opp2 = new Opportunity(Id = oppId, amount = 100, ...);
opp1.copyFieldsTo(opp2);

// opp2 will now have amount AND closedate populated

 

Hi - not sure if this is the place to post this type of thing as it is not really a question, but more of a hope this helps others post.

 

I have found that I have needed to create a map of type Map<Id, Opportunity> in many triggers, so I decided to create a small method to genericize this type of behavior.   I'm sure this method can be genericized further so that it can create a map of any SObject, not just opportunity, but I just don't have the time to do that =)

 

Hope this helps others.  Would also gladly accept feedback on ways to improve the code as I'm not really a seasoned apex developer:

 

    /**
     * @description Return an opportunityMap for objects that
     * 				have a lookup or parent-child relationship to opportunity
     * @param sObjects the list of sObjects that have opportunity id
     * @param oppFieldName the field name that has the opportunity id
     * @param oppSelectFields the list of opportunity fields to select
     */
    public static Map<Id, Opportunity> generateOppMap(List<SObject> sObjects, 
    		String oppFieldName, String[] oppSelectFields) {
    			
    	Set<Id> opportunityIds = new Set<Id>();
    	for (SObject so : sObjects) {
    		if (so.get(oppFieldName) != null) {
    			opportunityIds.add((Id) so.get(oppFieldName));
    		}
    	}
    	
    	// Prepare the select string
    	String selectString;
    	for (String oppField : oppSelectFields) {
    		oppField = oppField.trim();
    		if (selectString == null) {
    			selectString = String.escapeSingleQuotes(oppField);
    		} else {
    			selectString += ',' + String.escapeSingleQuotes(oppField);
    		}
    	}
    	String query = 'SELECT ' + selectString + ' FROM Opportunity ' +
    			'WHERE Id in :opportunityIds';
    	
    	Opportunity singleOpp;
    	Opportunity[] opps;
    	if (opportunityIds.size() == 1) {
    		singleOpp = Database.query(query);
    	} else {
    		opps = Database.query(query);
    	}
    	
    	if (opps == null) {
    		opps = new List<Opportunity>();
    		opps.add(singleOpp);
    	}
    	
    	Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
    	for (Opportunity opp : opps) {
    		oppMap.put(opp.Id, opp);
    	}
    	
    	return oppMap;

    }

 

 

 

Hi - I was wondering how customizable the live agent pop-up window is.  I'm not a javascript expert so I am unsure how to do these things or whether they are even possible.  Any help is appreciated.

 

  • Can you set the position of the pop-up when they click the "chat" button?
  • Can you set the size of the pop-up?
  • When you click "end chat", is it possible to close the entire window as well (instead of having to click the 'x' on the window)

Hi.  I have a pageBlockTable with two columns:  Edition Type (picklist) and Edition Code (selectList).  Based on the Edition Type, the Edition Code field will populate with different SelectOptions.  If the editionType changes, the editionCode field will re-populate accordingly.

 

I am currently unsure on how I am supposed to know which row in the table caused the action, i.e., if there are 3 rows, how do I know to change only row #2?  Any ideas on how I would figure that out?

            <apex:pageBlockTable value="{!editions}" var="edn" id="editionTable">
                <apex:column headerValue="Edition Type">
                	<apex:inputField value="{!edn.Edition_Type__c}">
                		<apex:actionSupport event="onchange" rerender="pricingDetails"/>
                    </apex:inputField>
                </apex:column>
                <apex:column headerValue="Edition Code">
                    <apex:pageBlockSectionItem >
		                <apex:selectList value="{!edn.Edition_Code__c}" id="editionCode" size="1">
		                    <apex:selectOptions value="{!editionCodes}"/>
		                </apex:selectList>
		            </apex:pageBlockSectionItem>
                </apex:column>
            </apex:pageBlockTable>

 controller:  In the select statement, I need another clause in the Where portion of the statement, i.e.

WHERE b.publication__c = :pricing.business_unit__c AND b.editionType__c = ?????????

    public List<SelectOption> getEditionCodes() {
        List<BossEdition__c > editions = [Select b.editionCode__c, b.Name from BossEdition__c b 
        			where b.publication__c = :pricing.business_unit__c 
order by b.Name]; List<SelectOption> options = new List<SelectOption>(); for (BossEdition__c edn : editions) { options.add(new SelectOption(edn.editionCode__c, edn.Name + ' (' + edn.editionCode__c + ')')); } return options; }

 

I've already seen the examples where you can set "CANADA" to be the default country when the selectListOptions are a known quantity.

 

However, I have to generate a selectList dynamically, and then based on the result set, choose an appropriate default.

 

I have a business_unit field.  Once I pick a business_unit, I need to populate a BOSS Unit field.  However, the default BOSS Unit may be different for each publication.  Here's what I have:

            <apex:pageBlockSectionItem >
                <apex:outputLabel value="BOSS Unit" for="bossUnit"/>
                <apex:selectList value="{!defBossUnit}" id="bossUnit" size="1">
                    <apex:selectOptions value="{!BOSSUnits}"/>
                </apex:selectList>
            </apex:pageBlockSectionItem>

 

Here's my controller code.  Basically some business_units have the default as PG, others as PAGE:

    public List<SelectOption> getBOSSUnits() {
        List<BossUnitSize__c > units = [Select b.Name, b.UnitSize__c from BossUnitSize__c b where b.SetID__c = :pricing.business_unit__c
                    order by b.Name];
        List<SelectOption> options = new List<SelectOption>();
        for (BossUnitSize__c unit : units) {
            options.add(new SelectOption(unit.unitSize__c, unit.Name));
            if (unit.Name == 'PAGE' || unit.Name == 'PG') {
                defBossUnit = unit.Name;
            }
        }
        
        return options;
    }

 The above code does NOT default the defBossUnit correctly.  Any ideas?

Is there a way?  I am trying to debug, but I cannot see the full status detail on the apex jobs monitor.

 

I am invoking a job that sends a synchronous job to a external webservice.  The webservice call is fine, but I am getting an error back when processing the response.  I cannot see the entire error so am having trouble debugging.

I have created a very simple service in peoplesoft.  All it does is take two numbers and returns the sum.  I know this service works through manually sending soap requests to the service.

 

I am able to generate apex classes via the wsdl2apex generator.

 

However, when I use those classes to do the callout, I get the following error:

System.CalloutException: Web service callout failed: Unable to parse callout response. Apex type not found for element http://xmlns.oracle.com/Enterprise/Tools/schemas/TI_RESULT_SIMPLE.V1=result 

 

Class.BOSSMathService.MathServiceSimple_Port.Add: line 20, column 13
Class.PricingCalculator.test: line 78, column 48
External entry point

 

My generated class:

 

//Generated by wsdl2apex

public class BOSSMathService {
    public class MathServiceSimple_Port {
        public String endpoint_x = 'http://mypsoftwebsite.com/PSIGW/PeopleSoftServiceListeningConnector';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'http://xmlns.oracle.com/Enterprise/Tools/schemas/TI_ADD_SIMPLE.V1', 'BOSSAddInput', 'http://xmlns.oracle.com/Enterprise/Tools/schemas/TI_RESULT_SIMPLE.V1', 'BOSSResult', 'http://xmlns.oracle.com/Enterprise/ERP/services/MathServiceSimple.1', 'BOSSMathService'};
        public Integer Add(Integer num1,Integer num2) {
            BOSSAddInput.Add_element request_x = new BOSSAddInput.Add_element();
            BOSSResult.ResultGroup_element response_x;
            request_x.num1 = num1;
            request_x.num2 = num2;
            Map<String, BOSSResult.ResultGroup_element> response_map_x = new Map<String, BOSSResult.ResultGroup_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'Add.V1',
              'http://xmlns.oracle.com/Enterprise/Tools/schemas/TI_ADD_SIMPLE.V1',
              'Add',
              'http://xmlns.oracle.com/Enterprise/Tools/schemas/TI_RESULT_SIMPLE.V1',
              'ResultGroup',
              'BOSSResult.ResultGroup_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.result;
        }
    }
}

 

 

Here is the code that invokes the callout:

 

BOSSMathService.MathServiceSimple_Port msp = new BOSSMathService.MathServiceSimple_Port();
		
System.debug('result = ' + String.valueOf(msp.ADD(4, 10)));

 

 

I know the request is being processed and that something is being returned from PeopleSoft via the Psoft logs.  Here is the raw xml coming back from the service:

 

 

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <ResultGroup xmlns="http://xmlns.oracle.com/Enterprise/Tools/schemas/TI_RESULT_SIMPLE.V1">
         <result>10</result>
      </ResultGroup>
   </soapenv:Body>
</soapenv:Envelope>

 

Any ideas?

 

Hi,

After looking at the documentation for the putSObject method (part of the SObject class), I still can't get it to work.

 

I have a print_pricing__c object and a child object called pricing_discount__c.

 

the getSObject method works fine:

discounts = pricing.getSObjects('print_discounts__r');

 

However, the corresponding putSObject method, I just can't seem to get to work.  It compiles fine, but at runtime, I get the following error:

System.SObjectException: Invalid relationship print_discounts__r for Print_Pricing__c 

 

Here's my code for that:

 

 pricing.putSObject('print_discounts__r', new print_discount__c(name='blah',field2='blah2'));

 I've tried variations of this, i.e.,  pricing.putSObject('print_discount__c', new print_discount__c(name='blah',field2='blah2'));

 

But to no avail.  Any idea how to use this method?  Thanks.

 

Hi - I've been trying to use the pageBlockTable tag to present some data in a table/list format.  However, I want to do this with a non-salesforce object.  None of the data that I'm presenting is stored in a database.  They are all data based on calculations.  Is there a way for me to do this or must I create a dummy object just so I can use the pageBlockTable tag appropriately?

Hi - I have a get method that I would like to take a parameter.

 

For example - let's just say I have a method in a controller extension called getMyOpportunity which takes as an argument, an id.

 

Now I want to use this in a VF page like so:

{!MyOpportunity}

 

However, I don't know how to pass the parameter to the function.  Is this even possible? 

 

Hi everyone,

We have multiple records (same record type) and User input percentage field. We need to make sure sum of that field is 100%. Is there any way of validating it in Visualforce page or so?

For example,

Record A    50%
Record B    25%
Record C    based on the inputs above percent for this record must be 25%


Kind regards,

Elgun
Is it possible to replace standard salesforce layouts with lightning component (like a visualforce page with standard conroller).

Our client would like to use SKUID to make user interface more friendly and be able to edit records right from the list view. But salesforce specialist involved in project implementation said that it is preferable to use lightning.

I could not find any confirmation in documentation that this is possible to replace standard detail or list layout with somethid build on Linghtning.

Guys, Can somebody confirm that this is possible?
Hi all-

Can anyone help me with this?  I am trying to put this trigger in the Lead object to interact with the Lead Round Robin app from the App exchange.

Thank you!

Error: Compile Error: unexpected token: trigger leadRoundRobin on Lead  at line 5 column 0



// LeadsRoundRobin Trigger
// Modifications to bulkify
// Some of this code has been borrowed from developer.force.com
// Last update by Rodney Jennings 2-11-2013
trigger leadRoundRobin on Lead (before insert, before update) 
{
    //Check if assignment owner has changed
    //Trigger index --> Queue ID
    Map<Integer,Id> queueIds = new Map<Integer,Id>(); 
    
    Integer idx = 0;
    for (Lead l : Trigger.new)
    {
        if(Trigger.isUpdate)
        {
            if(l.OwnerId <> Trigger.oldMap.get(l.id).OwnerId) 
            {
                if (l.TempOwnerId__c == 'SKIP')
                {
                    Trigger.new[idx].TempOwnerId__c = '';
                }
                else
                {
                    queueIds.put(idx, l.OwnerId);
                }
            }
        }
        else
        {
            queueIds.put(idx, l.OwnerId);
        }
        idx++;
    }
    System.debug('>>>>>queueIds: '+queueIds);
    if (queueIds.isEmpty()) return;
    //Find active Assignment Group for Queue
    //Trigger index --> Assignment_Group_Name ID
    Map<Integer,Id> asgnGroupNameIds = new Map<Integer,Id>();
    //Queue ID --> Assignment Group Queues
    Map<Id,Assignment_Group_Queues__c> asgnGroupQueues = new Map<Id,Assignment_Group_Queues__c>(); 
    
    for(Assignment_Group_Queues__c[] agq : [SELECT Assignment_Group_Name__c, QueueId__c
                                          FROM Assignment_Group_Queues__c
                                          WHERE QueueId__c in :queueIds.values()
                                          AND Active__c = 'True'])
    
    {
        for (Integer i = 0; i < agq.size() ; i++)
        {
            asgnGroupQueues.put(agq[i].QueueId__c, agq[i]);
        }
    }
    
    System.debug('>>>>>asgnGroupQueues: '+asgnGroupQueues);
    if (asgnGroupQueues.isEmpty()) return;

    for (Integer i : queueIds.keySet())
    {
        Assignment_Group_Queues__c agq = asgnGroupQueues.get(queueIds.get(i));
        
        if (agq <> null) 
        {
            asgnGroupNameIds.put(i, agq.Assignment_Group_Name__c);
        }
        //else no active assignment group queue error
    }
    System.debug('>>>>>asgnGroupNameIds: '+asgnGroupNameIds);
    if (asgnGroupNameIds.isEmpty()) return;
    //Determine next valid user in Queue/Assignment Group for round robin
    //User with earliest last assignment date wins.
    //asgnGroups maps an AG name to an arrary of AG members  
    Map<Id, Integer> assignedCountMap = new Map<Id, Integer>();
    // Assignment Group Name ID --> User ID
    Map<Id,Assignment_Groups__c[]> asgnGroups = new Map<Id,Assignment_Groups__c[]>(); 
    for(Assignment_Groups__c[] ags : [SELECT Group_Name__c, User__c, Last_Assignment__c, Millisecond__c
                                   FROM Assignment_Groups__c
                                   WHERE Group_Name__c in :asgnGroupNameIds.values()
                                   AND Active__c = 'True' AND User_Active__c = 'True'
                                   ORDER BY Group_Name__c, Last_Assignment__c, Millisecond__c])
    { 
        // First build map of AGNs with null user arrays 
        for (Integer i = 0; i < ags.size() ; i++) 
        {
            if (!asgnGroups.containsKey(ags[i].Group_Name__c)) 
            {
               asgnGroups.put(ags[i].Group_Name__c, null);
               //initialize assigned counts to zero
               assignedCountMap.put(ags[i].Group_Name__c, 0);  
            }
        }
        // Loop over unique AG Names and add user arrays
        
        for (Id gn : asgnGroups.keySet())
        {
            List<Assignment_Groups__c> users = new List<Assignment_Groups__c>();
            for (Integer i = 0; i < ags.size() ; i++) 
            {
                if (ags[i].Group_Name__c == gn)
                {
                    users.add(ags[i]);
                }
            }
            asgnGroups.put(gn, users);
        }
    }
    System.debug('>>>>>asgnGroups: '+asgnGroups);
    if (asgnGroups.isEmpty()) return;

    // updateAssignmentGroups maps AG member Id to an AG member object 
    Map<Id,Assignment_Groups__c> updateAssignmentGroups = new Map<Id,Assignment_Groups__c>();
    Map<Id, datetime> latestAGDateTime = new Map<Id,datetime>();
    
    for (Integer i : queueIds.keySet())
    {
        // this can return null if the lead is not in a Queue that has an assignment group
        Id assignedGroupNameId = asgnGroupNameIds.get(i);
        if(assignedGroupNameId <> null) 
        {
            // this has a size of zero if there are no users in the assigment queue
            Assignment_Groups__c[] ags = asgnGroups.get(assignedGroupNameId);
            if (ags.size()>0)
            {
                //Choose next user in line if user ID has already been used but not committed in this trigger batch
                idx = assignedCountMap.get(assignedGroupNameId);
                Assignment_Groups__c ag = ags[math.mod(idx, ags.size())];
               
                //Assign User to Lead as the new owner
                System.debug('>>>>>Owner changed for Lead ' + Trigger.new[i].Id + ' from '+Trigger.new[i].OwnerId+' to '+ ag.User__c);
                Trigger.new[i].OwnerId = ag.User__c;
                // don't assign back in an endless loop
                Trigger.new[i].TempOwnerId__c = '';
    
                //Set last assignment datetime
                datetime now = datetime.now();
                ag.Last_Assignment__c = now;
                ag.Millisecond__c = now.millisecondGMT();
                
                //update only latest Assignment Groups per ID
                if (latestAGDateTime.containsKey(ag.id))
                {
                    if(latestAGDateTime.get(ag.id) < now)
                    {
                        updateAssignmentGroups.put(ag.id, ag);
                        latestAGDateTime.put(ag.id, now);
                    }
                }
                else
                {
                    updateAssignmentGroups.put(ag.id, ag);
                    latestAGDateTime.put(ag.id,now);
                }
                //increment counter so next lead in AG goes to next user in line       
                idx++;
                assignedCountMap.put(assignedGroupNameId,idx);
            }
        }
    }
    //Map --> List/Array for DML update
    List<Assignment_Groups__c> updateAG = new List<Assignment_Groups__c>();
    for (Id agId : updateAssignmentGroups.keySet())
    {
        updateAG.add(updateAssignmentGroups.get(agId));
    }

    System.debug('>>>>>Update Assignment Groups: '+updateAG);
    //Update last assignment for Assignment Group in batch
    if (updateAG.size()>0) 
    {
        try
        {
            update updateAG;
        }
        catch (Exception e)
        {
            for (Integer i : queueIds.keySet())
            {
                Trigger.new[i].addError('ERROR: Could not update Assignment Group records ' + ' DETAIL: '+e.getMessage());
            }
        }
    }
}
I wrote this piece of code to select the Max value from a series of Child records for a Parent reocrd that in not in a Master Detail.  Basically the Parent Record SD_Member__c can have enerous Child records - SD_Mbr_Enroll_Cycles__c.  So I want to capture the Max Enrollment_Status_Date__c and update a field on the Parent Record.  

I wrote the following code and it works but I know there is a better way to write this.  
 
trigger Update_Latest_Enrollment_Date on SD_Mbr_Enroll_Cycles__c (after insert, after update) {
/*
  Developer     : Todd Barry
  Created       :
  Last Modified : 02/26/2014
  Test Class    : Test_Last_Enrollment_Logic
  Objective     : Update the corresponding Enrollment Date (Latest) - OnTrak Field on the SD Member record.
*/
For (SD_Mbr_Enroll_Cycles__c EC : Trigger.new){

String strId = ec.SD_Member_Stakeholders__c;

List <SD_Mbr_Enroll_Cycles__c> ec1 = [select Enrollment_Status__c, Enrollment_Status_Date__c from SD_Mbr_Enroll_Cycles__c
                                       Where SD_Member_Stakeholders__c =: Strid
                                       And Use_Me__c = True
                                       and Enrollment_Status__c = 'Enrolled'
                                       ORDER BY Enrollment_Status_Date__c DESC LIMIT 1];

Map<string,Date> MaxDate = New Map<string,Date>{};
For (SD_Mbr_Enroll_Cycles__c ec2: ec1)
MaxDate.put(ec2.Enrollment_Status__c, ec2.Enrollment_Status_Date__c) ;                                     
                                      
// Not sure I need this line.
//For (SD_Member__c sd : [Select id,Enrollment_Date_Latest_OnTrak__c From SD_Member__c Where id =: strId]){

Sd_Member__C sd1 = new Sd_member__c (id = strId,
          Enrollment_Date_Latest_OnTrak__c = maxdate.get('Enrolled'));

Update sd1;        
         
                       
}
}
If you have a test class with multiple test methods in it, and some static member along with a static initializer, then 
1) Test methods will run in no particular order (i'm sure you knew this one already).
2) Static members are nulled out for each test method being run.
3) Static initializer runs for every test method, instead of just once for the class.
4) Governor limits are reset for every test method.
5) Governor limits are shared by the test method and static initializer.

So question: is #2 and #3 - expected behavior or a bug?
Hello,

I have a trigger (below) that is meant to take the value from a custom field on the Account object and copy it to a custom field on related Opportunities that are not closed won or closed lost, but only when the value in the Account field changes.  The trigger saves without any errors, but the value does not write over to the Opportunity.  Can anyone help me figure out why the value is not pulling through?  Thanks,


trigger UpdateConsultant on Account (after update){
       
List<Account> acct = new List<Account>();

FOR(Account a : Trigger.new){

// Query Opportunity records realted to Account that is being created/edited
    List<Opportunity> opps = [SELECT AccountId, IsWon, IsClosed, Consultant_Partner__c, Consultant_Type__c
                              FROM Opportunity
                              WHERE AccountId IN: Trigger.newMap.keySet()];
       
        // Iterating through all the Opportunity records and updating them as per the conditions
        for(Opportunity opps2 :opps){

            // Update Consultant Partner field on Opportunity if Opp is Open and Consultant field changes at Account level
            IF(opps2.IsWon == FALSE && opps2.IsClosed == FALSE && opps2.Consultant_Type__c == 'Primary Consultant' && trigger.NewMap.get(opps2.AccountId).Consultant_Partner_Primary__c != trigger.OldMap.get(opps2.AccountId).Consultant_Partner_Primary__c){
                opps2.Consultant_Partner__c = a.Consultant_Partner_Primary__c;
            }
           
            ELSE IF(opps2.IsWon == FALSE && opps2.IsClosed == FALSE && opps2.Consultant_Type__c == 'Secondary Consultant' && trigger.NewMap.get(opps2.AccountId).Consultant_Partner_Secondary__c != trigger.OldMap.get(opps2.AccountId).Consultant_Partner_Secondary__c){
                opps2.Consultant_Partner__c = a.Consultant_Partner_Secondary__c;
            }
        }
       
        // Update all realted Opportunity records
//        IF(opps.size() > 0)
            update opps;
}
}
  • January 23, 2014
  • Like
  • 0
I'm getting the error "Invalid type: CloneClassAttendance" in test code bolded below.
We're supposed to go live tomorrow morning and I'm stuck... don't mean to sound too desperate... but I am :(
Thanks, Michele

Here's the test code:
@isTest
private class CloneClassAttendanceTest {
//CloneClassAttendance myTest = new CloneClassAttendance();
//Public CloneClassAttendance(){}
// above line gives error  Invalid constructor name:
    static testMethod void myUnitTest() {   
        // Add test contact
        Contact c = new Contact(LastName='Test');
        insert c;
        // Add test campaign
        Campaign cp = new Campaign(Name='TestCampaign');
        insert cp;
        // Add campaign member status
        CampaignMemberStatus cms = new CampaignMemberStatus( CampaignId = cp.Id, Label = 'Attended', SortOrder = 3);
        insert cms;
        // Add campaign member
        CampaignMember cm = new CampaignMember( CampaignId = cp.Id, Status = 'Attended', ContactId = c.Id);
        insert cm;
     
         //Page reference change VF_PageName with the name of your visualforce page
         PageReference cloneAttendance = Page.CloneClassAttendance;
         //Set the current page
        Test.setCurrentPage(cloneAttendance);
         //Set the id param on the page to the campaign id
         ApexPages.currentPage().getParameters().put('id', cp.Id);
         //Instantiate standard controller with the campaign record
         ApexPages.StandardController s = new ApexPages.StandardController(cp);
         //Instantiate extension class passing the standard controller
         //Line below gives error: Invalid type: CloneClassAttendance       
         CloneClassAttendance cca = new CloneClassAttendance(s);

         //Call your extensions methods here...
         cca.InsertRecord();
    }
}

Here's the Apex code I'm trying to test:
public class CloneClassAttendance
{
    private final Campaign theCampaign;

    public CloneClassAttendance( ApexPages.StandardController stdController )
    {
        theCampaign = (Campaign)stdController.getRecord();
    }

    //  returns the day-of-week for the given date in 2001 - 2099
    //  this works because 2001 started on a Monday
    //  0 = Sunday, ... 6 = Saturday
    private static Integer dayOfWeek( Date theDate )
    {
        Integer theYear = theDate.year() - 2001;
        return Math.mod( theYear + theYear/4 + theDate.dayOfYear(), 7 );
    }

    public void insertRecord()
    {
        Map<Date,Campaign> map_newCampaigns = new Map<Date,Campaign>();

        Date newDate = theCampaign.CloneStart__c;
        while ( newDate <= theCampaign.CloneEnd__c )
        {
            map_newCampaigns.put
            (   newDate,
                new Campaign
                (   Type                = 'Class Attendance',
                    IsActive            = true,
                    StartDate           = newDate,
                    EndDate             = newDate,
                    ParentId            = theCampaign.Id,
                    Name                = theCampaign.Name + '-' + newDate.format(),
                    Description         = theCampaign.Description,
                    Teacher__c          = theCampaign.Teacher__c,
                    Day_of_Week__c      = theCampaign.Day_of_Week__c,
                    Hours_Per_Class__c  = theCampaign.Hours_Per_Class__c,
                    Location__c         = theCampaign.Location__c,
                    Start_Time__c       = theCampaign.Start_Time__c,
                    End_Time__c         = theCampaign.End_Time__c,
                    Waitlist__c         = theCampaign.Waitlist__c,
                    Max_Capacity__c     = theCampaign.Max_Capacity__c,
                    Status              = 'Completed'
                )
            );
            newDate = newDate.addDays( 7 );
        }
        insert map_newCampaigns.values();

        List<CampaignMemberStatus>  list_newCampaignMemberStatus    = new List<CampaignMemberStatus>();
        List<CampaignMember>        list_newCampaignMembers         = new List<CampaignMember>();

        newDate = theCampaign.CloneStart__c;  
        while ( newDate <= theCampaign.CloneEnd__c )
        {
            Campaign newCampaign = map_newCampaigns.get( newDate );

            for ( CampaignMemberStatus status :
                [   SELECT  Id, HasResponded, IsDefault, Label, SortOrder
                    FROM    CampaignMemberStatus
                    WHERE   (   CampaignId = :theCampaign.Id
                            AND IsDeleted = false
                            )
                ]
                )
            {

                list_newCampaignMemberStatus.add
                (   new CampaignMemberStatus
                    (   CampaignId      = newCampaign.Id,
                        HasResponded    = status.HasResponded,
                        IsDefault       = status.IsDefault,
                        Label           = status.Label,
// the following line is a workaround due to the fact that when the campaign is cloned it automatically
// add CampaignMemberStatus of Sent and Received with sortorder 1 and 2. This was creating a duplicate bug.
                        SortOrder       = status.SortOrder +2
                    )
                );
System.debug( 'CampaignMemberStatus: CampaignId= ' + newCampaign.Id +' Label = ' + status.Label + ', SortOrder = ' + status.SortOrder );
            }

            for ( CampaignMember member :
                [   SELECT  Id, ContactId, Status
                    FROM    CampaignMember
                    WHERE   CampaignId = :theCampaign.Id
                ]
                )
            {
                list_newCampaignMembers.add
                (   new CampaignMember
                    (   CampaignId      = newCampaign.Id,
                        ContactId       = member.ContactId,
                        Status          = member.Status
                    )
                );
            }

            newDate = newDate.addDays( 7 );
        }

        insert list_newCampaignMemberStatus;
        insert list_newCampaignMembers;
    }
}

Here's the Visual Force page:
<apex:page standardController="Campaign" extensions="CloneClassAttendance" action="{!insertRecord}">
  <h1>Cloning Attendance</h1>
  <p> Class name is {! campaign.name} </p>
  <p> Class id is:   {! campaign.id} </p>
  <p> Class start date is:   {! campaign.startdate} </p>
  <p> Class end date is:   {! campaign.enddate} </p>
  <p> Next week is: {! campaign.startdate+7} </p>
  <p> Class Status is {! campaign.status} </p>
  <p> Class teacher is {! campaign.teacher__c} </p>
  <p> Class DOW is {! campaign.Day_of_Week__c} </p>
  <p> Class Hours_Per_Class__c is {! campaign.Hours_Per_Class__c} </p>
  <p> Class Location is {! campaign.Location__c} </p>
  <p> Class Start time is {! campaign.Start_Time__c} </p>
  <p> Class End time is {! campaign.End_Time__c} </p>
  <p> Class Description is {! campaign.Description} </p>
  <p> Class Waitlist is {! campaign.Waitlist__c} </p>
  <p> Class Max_Capacity is {! campaign.Max_Capacity__c} </p>
  <p> Clone start date is:   {! campaign.clonestart__c} </p>
  <p> Class end date is:   {! campaign.cloneend__c} </p>
</apex:page>
Does anyone know how I can get the Account Name and use it for the String Customer without doing a SOQL Query?

I'm trying to populate the String 'Customer' with Account Name, which is a look up from the Escalation__c object.

This is my Apex controller extension:

public with sharing class addCasesToEscalation{
    public Escalation__c theEsc {get;set;}
    public String searchString {get;set;}
    public Case[] shoppingCart {get;set;}
    public Case[] AvailableCases {get;set;}
    
    public String toSelect {get; set;}
    public String toUnselect {get; set;}
    public Decimal Total {get;set;}

    public Boolean overLimit {get;set;}
    public Id EscId {get;set;}
    public Id AcctId {get;set;}
   
    //using this for PDF report attachment
    public String pdfName {get;set;}
    public String Customer {get;set;}
 
    private Case[] forRemoval = new Case[]{};
    private Set<Case> clean = new Set<Case>();

    public addCasesToEscalation(ApexPages.StandardController controller) {

       
        // Get information about the Escalation being worked on
            system.debug(controller.getRecord());
            Escalation__c theEsc = (Escalation__c)controller.getRecord();
            EscId = theEsc.Id;
           
           
        // If cases were previously selected need to put them in the "selected cases" section to start with
        shoppingCart = [select Id, CaseNumber, Subject, Status, Priority, IsClosed, CreatedDate, Escalation__c from Case where Escalation__c=:EscId order by CreatedDate Desc];

            }
   

    public void updateAvailableList() {
   
        // We dynamically build a query string and exclude items already in the shopping cart
        String qString = 'select Id, CaseNumber, Subject, Status, Priority, CreatedDate, Escalation__c, IsClosed From Case WHERE AccountId = :AcctId';
       
        // note that we are looking for the search string entered by the user in the name OR description
        // modify this to search other fields if desired
        if(searchString!=null){
            qString+= ' and (Subject like \'%' + searchString + '%\' or CaseNumber like \'%' + searchString + '%\')';
        }
       
        Set<Id> selectedEntries = new Set<Id>();
        for(Case c : shoppingCart){
            selectedEntries.add(c.Id);
        }
       
        if(selectedEntries.size()>0){
            String tempFilter = ' and Id not in (';
            for(Id i : selectedEntries){
                tempFilter+= '\'' + (String)i + '\',';
            }
            String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
            extraFilter+= ')';
           
            qString+= extraFilter;
        }
              
        qString+= ' order by CreatedDate Desc';
        qString+= ' limit 101';
       
        system.debug('qString:' +qString);       
        AvailableCases = database.query(qString);
       
        // We only display up to 100 results... if there are more then we let the user know (see vf page)
        if(AvailableCases.size()==101){
            AvailableCases.remove(100);
            overLimit = true;
        }
        else{
            overLimit=false;
        }
     
    }
   
    public void addToShoppingCart(){
   
        // This function runs when a user hits "select" button next to a product
   
        for(Case c : AvailableCases){
            if((String)c.Id==toSelect){
                c.Escalation__c = EscId;
                shoppingCart.add(c);
                break;
            }
        }
       
        updateAvailableList(); 
    }
   

public PageReference removeFromShoppingCart(){
   
        // This function runs when a user hits "remove" on an item in the "Selected Cases" section
   
        Integer count = 0;
        for(Case ce : shoppingCart){

            if((String)ce.Id==toUnselect){
               
                if(ce.Id!=null&&ce.Escalation__c != null){
                    ce.Escalation__c = null;
                    forRemoval.add(ce);}
                shoppingCart.remove(count);
                break;            
            }
            count++;
        }
       
        updateAvailableList();
       
        return null;
    }
   
    public PageReference onSave(){
   
        // If previously selected devices are now removed, we need to delete them
        if(forRemoval.size()>0)
            //this is a somewhat hackey way to clean the list just in case there are duplicate cases in the list
            clean.addAll(forRemoval);
            forRemoval.clear();
            forRemoval.addAll(clean);
            update(forRemoval);
   
        // Update cases in shoppingCart
            if(shoppingCart.size()>0)
                update(shoppingCart);
       
        // After save return the user to the Escalation
        return new PageReference('/' + EscId);
    }
   
    public PageReference onCancel(){

        // If user hits cancel we commit no changes and return them to the Escalation  
        return new PageReference('/' + EscId);
    }
   
   //pdf attach extension
    public PageReference savePdf() {

    PageReference pdf = Page.escalationReport;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',EscId);

    // create the new attachment
    Attachment attach = new Attachment();

    // the contents of the attachment from the pdf
    Blob body;

    try {

        // returns the output of the page as a PDF
        body = pdf.getContent();

    // need to pass unit test -- current bug   
    } catch (VisualforceException e) {
        body = Blob.valueOf('Something went wrong');
    }
       
    pdfName = Customer + ' escalation report as of '+String.valueOf(System.today());
    attach.Body = body;
    // add the user entered name
    attach.Name = pdfName;
    attach.IsPrivate = false;
    // attach the pdf to the account
    attach.ParentId = EscId;
    insert attach;

    // send the user to the account to view results
    return new PageReference('/'+EscId);

  }
   
}
I have a custom object that I would like to create and save an opportunity from with a few of the fields. I think my problem is that I'm including contact lookup fields? I'm getting a save error that says "Illegal assignment from Id to SOBJECT:User"

How can I make this trigger work?

trigger meeting on MD_Meeting__c (after update) {
    List <Opportunity> oppToInsert = new List <Opportunity> ();
    for (MD_Meeting__c m : Trigger.new) {
        if (m.SD_Action__c=='Generate Opportunity') {   
        Opportunity o = new Opportunity ();  
        o.Owner = m.Sales_Director__c;
        o.Market_Developer__c = m.Market_Developer__c;
        o.Account = m.Account__c;
        o.Type = 'Sales - New Business';
    o.CloseDate = System.Today()+150;
    o.MeetingLookup__c = m.Name;
        o.add(o);
        }//end if
    }//end for o
    try {
        insert oppToInsert;
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
}
Is there a way to pull in permission sets into an apex class? We are looking to restrict the ability for users to click on the submit to finance button (custom JS button on the opportunity page layout).  Creating a new profile and page layout isn't an option for a solution, so I was wondering if there was a way to prevent a user from clicking on this button if they do not belong to a specific permission set.  For example, only our Order Admin team can submit opportunities to Finance - these folks have their own permission set called Order Admins.
Thanks for your help!

I have a custom button which when clickd will execute a apex class.The whole logic is like this:
http://wiki.developerforce.com/page/The_Get_Next_Button#Quickstart:_The_Get_Next_Case_and_Get_Next_Lead_Button

I had customized this and using as per my req.This works perfect in sandbox where i just have test data.When moved to production where i have 500k records/leads i get the error TOO MANY DML ROWS:10001

Can any one please tell me what am i missing?
Do i need to bulkify my class still?
Please help ..
Below is my apex code:

global without sharing class RetrieveNextUtils {
    webService static Id retrieveNextLead(String userId){
  
    String RtID=null;   
    String query ='Select Id,Owner.name,status,Time_Zone__c from Lead where Status =\'new\' ';
    query=query+ ' and owner.Name= 'Queue'  FOR UPDATE';  //Locking statment as when two users click the button they are pulling same lead .
    try{
    List<Lead> leads = Database.Query(query); 
   
    for(integer i=0;i<leads.size();i++)
    {
        String tzname = leads[i].time_zone__c;
        String str_LeadCurrTime= DateTime.now().format('HHmm',tzname);
     
        if(str_LeadCurrTime >=  '0900' && str_LeadCurrTime <= '1145' || str_LeadCurrTime >= '1315' && str_LeadCurrTime <= '1700' )
        {   
             leads[i].OwnerId =UserInfo.getUserId();
             RtID=leads[i].Id;
             break;
         } 
   }
   update leads;
   return RtID;
   }
   Catch(exception ex){
        return RtID;
   }

}
}

Hi, new to batch Apex and got question on Apex Scheduler vs. Batch Apex. I use the term "apex scheduler" to refer to class that implements "Schedulable" interface and "Batch Apex" for class that implements "Database.Batchable" interface.

What's the difference between these two? For example, I can create class that implements "Schedulable" interface, and I would have batch job (use the "Schedule Apex" page to run the batch job). I don't need to create batch Apex class (class that implements "Database.Batchable" interface), which seems to be complex to use. Anyone could shed some light ;> ? Thanks in advance.

I'm trying to integrate an external Web Service API into force.com. In that webservice I can get COntent of a File, my issue is how can I create a Visualforce page and APEX class such that I can get my force.com users to download the File. The file can be txt file, pdf file, excel file or anything. :( .... help ...

  • December 23, 2010
  • Like
  • 0

Hello All,

 

How do I enable  multi-currency support for my developer account?

 

any idea?

 

 

Thanks

Message Edited by Dowithforce on 10-20-2009 08:29 AM

Please help.  We are very new to using Eclipse as a deployment tool. 

 

We have a validation rule that is attached to a Custom Object.  When we try to deploy just the validation rule, I get an error that says:

 

# Deploy Results:
   File Name:    objects/Plan__c.object
   Full Name:  Plan__c
   Action:  NO ACTION
   Result:  FAILED
   Problem: Must specify a non-empty label for the CustomObject

 

I've reviewed the Plan__c object label and plural label and they are both populated with a value, so this must be related to something different. 

 

We've been able to do the same kind of validation rule deployment from Standard Objects without issue. 

 

I got it to work by deploying the entire Custom Object (which picks up all fields, rules, etc.), which was fine in this case.  However, there may be times where we do not wish to deploy the entire object.  Can you please tell me what can be done to alleviate the error we are receiving?

 

Thanks for any and all help.

Message Edited by eleemoody on 07-28-2009 09:47 AM