• sforce2009
  • SMARTIE
  • 575 Points
  • Member since 2009

  • Chatter
    Feed
  • 23
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 16
    Questions
  • 196
    Replies

I need to set a query parameter in a test method.  The documentation makes only a quick reference to this, saying:

To set a query string parameter:

  • If you're writing a custom controller, use the setParameters() method with ApexPages.currentPage() to add a query parameter in a test method. For example:
    String key = 'name';
    String value = 'Caroline';
    ApexPages.currentPage().setParameters().put(key, value);
    Note
     The setParameters() method is only valid inside test methods.

However, when I put this in my test method, I get the error:

 

Save error: Method does not exist or incorrect signature: [System.PageReference].setParameters()    Testm62ConsoleController.cls    /m62 Sandbox/src/classes    line 80    Force.com save problem

 

Here is my test method:

 

 static testMethod void testConsoleController() {

		// Find a telesales user for the tests
        Profile p = [select id from profile where name='Telesales']; 
        User u = new User(alias = 'standt', email='standarduser@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', profileid = p.Id, 
            languagelocalekey='en_US', 
            localesidkey='en_GB', 
            timezonesidkey='Europe/London',
            username='standarduser@testorg.com');


        System.runAs(u) {
         		
		//Set up the data
		List<Account> accs = new List<Account>();
		for (Integer i=0; i<50; i++) {
			Account a = new Account(
				Name = 'Test Account 1',
				BillingCountry = 'United Kingdom',
				Phone = '+44 (0)12679 121 5555',
				To_be_cleansed__c = true
			);
			accs.add(a);
		}
		insert accs;
		
		List<Contact> conts = new List<Contact>();
		List<Task> tasks = new List<Task>();
		// Create two contacts for each account
		for (Integer i=0; i<50; i++) {
			Contact c = new Contact();
			c.FirstName = 'Test';
			c.LastName = 'Contact 1';
			c.AccountId = accs[i].Id;
			c.MailingCountry = 'United Kingdom';
			c.Email = 'no@email11111.com';
			c.Phone = '+44 (0)1423 564888';
			conts.add(c);
		
			Contact c1 = new Contact();
			c1.FirstName = 'Test';
			c1.LastName = 'Contact 1';
			c1.AccountId = accs[i].Id;
			c1.MailingCountry = 'United Kingdom';
			c1.Email = 'no2@email11111.com';
			c1.Phone = '+32 (0) 2 679 12 11';
			conts.add(c1);
			
			// Add a task for each account
			Task t = new Task(WhatId=accs[i].Id, Type='Telephone call', Subject='Test subject', Status='Not started', 
            				Priority='Normal'); 
            tasks.add(t);
		}
	
		insert conts;
		insert tasks;
		
        PageReference pageRef = Page.newConsole;  // Instantiate telesales console page
        Test.setCurrentPage(pageRef);
      
        //Instantiate and construct the controller class.   
        m62ConsoleController controller = new m62ConsoleController();		
		Test.startTest();
		
		controller.selectedAcc = accs[4];
		controller.last();
		if (controller.getHasPreviousAcc()) controller.previousAcc();
		if (controller.getHasNextAcc()) controller.nextAcc();
		
		controller.getMyAccounts();
		controller.first();
		String ids = accs[6].Id;
		ApexPages.currentPage().setParameters().put('AccSel', ids);

		ids = conts[12].Id;
		ApexPages.currentPage().setParameters().put('ConSel', ids);

		controller.resetConts();
		controller.viewCont();
		controller.resetTsks();
		controller.viewTsk();
		
	}
    }

 Can anyone advise what I'm doing wrong? I've searched all over for more information but can't find any.

Thanks.

 

I'm using the following javascript to invoke a new task for the primary contact (a custom lookup field on the Account object). The task is created just fine with the primary contact in the Contact field, but upon saving, it returns to the home page instead of the account page from which it was called. Any suggestions that would redirect this to the account page?

 

navigateToUrl('/00T/e?who_id={!Account.Primary_Contact_Lookup__c}&amp;retURL=%2F{!Account.Id}');

 

Thanks.

Hi guys.

 

Bit of a conundrum here...

 

I've got a VF page that has an inputText field that users use to scan in barcodes using a handheld barcode scanner.

The barcode scanner merely act like a keyboard: it translates the scan to keys, then types those keys and hits enter.

 

What I'd like to do, is have users scan a barcode, then conduct an apex query. If the results are good, it updates a record, if the results are bad - it throws a pageMessage.

 

I got some JS that checks when the enter key is hit, and then I envoke the apex. However, there seems to be an issue with the sequence of reRendering and apex, and JS.

 

When I do the scan into the input field - the page does a refresh - but the apex:PageMessage that should display does not...

 

Here's what I have so far:

 

 

<apex:page standardController="terminalPrepOrder__c" extensions="terminalPrepOrderController" >
<apex:variable var="prp" value="{!terminalPrepOrder__c}"/>

function checkEnter(e){ <!-- e is event object passed from function invocation -->
var characterCode <!--literal character code will be stored in this variable -->

if(e && e.which){ <!--if which property of event object is supported (NN4) -->
e = e
characterCode = e.which <!-- character code is contained in NN4's which property -->
}
else{
e = event
characterCode = e.keyCode <!-- character code is contained in IE's keyCode property -->
}

if(characterCode == 13){ <!-- if generated character code is equal to ascii 13 (if enter key) -->
alert("clicked enter");
otherFindTerminal(); <!-- submit the form -->
return false;
}
else{
return true
}
}
</script>

<apex:pageMessages id="msgs"/>
<apex:form id="theForm"> <apex:actionFunction name="findTerminal" action="{!otherFindTerminal}" reRender="msgs"/> <apex:outputText value="Scan Terminal Barcode "/> <apex:inputText value="{!searchBarcode}" onkeypress="checkEnter(event)"/> <apex:commandButton value="Find" action="{!otherFindTerminal}" id="hitMe" reRender="msgs"/> </apex:form>

 Controller:

 

	public PageReference otherFindTerminal() {  
        try {
            if (searchBarcode != '') {
              terminal__c enteredTrm = [select Id from Terminal__c T where T.barcodeNumber__c = :searchBarcode limit 1];        
           
             terminalPrepOrder__c trmPrp = (terminalPrepOrder__c) controller.getRecord();
           
             trmPrp.Terminal__c = enteredTrm.Id;
             update trmPrp;
            }
            else if (searchBarcode == '' ) {
                ApexPages.Message invalidSearch = new ApexPages.Message(ApexPages.Severity.ERROR, 'Invalid barcode.');
                ApexPages.addMessage(invalidSearch);
            }
        }
        catch (exception e) {
        
            ApexPages.Message noTrm = new ApexPages.Message(ApexPages.Severity.ERROR, searchBarcode + ' not found. Please enter the Terminal barcode.');
            ApexPages.addMessage(noTrm);
        }
        return null;
    }

 

 

 

So when I click the commandButton - it functions perfectly - It does the query, and rerenders the messages...

 

When I use the input field and hit enter... it refreshes the page but does nothing...

 

 

Please help!

Thanks

  • May 10, 2010
  • Like
  • 0
Hai all, I have a command link defined in a visualforce page.On clicking that,I want the value to be filled in a text area which is another visualforce page.Can anyone help me to this?

Hi,

 

I have a custom button on Contact Page layout. The button actually overrides a Visualforce page.

The visualforce page Uses controller extension to extend Standardcontroller 'Contact". The Extension is " InactiveandMove".

 

Now, i need to execute Javascript when clicked on the button which pops up a confirmation dialog like, " Are you sure?".

When clicked OK, it has to execute the Controller extension Action : "Move".

 

But for some reason i am unable to do it. when i click on the button, it raises a error like this:

 

A problem with the OnClick JavaScript for this button or link was encountered:
missing ; before statement

 

Everything looks fine, but i am unable to figure out the problem.

Am i missing anything or should this be done in a different way?

 

Here is the VF Page:

 

<apex:page standardController="Contact"  extensions="Inactiveandmove"   >
<apex:form >
<apex:actionFunction name="SendtoMoveFunction" action="{!Move}" reRender="{!Id}"/>
</apex:form>
<apex:PageBlock title="Confirmation">
<b><Font Color="Red" Size="3"> <apex:outputLabel rendered="{!errorFlag}" > {!errorMsg}</apex:outputLabel></Font></b><br/><br/>
<b><Font Color="Green" Size="2"> <apex:OutputText >Please Contact your System Admininstartor for any further action on this!</apex:OutputText></Font></b><br/>
</apex:PageBlock>

</apex:page>

Here is the Controller extension:

 

public class Inactiveandmove {

    public String errorMsg { get; set;}
    public Boolean errorFlag {get ; set;}  
     
     //Constructor
    public Inactiveandmove(ApexPages.StandardController controller) 
    {
        errorMsg = '';
        errorFlag = false;

    }  

    public Contact contact  { get; private set;}
    

//Function that does the main job

    public PageReference Move(){ // This is the Action function to be called from Java script.

    //System.debug('id==='+Apexpages.Currentpage().getparameters().get('Id'));
   //Check if the contact is associated with any campaign that is Active.
    List<CampaignMember> active_Campaigns=[Select ContactId from CampaignMember where Campaign.Isactive=True and Contactid=:Apexpages.Currentpage().getparameters().get('Id')];
   
    if(active_Campaigns.size()!=0)  //If present in any active campaign, do not delete the contact
    {
        errorFlag=true;
        errorMsg='Cannot Delete the Contact, as it is associated with an Active Campaign';
        return null;
    }
    
    else
    {
        //Get all the campaigns(Inactive Ones) the contact is associated with
        List<CampaignMember> inactive_Campaigns=[Select ContactId from CampaignMember where Contactid=:Apexpages.Currentpage().getparameters().get('Id')];
        for(CampaignMember cm:inactive_Campaigns)
            delete cm; //Delete the contact from the inactive campaigns
       
        //Get the contact ownerID and AccountName which has to be logically deleted.
        contact c=[SELECT ownerId,Account.Name FROM contact where Id=:Apexpages.Currentpage().getparameters().get('Id')];

        c.OwnerId='005A0000000h2hh'; //change to Admin
        //Set the other values accordingly
        //c.Status__c='Retired/Resigned';
        c.HasOptedOutOfEmail=True;
        c.DoNotCall=True;
        c.Email=' ';
        c.Phone=' ';
        //c.No_Postal_Mail__C=True;
        //c.Previous_Account_Name__c=c.Account.Name; // Gets the account name and puts that in this custom field.
        //System.debug('account name == '+c.Account.Name);
        c.AccountId=NULL;

        update c; //Update the contact with New Values.
        
        errorFlag=true;
        errorMsg='Record Deleted';
        return Null;
        }

    }

    //Test Method
    public static testMethod void InactiveandmoveTest()
    {
        Contact con = [Select id from contact limit 1];
        ApexPages.StandardController sc = new ApexPages.StandardController(con);
    
        System.debug('sc id =='+sc.getId());
    //    sc.setId('003Q0000008c1By');
        Inactiveandmove InactiveAndMoveTest = new Inactiveandmove(sc);
        Apexpages.currentPage().getParameters().Put('id',sc.getId());
        InactiveAndMoveTest.Move();
    
    }
}

 

Added a custom button on Contact:

 

Detail Page button

Onclick Javascript

 

Here is the JavaScript&colon;

 

{!REQUIRESCRIPT("/soap/ajax/17.0/connection.js")}
function confirmation() {
var answer = confirm("Are You Sure?")
if (answer){
S2M()

}
else{
alert("Thanks for sticking around!")
}
}

function executeS2M() {
var pageref = sendtoMoveFunction();
return pageref;
}
confirmation();

 

Any help on this is highly appreciated.

 

Thanks,

Sales4ce

I need a way to know what org I am in?  For example:

https://na7.salesforce.com

or

https://na4.salesforce.com

 

I want this so that I do not have to remember to manually change code when I move from DEV, to Sandbox to Production.

 

thanks,

Tom

 

Hi,

 

I have a custom Object called " Country Mapping__c", which has following custom fields, "Country__c", "My_Organization__c".

Now i need to look at the Lead country and then look into the Country Mapping object and get a corresponding "My Organization" Value.

 

for ex: Country Mapping Object:

 

Country                                       My_Organization

Uruguay                                      Chile

Japan                                           Asia

United States                              USA

United States of America          USA

US                                                  USA

UK                                                   UK

United Kingdom                           UK

 

If a lead has country value=Uruguay, i need to populate "My_Organization" on Lead with "Chile".

How can i accomplish this?

Any Help/Idea on this is highly appreciated.

 

here is my trigger Uptil now:

 

trigger Map on Lead (after Insert) 
{
    List<Id> l_Ids=new List<Id>();
    for(Lead l : Trigger.New)
    {
        l_Ids.add(l.Id);
    }
    
    List<Lead> new_Leads=[Select Id, My_Organizat ion__c FROM Lead where Id in : l_Ids];
    List<Lead> update_Leads=new List<Lead>();
    
    for( Lead l : new_Leads)
    {
        l.My_Organization__c='USA';
        update_Leads.add(l);
    }
    
    Update update_Leads;       
}

 

Thanks,

Sales4ce

Hello,

I need help with a trigger.  I am trying to assign the correct Id on a Lookup Field based on querying for a corresponding value on the related Custom Object.  Here is my trigger, but all I get is "Expression cannot be assigned at line -1 column -1".  Help would be greatly appreciated!

 

 

trigger objectConnect on Custom_Object_B__c (after insert) {

    Map<String, Custom_Object_B__c> cobMap = new Map<String, Custom_Object_B__c>();

    for (Custom_Object_B__c cob : System.Trigger.new) {
        if (cob.ID_Field__c == null) {
            cob.ID_Field__c.addError('A valid ID is required.');
        } 
        else {
            skcMap.put(cob.ID_Field__c, cob);
            }
    }

    for (Custom_Object_A__c coa : [SELECT Id, ID_Field__c FROM Custom_Object_A__c WHERE SKID__c IN :cobMap.KeySet()]) {
            Custom_Object_B__c.Look_Up_Field__c = coa.Id;
    }
}

 Anyone know what my problem is?  I have searched on the error, but have not found anyone with that same error.

 

  • April 30, 2010
  • Like
  • 0

I'm using AggregateResult in order to return sum of shipments for every combination of customeregion,productfamily and year,here is the query i'm using
apex code:
public AggregateResult[] queryResult { get {return queryResult ;} set{ queryResult = value ;} }
public AggregateResult[] getschemalist22()
{
 queryResult = [select sum(shp_4000__c) salesshipments,sum(shp_4010__c) inventoryshipments,sum(sos_5000__c) salesoutshipments,Time__r.Years__c years,
   Customer__r.Region__c regions, JaguarProduct__r.Family__c families from FACT_LL__c
   group by Time__r.Years__c, Customer__r.Region__c, JaguarProduct__r.Family__c];
 return queryResult;
}

Now i required to display this aggregateresult in my visualforce page pageblocktable like

Customerregion       Productfamily        Year          Measures                                values

ASIA                             prodfamily1             2010         salesshipments                      2000
                                                                                          inventoryshipments                340
                                                                                          salesoutshipments                1090

 

NORTH AMERICA     prodfamily1            2010         salesshipments                      6100
                                                                                          inventoryshipments                900
                                                                                          salesoutshipments                5600

 

which displays 2 records with "sum of shipments for region asia,productfamily1,year 2010" and"sum of shipments for region northamerica,productfamily1,year 2010".

 

please specify if this is the right way to get aggregateresult,if yes please let me know how to display it in visualforce page

as desired or is there any other way to display the result.

Any help is much appreciated.

 

Thanks & Regards,

Satya.

I have a working trigger on a custom object, related between Contacts and Entitlements__c, that changes the value of some contact fields, depending on a field in the Account record and a returned value in a query.  Here it is:

 

 

trigger Contact_Entitlement_Active on Contact_Entitlement__c (after insert, after update) {

	Set<Id> Ent_Ids = new Set<Id>();
        
    for (Contact_Entitlement__c ce:Trigger.new){
       Ent_Ids.add(ce.Contact__c);
       system.debug('ID: ' + ce.Id);
    }   	

	List<Contact_Entitlement__c> activeCon = [select Id from Contact_Entitlement__c where Contact__c in :Ent_Ids and Entitlement__r.Start_Date__c <= today and Entitlement__r.End_Date__c > today and Entitlement__r.Support_Program__r.Support_Type__c <> 'No Support' order by Entitlement__r.End_Date__c];
	List<Contact> userType = [select AccountId, Status__c, User_Type__c, Account.Type from Contact where Id in :Ent_Ids];

			if (!activeCon.isEmpty()) {			
				if (userType[0].Account.Type == 'Partner') {
				userType[0].User_Type__c = 'partner';
				userType[0].Status__c = 'active';
				} else {
				userType[0].User_Type__c = 'customer';
				userType[0].Status__c = 'active';
				}
			} else {
				userType[0].User_Type__c = 'inactive';
			}
			update userType;

}

 I have this test class for it to create the records, and meet the "Insert" trigger condition.

 

 

 

static testMethod void Contact_Entitlement_Active_Update() {
        
	Account testAccount = new Account(Name='Test Partner', Type='Partner');
		insert testAccount;
	Contact testContact = new Contact(LastName='TestPerson',AccountId=testAccount.Id);
		insert testContact;
	Support_Program__c testProgram = new Support_Program__c(Name='Test Program');
		insert testProgram;
	Entitlement__c testEntitlement = new Entitlement__c(Name='Test Entitlement',Support_Program__c=testProgram.Id,End_Date__c=Date.newinstance(2011,10,10),Case_Pack__c=true, Renewal_Amount__c=100, Cases_Remaining__c=100, Total_Cases__c=0);
		insert testEntitlement;
	Program_Contact__c testPContact = new Program_Contact__c(Name='Test Contact',Contact__c=testContact.Id,Support_Program__c=testProgram.Id);
		insert testPContact;
	Contact_Entitlement__c testCEnt = new Contact_Entitlement__c(Contact__c = testContact.Id,Entitlement__c = testEntitlement.Id,Program_Contact__c=testPContact.Id);
		insert testCEnt;

 

I have the Account Type set to Partner, but there is no coverage for this part of the Trigger:

 



if (!activeCon.isEmpty()) {
 if (userType[0].Account.Type == 'Partner') {
    userType[0].User_Type__c = 'partner';
    userType[0].Status__c = 'active';
    } else {
    userType[0].User_Type__c = 'customer';
    userType[0].Status__c = 'active';
  }

 I am stuck on what to do.  Any ideas?

 

We're only allowed to have 5 jobs in the queue for batch processing at a time. Ordinarily there's a method on the Limits class that allows us to get to info regarding limits, etc but I can't find one in this case. My money's on a bug in the documentation... Any help?

 

Current documentation: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_limits.htm

I'm new to Apex and I'm having a bit of a time understanding it. I'm hoping for a bit of assistance. I have a huge amount of workflow rules (+180) to handle email alerts as well as field updates. This is real messy and I really like to have an Apex trigger handle most of the work.

 

What I'm having a hard time wraping my mind around is how to do field updates. What I'm looking to do for the moment is make a simple Apex trigger that simply reads the Pick list value from a pick list that contains email addresses and then sets that value in the email field. I then can use one workflow to read that email address field and send the email. This will elimate %80 of the workflows I'm having to use on this custom object.

 

Would someone be so kind in showing me a code example specifically on how to do this? I've been searching for hours in books, online, and so forth. I know I'm asking for someone to code this and normally I know I should make an attempt, but I'm a bit lost. Thanks.

  • April 16, 2010
  • Like
  • 0

Hi:

   I want to re-create the Task Page in Visualforce and have the Whoid and what id filled in. Now, I can get this to work if I dont use the VF task page and use the standard task page. But I can not get it to work on the VF Page??/

Basically a user will click new task and it will open up this VF task page and have the whoid and whatid filled in automatically through URL. Do not know how to:

 

public PageReference Monitor(){

    moni = new List<History__c>(
            [SELECT  id,
            Student__c
            FROM History__c 
            where Student__c=:ApexPages.currentPage().getParameters().get('oppIdd')
            AND id=:ApexPages.currentPage().getParameters().get('oppIddc')
            ]);
 
    
   //PageReference newpage = new PageReference('/00T/e?who_id=' + monitorstudent[0].Student__c+ '&what_id=' + monitorstudent[0].Id + '&retURL=%2Fhome%2Fhome.jsp');
    PageReference newpage = new PageReference('/apex/Task?who_id=' + monitorstudent[0].Student__c+ '&what_id=' + monitorstudent[0].Id );

        newpage.setRedirect(true);
        return newpage; 
} 
<apex:page standardController="Task" sidebar="false">

    <apex:form >
        <apex:pageBlock title="Edit Task" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>                
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Basic Information" columns="1">
                <apex:inputField value="{!Task.Ownerid}"/>
                    <apex:pageBlockSectionItem >
                        <apex:outputLabel value="Subject"/>
                            <apex:inputField value="{!Task.Subject}"/>
                    </apex:pageBlockSectionItem>
                    <apex:inputField value="{!Task.whoid}"/>
                    <apex:inputField value="{!Task.whatid}"/>
                </apex:pageBlockSection>
            </apex:actionRegion>

        </apex:pageBlock>
    </apex:form>

</apex:page>

 

 

Please help me figure this out. Thanks

ETechCareers

hi.

 

I make a trigger to update a field on Opportunity already created when it was created a custom object "proposta__c" (related list on Opportunity)

but isnt obrigatory have one "proposta__c" associated to the opportunity.

 

When the trigger not find the "proposta__c" i want to skip. I tried with List<> but not works..

 

here's my code - with the list commented and the other.

 

Please help me

 

trigger preencherNumeroOportunidade on Opportunity (after insert, before update) {

for (Opportunity o : Trigger.new)
{

 Proposta__c p = [select Proposta_N__c, Validade_em_dias__c from Proposta__c
  where
   Oportunidade__c =:o.id AND
   Valida__c ='Sim' LIMIT 1
  
  ];
       //if(p.Proposta_N__c !=null ){
            o.N_proposta_background__c = p.Proposta_N__c; 
            o.validade_proposta_background__c = p.Validade_em_dias__c;          
       // }   
    

}}
/*trigger preencherNumeroOportunidade on Opportunity (after insert, before update, after update) {

 
 Opportunity o = new Opportunity ();
 List <Proposta__c> p = new List<Proposta__c>();
  p = [select Proposta_N__c, Validade_em_dias__c from Proposta__c
  where
   Oportunidade__c =:o.id LIMIT 1
  
  ];
  if(p.size()>0)
        {        
            o.N_proposta_background__c = p[0].Proposta_N__c; 
            
            o.validade_proposta_background__c = p[0].Validade_em_dias__c;   
             update o;       
        }    
   


}*/
I would like to add a custom field to a Product object which will summarize the last time the product was ordered.

The 'obvious' way to do this would have been to make Product the master to an object called "Label Order", and then use a roll-up field on "Product".

However, it seems [for some unknown reason] that I can't make Product the Master.

Is this normal? Am I doing something wrong?

Is there a workaround so I can create the "Last_Label_Order" as a formula if Product is a LookUp for "Label Order"?

I have tried using readOnly on a selectCheckBoxes


IE

 

<apex:selectCheckboxes value="{!defaultValue}" readOnly="true"> <apex:selectOptions value="{!possiblevalues}"/> </apex:selectCheckboxes>

 

Doesn't appear to do anything.

 

Seems simple enough but no joy.

 

Work for anyone?

Hi. Long time reader, first time poster. I am having a problem associating a contact object with an account object in my custom controller extension. I have two objects, a contact and an account. I am creating a new contact and want it associated with the active account. When the contact gets inserted, it has all of the correct information (name, phone, ect.), but the account field is empty. I've posted the insert function here. Any help is appreciated.

 

 

public pagereference savecontact(){ my_obj.c.account = my_obj.a; insert my_obj.c; return page.MyPagePG2; }

 

Hi Can we show a lookup relationship in a Visual Force Page.

 

 

Hello

I have written a trigger that sends an email when a lead is updated. However I only want the email to be sent when a lead is created using a visualforce page not when a lead is created directly form salesforce. Currently, the trigger is selecting the last created lead not necessarily the lead created using the page. How can I limit the trigger so that it only sends using the vf page and not the interface? Or, do I have to send the email using a different method?

Trigger

 

trigger mhform on Lead (after insert) { Messaging.SingleEmailMessage mail= new Messaging.SingleEmailMessage(); String[] toAddresses = new String[]{'margiro@piab.com'}; Lead lead = [SELECT Id from Lead Order by Lead.createdDate Desc limit 1]; mail.setToAddresses(toAddresses); mail.setTemplateId('00X400000016by4'); mail.setTargetObjectId(lead.Id); mail.setReplyTo('support@acme.com'); mail.setSenderDisplayName('Piab Support'); mail.setSaveAsActivity(false); mail.setBccSender(false); mail.setUseSignature(false); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail}); }

 


 

I am working on History Tracking for one of my custom object and want it to be displayed in a customized fashion. I made two page blocks; 1st page block displays the items in grid with a link in first column as History (rerendered the 2nd page block on its click). In 2nd page block I created a Apex:pageBlockTable to display CreatedBy, CreatedDate, Field, OldValue, NewValue. This 2nd page block displays the History respective to the item clicked in the 1st page block.

 

Problem:

Everything works as supposed only when I exclude the Field column. If I put the field column in my 2nd page block, pageblock is not refreshed and nothing is displayed.

<apex:form id="pixelReqForm"> <apex:pageBlock title="Pixel Request Form (PRF)" id="PixReqForm"><br></br> <apex:pageBlockTable value="{!PixelReq}" var="aPixelReq" id="pixelReqTable"> <apex:column headerValue="History" id="hisTrack"> <apex:commandLink value="History" reRender="pixelReqHisTable"> <apex:param name="pixelReqID" value="{!aPixelReq.id}"/> </apex:commandLink> </apex:column> <apex:column headerValue="Delete" id="isDeleteColumn"> <apex:inputCheckbox value="{!aPixelReq.isDeleted__c}" id="isDelete"/> </apex:column> <apex:column headerValue="Agency"> <apex:inputField value="{!aPixelReq.Agency__c}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> <apex:pageBlock title="Pixel Request Form (PRF)" id="pixelReqHistBlock"><br></br> <apex:pageBlockTable value="{!PixReqHistory}" var="aHistory" id="pixelReqHisTable"> <apex:column headerValue="Created By" id="createdBy"> <apex:outputField value="{!aHistory.CreatedById}"/> </apex:column> <apex:column headerValue="Changed Field" id="changedField"> <apex:outputField value="{!aHistory.FIELD}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> <apex:pageBlock title="PRF History Tracking" id="histIFrame"> </apex:form> </apex:page> =============================== Controller: ... List <PixelReqForm__History> pixReqHist; public List<PixelReqForm__History> getPixReqHistory() { pixReqHist = [Select Id, IsDeleted, ParentId, CreatedById, CreatedDate, Field, OldValue, NewValue FROM PixelReqForm__History where PARENTID = :ApexPages.currentPage().getParameters().get('pixelReqID') order by createdDate desc]; return pixReqHist; } ...

 

 

Regards,
Rao

Hi ,

I am facing an issue with Campaign Member Status Update Date. Though this is available on SF Reports, I am unable to find equivalent field on eclipse schema. any help will be appreciated.

Please contact at sforce2009@gmail.com... Please visit www.trekbin.com to download our brouchure.
Is there anyway to ignore the accentuated characters in the LIKE operator of a select query?

Is there any one who knows how to use setContentType for Meeting Invites when we send an Email with EmailFileAttachment.

 

Much appreciated

I am a Salesforce developer with 5 years of development exp and 3 years on Salesforce.com. For further details please

contact me at sforce2009@gmail.com

Message Edited by sforce2009 on 09-22-2009 06:43 AM
Message Edited by sforce2009 on 09-23-2009 12:11 AM

This is post is related to my previous post.

        What is happening here is, i am using google calendar api in my visual force page. when i connect to the google calendar for hosted domain using gdata's Authsubutil classes, I am able to login and get the GRANT Access and DENY ACESS page. There it is showing the return URL also perfect. but when i click on Grant Access button it is redirecting back and throwing a null object ref error. on lines related to google feeds and Calendar Service object creation. Or it simply says the visual force page used in Return URL simply does not exist. 

 

Please Help.

 

RON HESS: i hope you can understand my problem Please advise some solution. i am available on skype 'v2_srinivas'

Hi

     I am using google api toolkit to connect to the google calendar and create events there according to the events created in my salesforce account.

     But now, i need to connect to google apps calendar instead of normal gmail which i am doing with this function AuthSubUtil.getRequestPageReference().

     How do i do that. please help....

 

I am trying to use a child-to-parent relationship to obain a Name value from the parent object on a "new" VisualForce page.

 

The child object is Data_Transaction__c and the parent object is Data_Activity__c.

 

The field Data_Activity__c is selected by a user and triggers a rerendering of the page. I then need to use the value of Data_Transaction__c.Data_Activity__r.Name as criteria for rendering the portion of the page appropriate for the selected Data Activity. Problem is Data_Transaction__c.Data_Activity__r.Name is null because the record is not actually saved yet. If I try to use just Data_Transaction__c.Data_Activity__c, it evaluates to the 18 character Id of the selected Data_Activity__c object.

 

Any suggestions on an alternative approach? Code sample below.

 

 

 

<apex:page standardController="Data_Transaction__c"  sidebar="false" id="thePage">

  <apex:sectionHeader title="Data Transaction Edit"subtitle="New Data Transaction"/>

  <apex:form id="theForm">

    <apex:pageBlock title="Data Transaction Edit" id="thePageBlock"mode="edit">

      <apex:pageMessages rendered="false"/>

      <apex:pageBlockButtons >

        <apex:commandButton value="Save" action="{!save}"/>

        <apex:commandButton value="Cancel" action="{!cancel}"/>

      </apex:pageBlockButtons>

      <apex:actionRegion >

        <apex:pageBlockSection title="Data Transaction Information"columns="1">

          <apex:outputField value="{!Data_Transaction__c.Production_Number__c}"/>

          <apex:pageBlockSectionItem >

            <apex:outputLabel value="Activity Type"/>

            <apex:outputPanel >

              <apex:inputField value="{!Data_Transaction__c.Data_Activity__c}">

                <apex:actionSupport event="onchange"

                                    rerender="thePanel"

                                    status="status"/>

              </apex:inputField>

 

              <apex:actionStatus startText="     Updating..."

                                 id="status"/>

            </apex:outputPanel>

          </apex:pageBlockSectionItem>

         </apex:pageBlockSection>

      </apex:actionRegion>

      <apex:outputPanel id="thePanel">

      <apex:pageBlockSection title="Mortgage Details" columns="1" rendered="{!Data_Transaction__c.Data_Activity__r.Name == 'Mortgage'}">

        <apex:inputField value="{!Data_Transaction__c.AS400__c}" rendered="{!Data_Transaction__c.Transaction_Type__c == 'Completed Work'}"/>   

        <apex:inputField value="{!Data_Transaction__c.HDES__c}" rendered="{!Data_Transaction__c.Transaction_Type__c == 'Completed Work'}"/>

        <apex:inputField value="{!Data_Transaction__c.Not_Processed__c}" rendered="{!Data_Transaction__c.Transaction_Type__c == 'Completed Work'}" label="Canceled"/>

        <apex:inputField value="{!Data_Transaction__c.Items__c}" required="true"/>              

        <apex:inputField value="{!Data_Transaction__c.Hours__c}" required="{!Data_Transaction__c.Transaction_Type__c == 'Completed Work'}" rendered="{!Data_Transaction__c.Transaction_Type__c == 'Completed Work'}"/>

      </apex:pageBlockSection>

 

Dont think that this is an easy question.

I cant split a string. This is not a regexp issue. It just doesnt work.

 

Heres my scenario, my code sends request to external service which return | delimited string. When I try to split the string it gives 1 part. I have experimented a little and hard coded the return string into my function by copying from debug log and it worked. I have tried to use another string variable and set it to the value of the parameter, no luck.

 

 

I am using the method documented in various posts to pre-populate default values in a standard page for a custom object.  i.e. I when the user wants to create a new record for the object, I generate this URL in Apex:

 

https://na7.salesforce.com/a0G/e?00NA0000003UhJ8=2010

 

This will open up the standard new screen for a custom object (page name = aOG) and in a year field put in 2010 (field id = 00NA0000003UhJ8)

 

This works fine, however, if I move the code to a new org, the page name and field ID will be different.

 

Does anybody know if there is a way to dynamically figure out the page name for a custom object and a field id for a field so I can programmatically figure out the appropriate URL vs hard coding it)? 

Good day, 

 

I would like to query some account which are filter by multiple criterias, not sure how can i do it 

 

 

SELECT ID FROM Account
WHERE id not in (select ...)
AND   id not in (select ....)
AND   id not in (select ...)
AND   id not in (select .....)

 and i got the error like Maximum 2 semi-join sub-select are allow , anyone can enlighten me is this a limitation of SOQL ?

 

Thank you !

 

I was trying to add a custom link of LinkedIn from the accounts page. I have been able to add the LinkedIn link but when I click on it from an account page it is not taking me directly to the company's profile but brings me to the login page of LinkedIn. Any suggestions would be greatly appreciated.

 

Sue

I need to set a query parameter in a test method.  The documentation makes only a quick reference to this, saying:

To set a query string parameter:

  • If you're writing a custom controller, use the setParameters() method with ApexPages.currentPage() to add a query parameter in a test method. For example:
    String key = 'name';
    String value = 'Caroline';
    ApexPages.currentPage().setParameters().put(key, value);
    Note
     The setParameters() method is only valid inside test methods.

However, when I put this in my test method, I get the error:

 

Save error: Method does not exist or incorrect signature: [System.PageReference].setParameters()    Testm62ConsoleController.cls    /m62 Sandbox/src/classes    line 80    Force.com save problem

 

Here is my test method:

 

 static testMethod void testConsoleController() {

		// Find a telesales user for the tests
        Profile p = [select id from profile where name='Telesales']; 
        User u = new User(alias = 'standt', email='standarduser@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', profileid = p.Id, 
            languagelocalekey='en_US', 
            localesidkey='en_GB', 
            timezonesidkey='Europe/London',
            username='standarduser@testorg.com');


        System.runAs(u) {
         		
		//Set up the data
		List<Account> accs = new List<Account>();
		for (Integer i=0; i<50; i++) {
			Account a = new Account(
				Name = 'Test Account 1',
				BillingCountry = 'United Kingdom',
				Phone = '+44 (0)12679 121 5555',
				To_be_cleansed__c = true
			);
			accs.add(a);
		}
		insert accs;
		
		List<Contact> conts = new List<Contact>();
		List<Task> tasks = new List<Task>();
		// Create two contacts for each account
		for (Integer i=0; i<50; i++) {
			Contact c = new Contact();
			c.FirstName = 'Test';
			c.LastName = 'Contact 1';
			c.AccountId = accs[i].Id;
			c.MailingCountry = 'United Kingdom';
			c.Email = 'no@email11111.com';
			c.Phone = '+44 (0)1423 564888';
			conts.add(c);
		
			Contact c1 = new Contact();
			c1.FirstName = 'Test';
			c1.LastName = 'Contact 1';
			c1.AccountId = accs[i].Id;
			c1.MailingCountry = 'United Kingdom';
			c1.Email = 'no2@email11111.com';
			c1.Phone = '+32 (0) 2 679 12 11';
			conts.add(c1);
			
			// Add a task for each account
			Task t = new Task(WhatId=accs[i].Id, Type='Telephone call', Subject='Test subject', Status='Not started', 
            				Priority='Normal'); 
            tasks.add(t);
		}
	
		insert conts;
		insert tasks;
		
        PageReference pageRef = Page.newConsole;  // Instantiate telesales console page
        Test.setCurrentPage(pageRef);
      
        //Instantiate and construct the controller class.   
        m62ConsoleController controller = new m62ConsoleController();		
		Test.startTest();
		
		controller.selectedAcc = accs[4];
		controller.last();
		if (controller.getHasPreviousAcc()) controller.previousAcc();
		if (controller.getHasNextAcc()) controller.nextAcc();
		
		controller.getMyAccounts();
		controller.first();
		String ids = accs[6].Id;
		ApexPages.currentPage().setParameters().put('AccSel', ids);

		ids = conts[12].Id;
		ApexPages.currentPage().setParameters().put('ConSel', ids);

		controller.resetConts();
		controller.viewCont();
		controller.resetTsks();
		controller.viewTsk();
		
	}
    }

 Can anyone advise what I'm doing wrong? I've searched all over for more information but can't find any.

Thanks.

 

How to truncate the timestamp from the date object so that the return type is again a valid date which has to be passed to a query to get the result from database.Since in database it is stored without timestamp.

Hi.

 

Created a Custom Object A.

The Custom Object A  having text fields and also look-up fields.

 

Then created a VF called testpage.

 

I need to use the Custom Object  A's Page-layout in testpage.

To say simply  I don't need to again re-create the all text fields in the testpage.

I need to insert records to the custom object A using the testpage.

 

Really appreciate for your great ideas.

 

cheers

suresh

 

I'm using the following javascript to invoke a new task for the primary contact (a custom lookup field on the Account object). The task is created just fine with the primary contact in the Contact field, but upon saving, it returns to the home page instead of the account page from which it was called. Any suggestions that would redirect this to the account page?

 

navigateToUrl('/00T/e?who_id={!Account.Primary_Contact_Lookup__c}&amp;retURL=%2F{!Account.Id}');

 

Thanks.

I'm trying to pull the set of records that are child cases of another case (they reference the parent case through the "Parent" standard field) in one query.  I can't seem to find an __r field name for this though.  I'd like to be able to do this:

 

[select Id, (select Id, Report_Status__c from Case.Parent__r) from Case where Id in :referencedWorkOrders]

 

But Parent__r is not recognized, and I'm unable to find anything about what the field name might be in our Enterprise WSDL, or by using the Apex Explorer.

 

Is this possible?  Is it not supported because the lookup from Child Cases to Parent Cases is between records of the same object?  Anyone have any other ideas for how to do this (in one query)?

 

Thanks!

Hi Guys,

 

I have a visual force page which will have a lookup field and needs to be prepopulated with the parents id when ever the page is called , We are able to do it by passind the parents(lookup) id , name as query string with the lookups field id .

 

But the problem is when we move the code to other org, the field id wont be the same and the lookup is not getting prepopulated.  Is there any better approach for this.

 

 

I imported some WSDL to get stubs and wrote a class that successfully class them when testing interactively.

 

I'm now writing Apex tests and my first test that calls Apex methods that will eventually get into methods that do callouts is failing with an exception. 

 

Are the any specific techniques that are needed to get Apex test methods to run when callouts are invoked?

 

 

Hi guys.

 

Bit of a conundrum here...

 

I've got a VF page that has an inputText field that users use to scan in barcodes using a handheld barcode scanner.

The barcode scanner merely act like a keyboard: it translates the scan to keys, then types those keys and hits enter.

 

What I'd like to do, is have users scan a barcode, then conduct an apex query. If the results are good, it updates a record, if the results are bad - it throws a pageMessage.

 

I got some JS that checks when the enter key is hit, and then I envoke the apex. However, there seems to be an issue with the sequence of reRendering and apex, and JS.

 

When I do the scan into the input field - the page does a refresh - but the apex:PageMessage that should display does not...

 

Here's what I have so far:

 

 

<apex:page standardController="terminalPrepOrder__c" extensions="terminalPrepOrderController" >
<apex:variable var="prp" value="{!terminalPrepOrder__c}"/>

function checkEnter(e){ <!-- e is event object passed from function invocation -->
var characterCode <!--literal character code will be stored in this variable -->

if(e && e.which){ <!--if which property of event object is supported (NN4) -->
e = e
characterCode = e.which <!-- character code is contained in NN4's which property -->
}
else{
e = event
characterCode = e.keyCode <!-- character code is contained in IE's keyCode property -->
}

if(characterCode == 13){ <!-- if generated character code is equal to ascii 13 (if enter key) -->
alert("clicked enter");
otherFindTerminal(); <!-- submit the form -->
return false;
}
else{
return true
}
}
</script>

<apex:pageMessages id="msgs"/>
<apex:form id="theForm"> <apex:actionFunction name="findTerminal" action="{!otherFindTerminal}" reRender="msgs"/> <apex:outputText value="Scan Terminal Barcode "/> <apex:inputText value="{!searchBarcode}" onkeypress="checkEnter(event)"/> <apex:commandButton value="Find" action="{!otherFindTerminal}" id="hitMe" reRender="msgs"/> </apex:form>

 Controller:

 

	public PageReference otherFindTerminal() {  
        try {
            if (searchBarcode != '') {
              terminal__c enteredTrm = [select Id from Terminal__c T where T.barcodeNumber__c = :searchBarcode limit 1];        
           
             terminalPrepOrder__c trmPrp = (terminalPrepOrder__c) controller.getRecord();
           
             trmPrp.Terminal__c = enteredTrm.Id;
             update trmPrp;
            }
            else if (searchBarcode == '' ) {
                ApexPages.Message invalidSearch = new ApexPages.Message(ApexPages.Severity.ERROR, 'Invalid barcode.');
                ApexPages.addMessage(invalidSearch);
            }
        }
        catch (exception e) {
        
            ApexPages.Message noTrm = new ApexPages.Message(ApexPages.Severity.ERROR, searchBarcode + ' not found. Please enter the Terminal barcode.');
            ApexPages.addMessage(noTrm);
        }
        return null;
    }

 

 

 

So when I click the commandButton - it functions perfectly - It does the query, and rerenders the messages...

 

When I use the input field and hit enter... it refreshes the page but does nothing...

 

 

Please help!

Thanks

  • May 10, 2010
  • Like
  • 0
Hai all, I have a command link defined in a visualforce page.On clicking that,I want the value to be filled in a text area which is another visualforce page.Can anyone help me to this?

Hi:

   I want to re-create the Task Page in Visualforce and have the Whoid and what id filled in. Now, I can get this to work if I dont use the VF task page and use the standard task page. But I can not get it to work on the VF Page??/

Basically a user will click new task and it will open up this VF task page and have the whoid and whatid filled in automatically through URL. Do not know how to:

 

public PageReference Monitor(){

    moni = new List<History__c>(
            [SELECT  id,
            Student__c
            FROM History__c 
            where Student__c=:ApexPages.currentPage().getParameters().get('oppIdd')
            AND id=:ApexPages.currentPage().getParameters().get('oppIddc')
            ]);
 
    
   //PageReference newpage = new PageReference('/00T/e?who_id=' + monitorstudent[0].Student__c+ '&what_id=' + monitorstudent[0].Id + '&retURL=%2Fhome%2Fhome.jsp');
    PageReference newpage = new PageReference('/apex/Task?who_id=' + monitorstudent[0].Student__c+ '&what_id=' + monitorstudent[0].Id );

        newpage.setRedirect(true);
        return newpage; 
} 
<apex:page standardController="Task" sidebar="false">

    <apex:form >
        <apex:pageBlock title="Edit Task" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>                
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Basic Information" columns="1">
                <apex:inputField value="{!Task.Ownerid}"/>
                    <apex:pageBlockSectionItem >
                        <apex:outputLabel value="Subject"/>
                            <apex:inputField value="{!Task.Subject}"/>
                    </apex:pageBlockSectionItem>
                    <apex:inputField value="{!Task.whoid}"/>
                    <apex:inputField value="{!Task.whatid}"/>
                </apex:pageBlockSection>
            </apex:actionRegion>

        </apex:pageBlock>
    </apex:form>

</apex:page>

 

 

Please help me figure this out. Thanks

ETechCareers

Hi All,

 

I have below test Visualforce page , in which i am trying to call onclick event for tab but it not working.

 

Can someone help me ..

 

code//

 

 

<apex:page standardController="Account" ><head> <script language="javascript"> function setfirst() { alert("first"); } function setsecond() { alert("second"); } </script></head> <apex:tabPanel switchType="client" selectedTab="tabdetails" id="tabPanel"> <apex:tab label="General" name="General" id="tabGeneral" onclick="setfirst()"> </apex:tab> <apex:tab label="Professional" name="Professional" id="tabProfessional" onclick="setsecond()"> </apex:tab> </apex:tabPanel></apex:page>

 

Regards,

Deepak