• Jeremy_n
  • NEWBIE
  • 279 Points
  • Member since 2010

  • Chatter
    Feed
  • 11
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 77
    Replies

 

I want to create a map<id, List<id>> where key is the contact id & the value is the list of custom__c's id. Actually contact is a lookup in custom__c object & 1 contact can be link to many records in custom__c.

These are the ways I tried...

Map<id,List<Custom__C>> cMap = new Map<id,List<id>>([select contact__c, id from custom__c where contact__c in: conList group by contact__c]);



list<id> idList = new List<Id>();
for(AggregateResult results : [select Contact__c, Id FROM custom__c WHERE Contact__c IN :con GROUP BY Contact__c]){
idList.add((ID)results.get('Id'));
cMap.put((ID)results.get('Contact__c'),idList);
}

But I couldnt get what I want.

Can I use AggregateResultset just to get data grouped by something & without actually using any aggeregate methods like count(), sum() etc?

I dont want to put a select query inside contact for loop to avoid limits of governors. FYI, this code is inside contact trigger.

 

 

Any ideas?

  • April 25, 2012
  • Like
  • 0

Hey guys,

 

At the moment I'm working on a Contact Page. The good news is that it does send a message. The bad news is, while I know how to check to see if necessary fields are missing, I don't know how to to show that to the user.

 

Furthermore, I want when a email IS sent to link the user to a page saying that they have sent it. Or at least give them a message.

 

Here is my code and controller for both pages

 

 

<apex:page title="Configero - Company" showHeader="false" controller="sendEmail">
    <title>Configero - Contact Us</title>
    <apex:composition template="ConfigeroTemplate">
        <apex:define name="mainContent">

             <apex:outputPanel styleclass="block" style="float:left;display:inline;width:445px">
                <div class="blockTitle"><span class="blue">Contact</span> Us</div>
                <div class="blockBody">
                    <p>If you have any questions or would like a quote for one of our services, please call 404.229.2232 or contact us via email at <a href="mailto:info@configero.com">info@configero.com</a>.</p>
                    <apex:form >
                        Your Name <span class="red">*</span> <br/><apex:inputText id="name" value="{!conname}" size="50"/> <br/>
                        Email Address <span class="red">*</span><br/><apex:inputText id="email" value="{!remail}" size="50"/> <br/>
                        Subject <span class="red">*</span><br/><apex:inputtext id="subject" value="{!subject}" size="50"/><br/>
                        Message <span class="red">*</span><br/><apex:inputTextarea id="message" value="{!body}" cols="59" rows="5"/> <br/>
                        <apex:commandButton value="Send Email" action="{!send}"/>
                    </apex:form>
                </div>
            </apex:outputPanel> 
            
        </apex:define>
    </apex:composition>
</apex:page>

 

public class sendEmail {
    public String subject { get; set; }
    public String body { get; set; }
    public String REmail {get; set; }
    public String ConName {get; set;}

    private final Account account;

    // Create a constructor that populates the Account object  
    
    /*public sendEmail() {
        account = [select Name, (SELECT Contact.Name, Contact.Email FROM Account.Contacts) 
                from Account where id = :ApexPages.currentPage().getParameters().get('id')];
    }*/

    public Account getAccount() {
        return account;
    }

    public PageReference send() {
        // Define the email  
        if(REmail == '')
        {
           //Fields not entered
           return null;
        }
        else if(ConName == '')
        {
            return null;
        }
        else if(Subject == '')
        {
            return null;
        }
        else if(body == '')
        {
            return null;
        }
        else
        {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 



        String[] toAddresses = new String[] {'email@gmail.com'};

        // Sets the paramaters of the email  
    
        email.setReplyTo( REmail);
        email.setSubject( 'New Contact Message: '+subject );
        email.setToAddresses( toAddresses );
        email.setPlainTextBody( 'Message: ' + body +'\r Signed: '+ConName );
    
        // Sends the email  
    
        Messaging.SendEmailResult [] r = 
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
        
        return null;
        }
    }
}

 Any advice is appreciated. Thanks

 

  • September 22, 2010
  • Like
  • 0

I have a custom object that is using record types.  I am also using the Account Tabbed view.

 

In order to show one record type per tab on my account, I created a custom controller and used that to create my lists.  I am trying to add a new button to each tab so users can create new records.

 

I am having a problem getting the account ID into the custom object.  When I use the following, it assigns the accounts ID to the name field on the custom object.  Trying to figure out how I correctly assign the account to the custom object.

 

Any help would be greatly appreciated!!! Thanks!!!!

 

 

 public PageReference NewEnrollHealth() {
    Id Aid = ApexPages.currentPage().getParameters().get('id');
    PageReference pageRef = new PageReference('https://cs3.salesforce.com/a01/e?CF00N700000021Lm4='+Aid+'&CF00N700000021Lm4_lkid=001Q000000EAALT');
   
            return PageRef;
      }

 

 

  • September 13, 2010
  • Like
  • 0

Hi, I am going to try to explain my situation in another way.  Below are the two seperate queries that some how I want to join together so that the final results are stored in a single custom object.  I have included AccountID in both queries in hopes to tight them together by that common field.  Each fields data should be stored in the custom object.

 

Of course I will have WHERE clauses on both queries but to keep it simple I did not include the WHERE clause.

 

Select o.AccountId, o.Id, o.Lead_Rep__c, o.OwnerId, o.Owner.Email, o.Owner.FirstName, o.Owner.LastName, o.Owner.Phone from Opportunity o

Select c.AccountId, c.Account.EIN__c, c.Email, c.FirstName, c.LastName, c.Phone from Contact c

 Does anyone have any clues or examples of what I am trying to do?

 

If I can get the results into a custom object then I can export using the DataLoader

Is there any way to restart  an autonumber field in a Custom Object??

I can't change the type of my field because I use it in a trigger

I have two objects, A and B, which are linked via a lookup field. B is the sub-object in this example.

 

Now even though they're linked with a lookup, I want one key field to be synced between the two objects. I want users to be able to edit from either record.

 

However, here's my problem:

When someone changes the value on A, the trigger on A fires, and updates B. This causes a chain reaction which causes the trigger on B to fire, and update A again. I'm not actually sure how many times it goes through the loop before failing.

 

This actually works for records where there are only a few B records, but my test cases fail because of too many DML rows. I thought this was a problem with just the number of records, so I created some Asynchronous Apex to handle the actual updating. However, now I get the error that a future method cannot call a future method (since one future method is causing the second trigger to fire which also uses a future method).

 

I have tried and failed with the following:

Trigger.isExecuting - this always returns true since they are triggers, so I can't use this

Custom checkbox which says Updated from Sync - This works for the initial update, but I can never set this field back to false, because when I do (via trigger or workflow rule) it fires the other trigger again, and I get the same errors.

 

Any ideas on how to sync one field between two objects?

I have made a trigger that intercepts leads that are created by our web-to-lead form. The trigger ensures that there are no duplicate leads based on email, (which is probably an unnecessary safety step because I don't there is a way for two leads to be submitted by one web-form). It then packages those unique leads into a map and sends it over to the class I have pasted below. The goal of the class is to find existing leads and contacts and update them with the data supplied by the incoming lead, and then delete the incoming lead.

 

For each of the lines in Bold I get the 'Initial Term of Field Expression must be concrete Sobject' error. I think this is because the platform is assuming that 

newLeads.get(leadB.email)...

could return more than one result. So I am thinking that I have to prove that 'newLeads.get(leadB.email)' will only return one result, but I am not sure how to do this.

 

public with sharing class leadHandler {

Public Static Void leadDeDuper(Map<String,String> newLeads) {
Set<String> leadsToDelete = new Set<String>();
List<Lead> leadsToDeleteList = new List<Lead>();
List<Lead> existingLeads = new List<Lead>();
List<Contact> contactsToDelete = new List<Contact>();
List<Contact> existingContacts = new List<Contact>();

//finds existing Leads where their email equals the incoming Lead
for(Lead leadB : [select Id, Name, Blog__c,Email,HasOptedOutofEmail,Product_Announcements__c, MarketingCampaign__c, Insights_Newsletter__c,Press_Releases__c from Lead where Email IN :newLeads.KeySet()]) {
//adds the incoming lead to a set that will be deleted further down
leadsToDelete.add(newLeads.get(leadB.email));

//updates fields in existing leads
leadB.HasOptedOutOfEmail = false;
leadB.Press_Releases__c = newLeads.get(leadB.email).Press_Releases__c;
leadB.Insights_Newsletter__c = newLeads.get(leadB.email).Insights_Newsletter__c;
leadB.Product_Announcements__c = newLeads.get(leadB.email).Product_Announcements__c;
leadB.Blog__c =newLeads.get(leadB.email).Blog__c;
leadB.Marketing_Opt_Out__c = false;

existingLeads.add(leadB);
}

if(existingLeads.size()>0) {
update existingLeads;
}
//finds existing contacts where their email equals the incoming leads
for(Contact contactA : [select ID, Name, Email, HasOptedOutofEmail, Insights_Newsletter__c, Press_Releases__c from Contact where Email IN :newLeads.keySet()]) {

//adds the lead to a set to be deleted below
leadsToDelete.add(newLeads.get(contactA.Email));

//updates the existing contact
contactA.HasOptedOutOfEmail = false;
contactA.Insights_Newsletter__c = newLeads.get(contactA.email).Insights_Newsletter__c;
contactA.Press_Releases__c = newLeads.get(contactA.email).Press_Releases__c;
contactA.Product_Announcements__c = newLeads.get(contactA.email).Product_Announcements__c;
contactA.Blog__c = newLeads.get(contactA.email).Blog__c;


existingContacts.add(contactA);
}

if(existingContacts.size()>0) {
update existingContacts;
}

if(leadsToDelete.size()>0) {
for(Lead dLead : [Select ID from Lead where ID IN:leadsToDelete]) {
leadsToDeleteList.add(dLead);
}
delete leadsToDeleteList;
}

}

}

 

 

how to give a query to fetch the data for 2 weeks back from now.

 

i gave like     Date__c = Last_Week - 1  But its showing unidentified identifier ' - ' as an error

I am having trouble deploying an apex class from my sandbox to my production.  Everything in the sandbox works fine but when I try to deploy it from eclipse I get a Failures and Warnings screen.  My apex class is called ProductstoAssets and an image of the error I am receiving is attached.  Someone please help!  It's driving me nuts that I finally got this working right in the sandbox and now I can't get it moved over to production.  If you need the debug log I can post it in sections.

 

eclipseerror

Hi, I am using a formula field to get the Ultimate Parent (Account) of every contact and every opportunity - however obviously this is stored as a text field.

 

now, when I run reports on these contacts and opportunities, and try to restrict by the Ultimated Parent using this formula field, some contacts from other Accounts show up here which shouldnt.

 

I realized that this is happening because Salesforce is unable to differentiate between IDs with different cases if they are coming from a text field. Example:

 

Account ABC - 0012000000UDldR

Account DEF - 0012000000UDldr

 

Notice that the case of the last letter is different, but when creating a criteria in a report to filter by any of these IDs, Salesforce is unable to filter properly.

 

Any workaround for such an issue?

 

Best,

Pranav

We are a fast-growing Salesforce Consulting Partner on the east coast, and we find ourselves with a need for good Salesforce developers. Here's what we need:

 

  • Understanding of the business processes that live behind the Salesforce screens
  • Abilitiy to talk to a customer and understand what they're saying, whether it's tech-talk or salesperson-talk (you know what I mean)
  • Pride in one's work, and the ability to adapt to the requirements of a project

Here's what we want:

  • Apex Triggers, Visualforce pages and custom controllers, comples workflow rules
  • Excellent written communication skills
  • Self-scheduling, self-motivated, and realistic about self-limits

 

Please contact me with a resume and portfolio or description of past work. I am a technical consultant, and look forward to talking to every applicant.

 

Thanks,

Jeremy Nottingham

Synaptic Application Partners

jeremy.nottingham@synapticap.com

 

Has anyone successfully created a "Copy to Clipboard" button in Visualforce?

 

I've got a method that works for Internet Explorer only ( http://www.htmlgoodies.com/beyond/javascript/article.php/3458851/Click-Its-Copied.htm) , which will be acceptable at this point, although I would prefer a cross-browser solution.

 

However, I don't seem to be able to make it work in a VF page. Here's my basic attempt:

 

 

<apex:page title="Clipboard Test" showheader="false">

	<script language="JavaScript">
		function ClipBoard()
		{
			holdtext.innerText = {!$Component.copytext}.innerText;
			Copied = holdtext.createTextRange();
			Copied.execCommand("Copy");
		}


	</script>

<body >
	<apex:outputpanel ID="copytext" >
		This text will be copied onto the clipboard when you click the button below.
	</apex:outputpanel>
	
	<TEXTAREA ID="holdtext" STYLE="display:none;">
	</TEXTAREA>
	
	<BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON>

</body>	
	
</apex:page>

 

I am not a Javascript expert, which is making this all harder for me. Please help!

 

Thanks,

 

Jeremy

 

 

I want to create a map<id, List<id>> where key is the contact id & the value is the list of custom__c's id. Actually contact is a lookup in custom__c object & 1 contact can be link to many records in custom__c.

These are the ways I tried...

Map<id,List<Custom__C>> cMap = new Map<id,List<id>>([select contact__c, id from custom__c where contact__c in: conList group by contact__c]);



list<id> idList = new List<Id>();
for(AggregateResult results : [select Contact__c, Id FROM custom__c WHERE Contact__c IN :con GROUP BY Contact__c]){
idList.add((ID)results.get('Id'));
cMap.put((ID)results.get('Contact__c'),idList);
}

But I couldnt get what I want.

Can I use AggregateResultset just to get data grouped by something & without actually using any aggeregate methods like count(), sum() etc?

I dont want to put a select query inside contact for loop to avoid limits of governors. FYI, this code is inside contact trigger.

 

 

Any ideas?

  • April 25, 2012
  • Like
  • 0

I have a custom object "Time_Entry__C" that has a look-up field called "Employee__C" which holds the ID from an Employee object

  - The employee object has ID, Firstname__C; Lastname__C fields.

 

I want to populate the Employee1__c field (in the Time_Entry__C object) with the ID from the Employee object (SFDC_Employee__c) BASED upon the current user (if found).

 

For example.  The current user = "John Doe"  When he creates a record in the Time_Entry__c object, I want a "before insert"  trigger to find the ID in the SFDC_Employee__c object  where SFDC_Employee__c.firstname = UserInfo.firstname and SFDC_Employee__c.lastname = Userinfo.Lastname then plop that Employee ID into the Employee1__c  lookup field on the Time_Entry__c object.

 

Any help?

  • October 31, 2011
  • Like
  • 0

Hello all, 

 

I am trying to learn Apex. I know that it is a Java like object oriented programming language. I was wondering which one of these books will benefit me more, a introduction to java book or the object oriented programming for dummies book. 

 

Thanks in advance. 

 

 

 

 

I have create 2 trigger to insert a Contact when a new Account record is created andupdate a Contact's Email if a custom field (Company Email) on the Account record is changed. I am not sure how to add a new contact if the Account record already exists and Company Email feild was previously "null" and then update with an email address.

 

Insert Trigger

trigger CompanyEmail on Account (after insert) {

   
  List<Contact> ct = new List <Contact>();
    for (Account newAccount: Trigger.New){
    
        if (newAccount.Company_Email__c != null){
                 ct.add (new Contact(
                     FirstName = 'Account',
                     LastName = 'Email',
                     Email = newAccount.Company_Email__c,
                     AccountId = newAccount.id,
                     OwnerId = '00530000001jaC1'));   
         }
insert ct;  
        }}

 Update trigger:

trigger TriggerWithUpdateEmail on Account (after update) 
    {
        Integer index = 0;       
        for(Account acc : Trigger.New)
            {
                //Check entry criteria
                if(acc.Company_Email__c != Trigger.Old[index].Company_Email__c)                
                    {
                    
                         List<Contact> listCon = [Select Email from Contact where (AccountId =: acc.id) and (FirstName = 'Account')];      
                         for(Contact con : listCon)
                             {
                                 con.Email = acc.Company_Email__c;
                             }
                         update listCon;    
                    }
                index++;
            }
    }

 

  • October 31, 2011
  • Like
  • 0

How would you determine what object is associated with an event. The Related To field on Events object is a drop down of Objects so how can one determine the selected object at runtime?

 

Thanks

Hi

 

I am getting this error in the production.

 

System.DmlException: ConvertLead failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ConvertLead: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0062000000F3KnAAAV; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Profile Class allowed on this Record Type is 00. Your MPAN should start with 00.: [MPAN_1_Top_Line__c] Trigger.ConvertLead: line 206, column 5

 

This is a validation rule which was implemented in the production.Due to this there is a code breakage.

 

The related class is

 public static testMethod void testConvertLead(){
            Lead newLead = new Lead();
            newLead = setupLead();
            newLead.Status = 'Qualified';
            System.assertNotEquals(newLead, null);
            newLead.Status = 'Qualified';
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(newLead.id);
            lc.setOwnerId(UserInfo.getUserId());

            LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
            lc.setConvertedStatus(convertStatus.MasterLabel);
            Database.LeadConvertResult lcr = Database.convertLead(lc); 
            System.assert(lcr.isSuccess());
    }

 

 

and the related trigger is

 

trigger ConvertLead on Lead (after update) {
    List<Account> Accs = new List<Account>();
    List<Opportunity> oppors = new List<Opportunity>();
    List<Opportunity> updateOprs = new List<Opportunity>();
    Id UserProfileId = [Select Name, Id From Profile where Name = 'Sub Broker'].Id;
    List<Task> tsks = new List<Task>();
    List<Contact> decisionMakerContacts = new List<Contact>();
    for(Lead ConvertedLead : Trigger.new){
          if(ConvertedLead.IsConverted == true){   
             Account Acc = [SELECT Id, Name FROM Account WHERE Id = :ConvertedLead.ConvertedAccountId];
             Contact cnt = [Select Id, Name, Email from Contact WHERE Id = :ConvertedLead.ConvertedContactId];
             tsks = [Select WhatId, Subject From Task where WhatId = : ConvertedLead.ConvertedAccountId or WhatId = : ConvertedLead.ConvertedOpportunityId limit 1];
         /*      Acc.Channel_Source__c = ConvertedLead.Channel_Source__c;
             Acc.Channel_Type__c = ConvertedLead.Channel_Type__c;
             Acc.Channel_Partner__c = ConvertedLead.Channel_Partner__c;
             Date formatDate = date.newInstance(ConvertedLead.CreatedDate.dayOfYear(), ConvertedLead.CreatedDate.month(), ConvertedLead.CreatedDate.day());
             Double Closedays = formatDate.daysBetween(System.Today());
             
             Acc.ShippingStreet = ConvertedLead.Site_Street__c;
             Acc.Site_Building_Number__c = ConvertedLead.Site_Buiilding_Number__c;
             Acc.Site_Building_Name__c = ConvertedLead.Site_Buiilding_Name__c;
             Acc.ShippingState = ConvertedLead.Site_County__c;
             Acc.ShippingPostalCode = ConvertedLead.Site_Postal_Code__c;
             Acc.ShippingCountry = ConvertedLead.Site_Country__c;
             Acc.ShippingCity  = ConvertedLead.Site_City__c; 
             Acc.days_between_the_LEAD_and_Acc_Creat_Date__c = Closedays;
             Acc.RA_Building_Name__c = ConvertedLead.RA_Building_Name__c;
             Acc.RA_Building_Number__c = ConvertedLead.RA_Building_Number__c;
             Acc.RA_Street__c  = ConvertedLead.RA_Street__c;
             Acc.RA_Postal_Code__c  = ConvertedLead.RA_Postal_Code__c; 
             Acc.RA_County__c  = ConvertedLead.RA_County__c; 
             Acc.RA_Country__c  = ConvertedLead.RA_Country__c;
             Acc.RA_City__c  = ConvertedLead.RA_City__c; 
             Acc.Company_Reg_No__c =  ConvertedLead.Company_Reg_Number__c;
             Acc.Date_LOA_Obtained__c =ConvertedLead.Date_LOA_Obtained__c;
             Acc.LOA_Obtained__c =ConvertedLead.LOA_Obtained__c;
             Acc.Current_Electric_Supplier_Meter1__c = ConvertedLead.New_Supplier__c; */
             
                                 
              if(ConvertedLead.Related_Utility__c == 'Gas & Electricity' || ConvertedLead.Related_Utility__c == 'Gas' || ConvertedLead.Related_Utility__c == 'Electricity'){
                Opportunity updateopr = leadOpportunity.setOpportunityRecordType(ConvertedLead, UserProfileId);
                updateopr.Channel_Source__c = ConvertedLead.Channel_Source__c;
                updateopr.Channel_Type__c = ConvertedLead.Channel_Type__c;
                updateopr.Channel_Partner__c = ConvertedLead.Channel_Partner__c;
                updateopr.Description = ConvertedLead.Description;
            /*    updateopr.Site_Building_Number__c = ConvertedLead.Site_Buiilding_Number__c;
                updateopr.Site_Building_Name__c = ConvertedLead.Site_Buiilding_Name__c;
                updateopr.Site_Street__c = ConvertedLead.Site_Street__c;
                updateopr.Site_Postal_Code__c = ConvertedLead.Site_Postal_Code__c;
                updateopr.Site_County__c = ConvertedLead.Site_County__c;
                updateopr.Site_Country__c = ConvertedLead.Site_Country__c;
                updateopr.Site_City__c = ConvertedLead.Site_City__c;
                
                updateopr.New_Supplier_Renewal_Opt_Out__c = ConvertedLead.New_Supplier_Renewal_Opt_Out__c;
                updateopr.Partner_Reference__c = ConvertedLead.Partner_Reference_Number__c;
            
             */
                //if(ConvertedLead.Current_Supplier__c != null) updateopr.Current_Supplier__c = ConvertedLead.Current_Supplier__c;
                if(ConvertedLead.Related_Utility__c == 'Gas'){
              /*        Acc.HasGas__c =  true;
                    if(ConvertedLead.MPR_2__c != null)Acc.MPR_2_Account_2__c =  ConvertedLead.MPR_2__c;
                    Acc.MPR_1_Account_2__c =  ConvertedLead.MPR_1__c;
                    
                    updateopr.Name = 'Gas';
                    updateopr.Related_Utility__c = 'Gas';
                    //updateopr.Current_Supplier__c = ConvertedLead.Current_Supplier_Electricity__c;
                    updateopr.Current_Supplier__c = ConvertedLead.Current_Supplier_Gas__c;
                    //updateopr.Current_Supplier__c = ConvertedLead.Current_Supplier__c;
                    updateopr.Current_Gas_Unit_Price_2__c = ConvertedLead.Current_Gas_Unit_Price_2__c;
                    updateopr.Current_Gas_Unit_Price_1__c = ConvertedLead.Current_Gas_Unit_Price_1__c;
                     
                    updateopr.Annual_Spend__c = ConvertedLead.Annual_Spend_Gas__c;
                    updateopr.Current_Gas_Unit_Price_1__c = ConvertedLead.Current_Gas_Unit_Price_1__c;
                    
                    updateopr.Contract_Status__c = ConvertedLead.Contract_Status_Gas__c;
                    
                    if(ConvertedLead.MPR_2__c != null)updateopr.MPR_2__c = ConvertedLead.MPR_2__c ; 
                    updateopr.MPR_2_AQ__c = ConvertedLead.MPR_2_AQ__c; 
                    updateopr.MPR_1__c = ConvertedLead.MPR_1__c; 
                    updateopr.MPR_1_AQ__c = ConvertedLead.MPR_1_AQ__c;
                    
                         
                */
                    if(ConvertedLead.Actual_Expiry_Date_Gas__c != null){updateopr.Actual_Expiry_Date__c = ConvertedLead.Actual_Expiry_Date_Gas__c;} 
                    
                     if(ConvertedLead.Contract_Status_Gas__c == 'In Contract'){
                        updateopr.StageName = 'Prospecting';
                    } 
                    
                }
                 if(ConvertedLead.Current_Supplier_Gas__c == ConvertedLead.New_Supplier__c){
                //   updateopr.Current_Supplier__c = ConvertedLead.New_Supplier__c;
                 }
                 
                  if(ConvertedLead.Current_Supplier_Electricity__c == ConvertedLead.New_Supplier__c){
                    // updateopr.Current_Supplier__c = ConvertedLead.New_Supplier__c;
                 }
                   
                    //updateopr.Contract_Term_Months__c = ConvertedLead.Contract_Term_Months_FL__c ;
                    
                    if(ConvertedLead.Related_Utility__c == 'Electricity' || ConvertedLead.Related_Utility__c == 'Gas & Electricity'){
                     // Acc.HasElectricity__c = true;
                     
                    /*updateopr.Name = 'Electricity';
                    updateopr.Related_Utility__c = 'Electricity';
                    updateopr.KVA__c = ConvertedLead.KVA__c;
                    /*updateopr.MPAN_1_Top_Line__c = ConvertedLead.MPAN_Profile__c+ConvertedLead.MTC__c+ConvertedLead.LLF__c;
                    updateopr.MPAN_1_Bottom_Line__c = ConvertedLead.MPAN_Dis_Id__c+ConvertedLead.MPANLeft__c+ConvertedLead.MPANMid__c+ConvertedLead.MPANRight__c;
                    if( ConvertedLead.Rel_MPAN_Profile__c != null )updateopr.MPAN_2_Top_Line__c = ConvertedLead.Rel_MPAN_Profile__c;
                    if(ConvertedLead.Rel_MTC__c != null) updateopr.MPAN_2_Top_Line__c += ConvertedLead.Rel_MTC__c+ConvertedLead.Rel_LLF__c;
                    if(ConvertedLead.Rel_LLF__c != null) updateopr.MPAN_2_Top_Line__c += ConvertedLead.Rel_LLF__c;
                    if(ConvertedLead.Rel_MPAN_Dis_Id__c != null) updateopr.MPAN_2_Bottom_Line__c = ConvertedLead.Rel_MPAN_Dis_Id__c+ConvertedLead.Rel_MPANLeft__c+ConvertedLead.Rel_MPANMid__c+ConvertedLead.Rel_MPANRight__c;
                    if(ConvertedLead.Rel_MPANLeft__c != null) updateopr.MPAN_2_Bottom_Line__c += ConvertedLead.Rel_MPANLeft__c;
                    if(ConvertedLead.Rel_MPANMid__c != null) updateopr.MPAN_2_Bottom_Line__c += ConvertedLead.Rel_MPANMid__c;
                    if(ConvertedLead.Rel_MPANRight__c != null) updateopr.MPAN_2_Bottom_Line__c += ConvertedLead.Rel_MPANRight__c;

                    updateopr.LLF__c = ConvertedLead.LLF__c;
                    updateopr.MPAN_Profile__c = ConvertedLead.MPAN_Profile__c;
                    updateopr.MPAN_Dis_Id__c = ConvertedLead.MPAN_Dis_Id__c;
                    updateopr.MPANLeft__c = ConvertedLead.MPANLeft__c; */
                    if(ConvertedLead.Actual_Expiry_Date_Electricity__c != null){updateopr.Actual_Expiry_Date__c = ConvertedLead.Actual_Expiry_Date_Electricity__c;}
                //  updateopr.MPANMid__c = ConvertedLead.MPANMid__c;
                //  updateopr.MPANRight__c = ConvertedLead.MPANRight__c;
                //  updateopr.Related_MPAN__c = ConvertedLead.Related_MPAN__c;
                    
                    //updateopr.Contract_Status__c = ConvertedLead.Contract_Status_Electricity__c;
                    
                    //if(ConvertedLead.Rel_MPAN_Profile__c!= null)updateopr.Related_MPAN_Profile__c = ConvertedLead.Rel_MPAN_Profile__c;
                    
                    //if(ConvertedLead.Rel_MTC__c != null)updateopr.Related_MTC__c = ConvertedLead.Rel_MTC__c;
                    //if(ConvertedLead.Rel_LLF__c != null) updateopr.Rel_LLF__c = ConvertedLead.Rel_LLF__c;
                    //if(ConvertedLead.Rel_MPANLeft__c != null) updateopr.Rel_MPANLeft__c = ConvertedLead.Rel_MPANLeft__c;
                    //if(ConvertedLead.Rel_MPANMid__c != null) updateopr.Rel_MPANMid__c = ConvertedLead.Rel_MPANMid__c;
                    //if(ConvertedLead.Rel_MPANRight__c != null) updateopr.Rel_MPANRight__c = ConvertedLead.Rel_MPANRight__c;
                    //updateopr.MTC__c = ConvertedLead.MTC__c;
                    //updateopr.Voltage__c = ConvertedLead.Voltage__c;
                    //updateopr.Current_Supplier__c = ConvertedLead.Current_Supplier_Electricity__c;
                    //updateopr.Email_Contact_del__c = cnt.Id;
                    
                    //updateopr.Electric_AQ_Day__c = ConvertedLead.Electric_AQ_Day__c;
                    //updateopr.Electric_AQ_Eve_W_end__c = ConvertedLead.Electric_AQ_Eve_W_end__c;
                    //updateopr.Electric_AQ_Night__c = ConvertedLead.Electric_AQ_Night__c;
                    //updateopr.Annual_Spend__c  = ConvertedLead.Annual_Spend_Electricity__c;
                    
                    //updateopr.Site_Building_Number__c = ConvertedLead.Site_Buiilding_Number__c;
                     //updateopr.Site_Building_Name__c = ConvertedLead.Site_Buiilding_Name__c;
                     //updateopr.Site_Street__c = ConvertedLead.Site_Street__c;
                     //updateopr.Site_Postal_Code__c = ConvertedLead.Site_Postal_Code__c;
                     //updateopr.Site_County__c = ConvertedLead.Site_County__c;
                     //updateopr.Site_Country__c = ConvertedLead.Site_Country__c;
                     //updateopr.Site_City__c = ConvertedLead.Site_City__c; 
                     
                }
                                
                if(ConvertedLead.Related_Utility__c == 'Gas & Electricity'){
                    //Opportunity oppr = CreateGasOpportunity.createOpportunity(ConvertedLead, UserProfileId, Acc, cnt); 
                 // oppr.Lead_Created__c = formatDate;
                    //Acc.HasGas__c =  true;
                //  Acc.MPR_2_Account_2__c =  ConvertedLead.MPR_2__c;
                    //Acc.MPR_1_Account_2__c =  ConvertedLead.MPR_1__c;
                    //oppr.Customer_Type__c = 'New Customer';
                    //oppr.Type = 'New Business';
                    //oppors.add(oppr);
                   // ConvertedLead.addError('Lead cannot be converted');
                }
                
                if(updateopr.Name == 'Electricity'){
                   if(ConvertedLead.Related_Utility_Type__c == 'Non Half Hourly'){
                      //    updateopr.KVA__c = ConvertedLead.KVA__c ;
                       //   updateopr.Voltage__c = ConvertedLead.Voltage__c;
                   }    
                }
                 if(ConvertedLead.Contract_Status__c == 'In Contract'){
                    updateopr.Type = 'Future Business';
           }
                if(ConvertedLead.Related_Utility__c == 'Gas'){
                //updateopr.Current_Supplier__c = ConvertedLead.Current_Supplier_Gas__c;
                }
                // Create Opportunity Task
                // Create Task for the Opportunity
                if(ConvertedLead.Name_of_Decision_Maker__c != null){
                   List<String> Str = ConvertedLead.Name_of_Decision_Maker__c.split(' ',-2);
                   String FirstName = '';
                   String LastName = '';
                   if(Str.size() == 1)LastName = Str.get(0);
                   if(Str.size() > 1){
                        FirstName = Str.get(0);
                        LastName = Str.get(1);
                   }
                   Contact decisionMakerContact = new Contact(AccountId = Acc.Id, FirstName = FirstName, LastName = LastName,Phone=ConvertedLead.Phone,Email=ConvertedLead.Email,MailingCity=ConvertedLead.RA_City__c,MailingPostalCode=ConvertedLead.RA_Postal_Code__c,MailingStreet=ConvertedLead.RA_Street__c,Title=ConvertedLead.Title);
                   decisionMakerContacts.add(decisionMakerContact);
                } 
                //updateopr.Customer_Type__c = 'New Customer';
                //updateopr.Type = 'New Business';
                updateopr.Opportunity_Contact_Name__c = cnt.Name;
                updateopr.Email_Contact_del__c = cnt.Id;
                updateopr.Lead_Created__c = ConvertedLead.createdDate.date();
                Acc.Lead_Created_Date__c = ConvertedLead.createdDate.date();
                Accs.add(Acc); 
                updateOprs.add(updateopr);
              }
          } 
    }
    
    update Accs;
    update updateOprs;
//  if(oppors.size() > 0){insert oppors;}
    if(decisionMakerContacts.size() > 0){insert decisionMakerContacts;}
}

 

I am getting error in the 3 last line 

 

 

update updateOprs;

 

Please help

  • September 23, 2010
  • Like
  • 0

I've an SOQL which queries an object and its associated Account & Contact values like this:

 

CustomObject__c co = [Select ID, Account__c, Contact__c, OwnerID From  CustomObject__c Where ID =: idvar];

 

Now, this works fine in my Development org. I can read the record in above query. But in user org I could not do so. Just so you know, I am "not" using "with sharing" keyword in my Apex Class. So automatic sharing does not apply to the SOQL results, right?

 

The only difference I can note in the 2 orgs is: User has Record Types created. DO anyone know if RecordType can effect user read permissions?

 

I've verified "Sharing Settings" too, the values are identical in both orgs, and also user is using same profile settings and Same Group as I'm using in my Dev org.

 

 

Please help, this is really bugging me out, I don't know what is making the record invisible in soql ... :(

  • September 23, 2010
  • Like
  • 0

We have a business requirement to track the # of days between an opportunity being created and the first completed task against that opp.

 

I've created 2 triggers and 1 apex class to achive this. The triggers work as desired but i'm having trouble with the apex class. Since I don't have enough test coverage, I can't migrate this to production but i just can't figure out what needs to be corrected on the test class. Can someone please help me with this?

 

1) Store an activity completed date

 

 

trigger Task_Completed_Date on Task (before insert, before update) {
   Task[] checkTasks = Trigger.new;
   for(Task t : checkTasks){
      if(t.Status=='Completed'){
         t.DateTimeCompleted__c = System.now();
      }
   }
}

 

2) Update a custom field on the opp called "First_Activity_Completed_date__c" with that date

 

trigger Update_FirstCompletedActivity_onOpp on Task (after insert, after update){  
    List<Opportunity> Opp = new List<Opportunity>();  
    for (Task t: Trigger.new)  {   
    if(t.Type=='Call Back'&&t.Status=='Completed'){   
        Opp = [select Id,First_Completed_Activity__c from Opportunity where Id=:t.WhatId];     
        Opp[0].First_Completed_Activity__c = t.DateTimeCompleted__c;   
        update Opp;
        }
}
}

 Test Class

 

public class testTask_Completed_Date{

    static testmethod void testme(){
 
     Opportunity opp = [select First_Completed_Activity__c from Opportunity where recordtypeid = '012300000000lqDAAQ' limit 1];
                System.debug('[[[[[[[[[[[[[[[[[[[[[[ start '+opp.Id);
    System.assert(opp.First_Completed_Activity__c == null );  
    System.assert(opp.NextStep != 'xx' );  
    Task tk = new Task(OwnerId = opp.OwnerId,Status='Not Started',Subject = 'test', Type = 'Test', ActivityDate = Date.newInstance(2026,10,10),WhatId = opp.Id);
    insert tk;
    opp = [select First_Completed_Activity__c from Opportunity where Id = :opp.Id ];

    tk.ActivityDate = Date.newInstance(2026,11,10);
    update tk;
    opp = [select First_Completed_Activity__c from Opportunity where ownerid = '00530000000ybdAAAQ' limit 1 ];

    
    //Events

    Schema.DescribeFieldResult f = Event.Type.getDescribe();
    List <Schema.PicklistEntry> typevalues = f.getPicklistValues();
    List<Event> events = new List<Event>();
    for (Schema.PicklistEntry avalue :typevalues) {
      events.add(new Event(OwnerId = opp.OwnerId, Subject = 'test', ActivityDateTime= Datetime.now()+5 ,DurationInMinutes=60, WhatId = opp.Id, Type = avalue.getValue()));
    }
    insert events;          
      }
}

 

 

 

  • September 22, 2010
  • Like
  • 0

Hey guys,

 

At the moment I'm working on a Contact Page. The good news is that it does send a message. The bad news is, while I know how to check to see if necessary fields are missing, I don't know how to to show that to the user.

 

Furthermore, I want when a email IS sent to link the user to a page saying that they have sent it. Or at least give them a message.

 

Here is my code and controller for both pages

 

 

<apex:page title="Configero - Company" showHeader="false" controller="sendEmail">
    <title>Configero - Contact Us</title>
    <apex:composition template="ConfigeroTemplate">
        <apex:define name="mainContent">

             <apex:outputPanel styleclass="block" style="float:left;display:inline;width:445px">
                <div class="blockTitle"><span class="blue">Contact</span> Us</div>
                <div class="blockBody">
                    <p>If you have any questions or would like a quote for one of our services, please call 404.229.2232 or contact us via email at <a href="mailto:info@configero.com">info@configero.com</a>.</p>
                    <apex:form >
                        Your Name <span class="red">*</span> <br/><apex:inputText id="name" value="{!conname}" size="50"/> <br/>
                        Email Address <span class="red">*</span><br/><apex:inputText id="email" value="{!remail}" size="50"/> <br/>
                        Subject <span class="red">*</span><br/><apex:inputtext id="subject" value="{!subject}" size="50"/><br/>
                        Message <span class="red">*</span><br/><apex:inputTextarea id="message" value="{!body}" cols="59" rows="5"/> <br/>
                        <apex:commandButton value="Send Email" action="{!send}"/>
                    </apex:form>
                </div>
            </apex:outputPanel> 
            
        </apex:define>
    </apex:composition>
</apex:page>

 

public class sendEmail {
    public String subject { get; set; }
    public String body { get; set; }
    public String REmail {get; set; }
    public String ConName {get; set;}

    private final Account account;

    // Create a constructor that populates the Account object  
    
    /*public sendEmail() {
        account = [select Name, (SELECT Contact.Name, Contact.Email FROM Account.Contacts) 
                from Account where id = :ApexPages.currentPage().getParameters().get('id')];
    }*/

    public Account getAccount() {
        return account;
    }

    public PageReference send() {
        // Define the email  
        if(REmail == '')
        {
           //Fields not entered
           return null;
        }
        else if(ConName == '')
        {
            return null;
        }
        else if(Subject == '')
        {
            return null;
        }
        else if(body == '')
        {
            return null;
        }
        else
        {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 



        String[] toAddresses = new String[] {'email@gmail.com'};

        // Sets the paramaters of the email  
    
        email.setReplyTo( REmail);
        email.setSubject( 'New Contact Message: '+subject );
        email.setToAddresses( toAddresses );
        email.setPlainTextBody( 'Message: ' + body +'\r Signed: '+ConName );
    
        // Sends the email  
    
        Messaging.SendEmailResult [] r = 
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
        
        return null;
        }
    }
}

 Any advice is appreciated. Thanks

 

  • September 22, 2010
  • Like
  • 0

Hi,

We are doing email validation solution.

The solution has two implementations:

1. An after update trigger which is installed on the Lead objects so that when a lead is updated from an external forma (in Facebook for example) the trigger fires a future method which does a webservice call which validates the email and replaces the current email with the validated one.

2. We have an interactive part where when a user edits the Lead record from the user interface we popup a window with both the original email and the validated email and let the user choose which one he/she wants to leave.

 

Now the problem is when we install both solutions and the user edits a lead from the user interface. Then the email will be validated by both our interactive solution and the trigger.

What we need is a way for the trigger to find out that that lead was updated by the user interface and not fire.

Ideally we would not want to extend the lead with another field and having the user interface fill in that field we are looking for minimum to non intrusive solution to this if possible.

 

Thanks,

Kos

  • September 22, 2010
  • Like
  • 0

iam new to apex.urgent need of test class for apex class

 

my apex class

 

public class MyController {
public ID accountId {get;set;}
  public String email {get;set;}
public String getName() {
return 'MyController';
}
public Opportunity getOpportunity() {
return [select Account.Id, Account.name, Account.G_English_Name__c, Account.B_English_Name__c, Contact__r.name, Contact__r.MailingStreet,Contact__r.MailingCity,
        Contact__r.MailingState, Contact__r.MailingPostalCode, Contact__r.MailingCountry from Opportunity
where id = :ApexPages.currentPage().getParameters().get('id')];
}


public PageReference sendPdf() {

    PageReference pdf = Page.pdfgeneratortemplate;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',accountId);
 
    // 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('Some Text');
    }
 
    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
    attach.setContentType('application/pdf');
    attach.setFileName('testPdf.pdf');
    attach.setInline(false);
    attach.Body = body;
 
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setUseSignature(false);
    mail.setToAddresses(new String[] { 'anand.2861985@gmail.com' });
    mail.setSubject('PDF Email Demo');
    mail.setHtmlBody('Here is the email you requested! Check the attachment!');
    mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
 
    // Send the email
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with PDF sent to '+email));
 
    return null;
 
  }
 
}

Hi All,

          I have a small problem with my controller. I am trying to get values from a custom object  and trying to update the values. But it is not working fine. I have paste the visualforce code and the controller below:

 

 

<apex:page standardcontroller="Case" sidebar="false" showHeader="false" extensions="SubmitCaseController">
             
                           
       <apex:outputPanel styleClass="box1" style="border-style:none;border-widht:0px;background-color: #FFFFFF;margin-top:35px" >        
 
         <apex:outputPanel styleClass="box1" style="border:none">
    <apex:dataTable columns="2" id="firstbox1" value="{!List}" var="p" rendered="{!(List!=null)}">
        <apex:column styleClass="c1">
            <apex:outputtext value="Profile Name"/>
        </apex:column>
        <apex:column styleClass="c2">
            <apex:inputtext value="{!p.Name}" style="width:250px"/>
        </apex:column>
        <apex:column styleClass="c1">
            <apex:outputtext value="Operating System"/>
        </apex:column>
        <apex:column styleClass="c2">
            <apex:inputtext value="{!p.operating_system__c}" style="width:250px"/>
        </apex:column>
        <apex:column styleClass="c1">
            <apex:outputtext value="Application Development Language"/>
        </apex:column>
        <apex:column styleClass="c2">
            <apex:inputtext value="{!p.Application_Development_Language__c}" style="width:250px"/>
        </apex:column>
        <apex:column styleClass="c1">
            <apex:outputtext value="Database"/>
        </apex:column>
        <apex:column styleClass="c2">
            <apex:inputtext value="{!p.Database__c}" style="width:250px"/>
        </apex:column>
        <apex:column styleClass="c1">
            <apex:outputtext value="Web Server"/>
        </apex:column>
        <apex:column styleClass="c2">
            <apex:inputtext value="{!p.Web_Server__c}" style="width:250px"/>
        </apex:column>
        <apex:column styleClass="c1">
            <apex:outputtext value="Servlet Engine"/>
        </apex:column>
        <apex:column styleClass="c2">
            <apex:inputtext value="{!p.Servlet_Engine__c}" style="width:250px"/>
        </apex:column>
         <apex:column styleClass="bbox1">
                                                     <apex:column styleClass="bbox1">
              
<apex:commandButton value="Update" action="{!Save}" />
               </apex:column>
    </apex:dataTable>               
</apex:outputPanel>    
                     </apex:outputPanel>
        </apex:form>
   </apex:outputPanel>
</apex:page>

 

My controller is as follows:

 

public abstract class SubmitCaseController {

   
    public SubmitCaseController(ApexPages.StandardController controller) {
           }
    
   public List<Customer_Profile__c> cList{get;set;}
                 
   public PageReference Save(){
             update cList;
             return null;
   }
  
    
      public List<Customer_Profile__c> getList(){     
        cList = [select Id,Name,Application_Development_Language__c,Database__c,operating_system__c,Servlet_Engine__c,Web_Server__c from Customer_Profile__c where Account__r.Name =:accName];
              return cList;
    }        
    
     }

 

 

Can anyone please help me with this issue. Thanks in advance.

Hey guys,

 

I'm integrating google maps using their JS API V3, and I've got it working except for one stupid little thing...

 

Basically, I wanted to perform queries through APEX (to minimize client resource usage) then pass those results back to the PAGE for googleMap JS API processing.

 

 

When the user input search parameters, and clicks a command link, the link calls an action function which initiates the query by passing the parameters back to the controller. The controller initiaites the query, and processes the results.

 

Here is where I get stuck!

 

How do I pass those results back as a JS friendly multidimensional array?

 

I've made an ugly controller that takes the list and constructs a string in the form of a JS array.

 

(assume I've done my query, and populated public address__c [] addresses = new address__c[0];

 

	public string  getFormattedAddresses() {
		for (integer i = 0;i < addresses.size(); i++ ) {
			address__c a = addresses.get(i);
			//Construct a friendly string...
			// name = 1
			// lat = 2
			// long = 3
			// streetAddress = 4
			
			if (formattedAddresses != null) {
				formattedAddresses = formattedAddresses + ', [\''
				+ a.id + '\', \'' 				//0 string
				+ a.name + '\', ' 				//1 string
				+ a.lat__c + ', '				//2 int
				+ a.long__c + ', \''			//3 int
				+ a.streetAddress__c + '\']';   //4 string
			} 
			else {
				formattedAddresses = '[\'' 
				+ a.id + '\', \'' 				//0 string
				+ a.name + '\', ' 				//1 string
				+ a.lat__c + ', '				//2 int
				+ a.long__c + ', \''			//3 int
				+ a.streetAddress__c + '\']';   //4 string
			}
		}
		return formattedAddresses;
	}

 

 

Then, on the VF page, once the query has been completed, the actionstatus performs the googleMap initialize function, and passes that string value (which I've rendered in the page as an inputHidden) into the function:

 

                <!-- Call the initialize function when done and pass the results. -->
                <apex:actionStatus id="mapStatus" 
                    startText="    Going..." 
                    stopText="     Done!" 
                    onstop="initialize(document.getElementById('{!$Component.formattedAddresses}').value)"/>

 

 

my Initialize function looks like this:

 

        <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false&callback=initialize">
        </script>

    <script type="text/javascript" >
        var markers = new Array();

        function initialize(formattedAddresses) {
            alert('Initialize() was called!');
            <!--Here is the initial lat/long... In the future, this should be centered on the users actual point if avail through blackberry I should also add a marker here one time-->
            var myLatlng = new google.maps.LatLng(49.286711, -123.113815);
            var myOptions = {
                zoom: 12,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            <!-- my maps bounds so we can dynamically fit them to the view -->
            var bounds = new google.maps.LatLngBounds();

            <!-- This is the JS list of addresses... This is passed right from the googleMapController after being formatted to be JS friendly -->
            var addresses = [
               formattedAddresses
            ];

            <!-- How many addresses do I have? -->
            alert('Number of addresses: ' + addresses.length + '= ' + addresses);
            
            <!-- The info window instance we will use to populate data -->
            //var info = new google.maps.InfoWindow();

            <!-- Loop through the addresses and add them as markers -->
            for(var i = 0; i < addresses.length; i++) {
                <!-- My specific address -->
                var addressToMark = addresses[i];
                <!--  Now pull out the specific addresses columns to make a latlng NOTE we should never change these columns! -->
                var latLng = new google.maps.LatLng(addressToMark[2], addressToMark[3]); 
                
                <!-- Now create a marker in the array -->
                markers[i] = new google.maps.Marker({
                    position: latLng,
                    map: map,
                    title: addressToMark[1]
                });
                
                <!--  Now fit the bounds to include this marker -->
                bounds.extend(latLng);
                map.fitBounds(bounds);

                <!-- Now call an external function to create infowindow for that marker... -->
                attachInfo(markers[i], i);
            }
            <!-- end for loop -->
            
            <!-- Attach infoWindow to a specified marker -->
            function attachInfo(marker, number) {
                var addressToInfo = addresses[number];
                    var infoHtml = '<a href="/' + addressToInfo[0] + '">' + addressToInfo[1]; + '</a>' + 
                    '<p>' + addressToInfo[4] + '</p>'
                    var infowindow = new google.maps.InfoWindow({ 
                        content: infoHtml
                    });
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map,marker);
                });
            }
            <!-- end attachInfo -->
        }
        <!-- End initialize -->

 

When it gets to the alert to prove that I have addresses in my array, it looks like this:

 

 

Number of addresses: 1= ['a07A0000006Rv78IAC', 'ADD-0000002', 49.2867114, -123.113815, '250 Howe st'], ['a07A0000006Rv6yIAC', 'ADD-0000001', 49.2766039, -123.1173663, '950 cambie street'], ['a07A0000006RuzmIAC', 'ADD-0000000', 49.213630, -122.961624, '6860 Rumble st'], ['a07A0000006S3CbIAK', 'ADD-0000006', 49.1681134, -122.5905083, '9124 Gay st']

 

Which is of course wrong... it should say 4 addresses, not 1.

 

 

If i manually paste that alert into my initialize function like so:

 

            <!-- This is the JS list of addresses... This is passed right from the googleMapController after being formatted to be JS friendly -->
            var addresses = [
               
['a07A0000006Rv78IAC', 'ADD-0000002', 49.2867114, -123.113815, '250 Howe st'], ['a07A0000006Rv6yIAC', 'ADD-0000001', 49.2766039, -123.1173663, '950 cambie street'], ['a07A0000006RuzmIAC', 'ADD-0000000', 49.213630, -122.961624, '6860 Rumble st'], ['a07A0000006S3CbIAK', 'ADD-0000006', 49.1681134, -122.5905083, '9124 Gay st']
            ];

 It works fine!!!

 

Number of addresses: 4= a07A0000006Rv78IAC,ADD-0000002,49.2867114,-123.113815,250 Howe st,a07A0000006Rv6yIAC,ADD-0000001,49.2766039,-123.1173663,950 cambie street,a07A0000006RuzmIAC,ADD-0000000,49.21363,-122.961624,6860 Rumble st,a07A0000006S3CbIAK,ADD-0000006,49.1681134,-122.5905083,9124 Gay st

 

 

 

 

 

So where am I going wrong with my string/array?

 

Thanks!

  • September 13, 2010
  • Like
  • 0

Anyone know of a way to get the Week of the Month (number 1 to 5 depending on month/calendar) in Apex Classes?

If there is custom code that someone has built, please let me know.  THANKS.

 

 

I only found Day of Year for the Salesforce datetime methods.

 

example:  Day of Year

 

Datetime myDate = datetime.newInstance(2008, 2, 5, 8, 30, 12);
system.assertEquals(myDate.dayOfYear(), 36);

I have a custom object that is using record types.  I am also using the Account Tabbed view.

 

In order to show one record type per tab on my account, I created a custom controller and used that to create my lists.  I am trying to add a new button to each tab so users can create new records.

 

I am having a problem getting the account ID into the custom object.  When I use the following, it assigns the accounts ID to the name field on the custom object.  Trying to figure out how I correctly assign the account to the custom object.

 

Any help would be greatly appreciated!!! Thanks!!!!

 

 

 public PageReference NewEnrollHealth() {
    Id Aid = ApexPages.currentPage().getParameters().get('id');
    PageReference pageRef = new PageReference('https://cs3.salesforce.com/a01/e?CF00N700000021Lm4='+Aid+'&CF00N700000021Lm4_lkid=001Q000000EAALT');
   
            return PageRef;
      }

 

 

  • September 13, 2010
  • Like
  • 0

We're using Visualforce pages more and more here, but we've been working around something for a while that I think is probably pretty simple.

 

Many times, we have multiple visualpage pages that use different controllers (or extensions) based on the record type, or how many records we want to pull. 

 

I see there are several different examples using javascript / params to have a user pass a variable value to a controller - we've been successful there.  But I would simply like to set the variable value when the page loads, so for instance if they go to a page that is supposed to display only 30 records, verses a page that is supposed to display 180 records.  Is there a simple way to pass this value to a controller variable using the <apex:page action=""> perhaps?

  • September 13, 2010
  • Like
  • 0

I have a page with two commandbuttons and two action methods in the controller.

 

The page is built using the OppLineItem standardController and is using the lineitem to derive field to create a custom Object record - an Order in this case.

 

The buttons are called 'Cancel' and 'SaveOrder'

 

The Cancel method, is just a pagereference going back to the previous page.

 

The SaveOrder method captures the data from the inputfields on the page adds them to a new Order record and inserts, and then redirects the user to the Opportunity record. 

 

Straightforward stuff. The Cancel button works perfectly. The SaveOrder button does nothing but refresh the page (in fact it does this twice, runs through the entire process of setting up the page twice and quits).Not even the debug statement I put in the first line of the method shows up in the debug log.

 

Here's the weird part. If I switch the action method names - call the Save method 'Cancel', and the Cancel method 'SaveOrder', and then click the Cancel button - the method works!!!!! It creates the record and redirects the user.But if I click the saveOrder button in this case - I get the same behavior - it just refreshes the page.

 

Here is the relevant code:

 

    public PageReference cancel()
    {
    	returnPage = new PageReference('/apex/ManageOrders_QC?id='+OLI.OpportunityId).setRedirect(true);
    	return returnPage;
    }
    public PageReference saveOrder()
    {
    	system.debug('Start Save');
        ... other code

        returnPage = new PageReference('/apex/ManageOrders_QC?id='+OLI.OpportunityId).setRedirect(true);
    	return returnPage;
    }

<apex:page standardController="OpportunityLineItem" extensions="Controller_NewManualOrder" >
    <apex:form >
         <apex:pageBlock id="OrderFields">
             <apex:pageBlockButtons id="Buttons">
                <apex:CommandButton id="SaveButton" value="Save Order" action="{!saveOrder}"/>
                <apex:CommandButton id="cancelButton" value="Cancel" action="{!cancel}"/>
                <apex:CommandButton id="returnButton" value="Return to Opportunity" action="{!ReturnToOpp}"/>
                
            </apex:pageBlockButtons>
            ...PageBlocktable showing fields
         </apex:pageBlock>
    </apex:form >
</apex:page>

 What is going on here?

 

 

 

Hi.

i had made a class test in sandbox, gives me 81%..then i deploy the class to production to run , gives me an error : Failure Message: "System.QueryException: List has no rows for assignment to SObject", Failure Stack Trace: "Class.myClass.myTest: line 6, column 21 External entry point"

 

this is my class:

line 6 is this: 

Product2 produto3 = [select id from Product2 where name = 'DSL 10ppm CIF NWE AAWZC00'];

Can help me?

 

 

@isTest 
private class myClass {
    static testMethod void myTest() {
//--------------------------------------------------
 
Product2 produto3 = [select id from Product2 where name = 'DSL 10ppm CIF NWE AAWZC00'];
RecordType rtp = [select id from RecordType where name = 'Platts'];
Pricing__c p = new Pricing__c (RecordTypeId = rtp.id, produto__c =produto3.id, valor_inicial__c =1, cambio_usd_ton__c = 1,
valido_de__c =date.today(), valido_ate__c= date.today());
insert p;



Product2 produto4 = [select id from Product2 where name = 'Diesel - PVP'];
RecordType rtpp4 = [select id from RecordType where name = 'Preço de Venda'];
Pricing__c p4 = new Pricing__c (RecordTypeId = rtpp4.id, produto__c = produto4.id, 
valido_de__c =date.today(), valido_ate__c= date.today());
insert p4;


Product2 produto_composto2 = [select id from Product2 where name = 'COMBUSTÍVEL BIODIESEL 10%'];
RecordType rtpp = [select id from RecordType where name = 'Produtos Compostos'];
Pricing__c p3 = new Pricing__c (RecordTypeId = rtpp.id, produto__c = produto_composto2.id, 
valido_de__c =date.today(), valido_ate__c= date.today());
insert p3;
Account acc = new Account(name='testing account');
        insert acc;
Account acc_filho = new Account(name='testing account filho');
        insert acc_filho;
        
Account a = [select Parentid from Account where //id ='001Q000000AdLXY'
id= :acc_filho.id];

a.parentid = acc.id;
//'001Q000000AdLXO';
update a;

Account aa = [select Parentid from Account where id= :acc_filho.id];

aa.parentid = null;
update aa;
 
Partidas_Financeiras__c pf_criar = new Partidas_Financeiras__c(conta__c = acc.id,valor_liquido__c =1 );
insert pf_criar;
    list<Partidas_Financeiras__c> pf = [select Recebido_aguarda_registo_em_SAP__c from
    Partidas_Financeiras__c where conta__c = :acc.id];
    for(Partidas_financeiras__c pfff : pf){
pfff.Recebido_aguarda_registo_em_SAP__c =true;
}
update pf;   
        
 //create a test opportunity

        Opportunity op = new Opportunity(name='testopp1', StageName='Prospecting', CloseDate = date.today(), 
        AccountId = acc.Id);
        insert op;
        Product2 produto = [select id from Product2 where name = 'COMBUSTÍVEL GASÓLEO'];
        PriceBookEntry pbookEntry = [select id from PriceBookEntry where Product2Id = :produto.id];
        Centro_de_carga__c cdc = [select id from Centro_de_carga__c where name = '01 - PrioAF: Matosinhos'];
        //create opportunity line item
        OpportunityLineItem olitem = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry.Id, 
        Quantity = 1,centro_de_carga2__c = cdc.id, tipo_de_preco_de_referencia__c = 'Preço de Compra',
        incoterms__c = 'EXW');
        insert olitem;

        Product2 produto_composto = [select id from Product2 where name = 'COMBUSTÍVEL BIODIESEL 10%'];
        PriceBookEntry pbookEntry2 = [select id from PriceBookEntry where Product2Id = :produto_composto.id];
        Centro_de_carga__c cdc2 = [select id from Centro_de_carga__c where name = '01 - PrioAF: Matosinhos'];
        OpportunityLineItem olitem2 = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry2.Id, 
        Quantity = 1,centro_de_carga2__c = cdc2.id, tipo_de_preco_de_referencia__c = 'Preço de Compra',
        incoterms__c = 'EXW');
        insert olitem2;
       
Product2 produto_composto3 = [select id from Product2 where name = 'COMBUSTÍVEL BIODIESEL 20%'];
PriceBookEntry pbookEntry3 = [select id from PriceBookEntry where Product2Id = :produto_composto3.id];
            OpportunityLineItem olitem3 = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry3.Id, 
        Quantity = 1,tipo_de_preco_de_referencia__c = 'Preço de Venda',
        incoterms__c = 'EXW');
        insert olitem3;
    
        Product2 produto7 = [select id from Product2 where name = 'COMBUSTÍVEL GASÓLEO'];
        PriceBookEntry pbookEntry4 = [select id from PriceBookEntry where Product2Id = :produto7.id];
        //create opportunity line item
        OpportunityLineItem olitem4 = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry4.Id, 
        Quantity = 1, tipo_de_preco_de_referencia__c = 'Platts',
        incoterms__c = 'EXW');
        insert olitem4;

 
//---------------------------------------------------------------------

Proposta__c pro =new Proposta__c (Oportunidade__c =op.Id, name ='teste',valido_de__c =Date.today(),
    Validade_em_dias__c =3, count_proposta__c =1 );
insert pro;

Proposta__c pro2= [select substituida__c  from Proposta__c where id = :pro.id];
pro2.substituida__c = true;
update pro2;

Proposta__c pro3 =new Proposta__c (Oportunidade__c =op.Id, name ='teste2',valido_de__c =Date.today(),
    Validade_em_dias__c =3 );
insert pro3;



//-----------------------------------------------------------
RecordType rt = [select id from RecordType where name = 'Combustíveis Compostos'];
Input_Resumo_pricing__c  irp= new Input_Resumo_pricing__c(RecordTypeId = rt.id, valido_de__c = Date.today(),
valido_ate__c = Date.today());
insert irp;

RecordType rt2 = [select id from RecordType where name = 'Combustíveis não Compostos'];
Input_Resumo_pricing__c  irp2= new Input_Resumo_pricing__c(RecordTypeId = rt2.id, valido_de__c = Date.today(),
valido_ate__c = Date.today());
insert irp2;

RecordType rt3 = [select id from RecordType where name = 'Pricing Manual'];
Input_Resumo_pricing__c  irp3= new Input_Resumo_pricing__c(RecordTypeId = rt3.id, valido_de__c = Date.today(),
valido_ate__c = Date.today());
insert irp3;

//--------------------------------------------------------------


//-----------------------------------------------


    }
}